Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: SQL
Expertise: Beginner
Apr 25, 2006

Count the Number of Rows in Two Tables Using a Single Query

There are several ways to simply count the number of rows in two tables using single query.
  1. 
    
    select ( select count(*) from Table1 )
         + ( select count(*) from Table2 ) 
            as total_rows
     from my_one_row_table
    
    
  2. 
     select sum(rows)
              as total_rows
      from (
        select count(*) as rows
          from Table1
        union all
        select count(*) as rows
          from Table2
           ) as u 
    
    UNION ALL is necessary here, not UNION, to guard against the case when both tables have the same number of rows, because UNION would discard one of the duplicate counts! Note also that no GROUP BY is necessary in the main query, because all the rows (produced by the UNION ALL subquery) are considered one group.
  3. We could also use a CROSS JOIN:
    
       select t1.rows + t2.rows  
              as total_rows
        from (
               select count(*) as rows
               from Table1
             ) as t1
        cross join (
                select count(*) as rows
                from Table2
                   ) as t2 
     
    The cross join works because each derived table has only one row.
Sanjay Agarwal
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap