Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.
    select ( select count(*) from Table1 )
         + ( select count(*) from Table2 ) 
            as total_rows
     from my_one_row_table
     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.



Thanks for your registration, follow us on our social networks to keep up-to-date