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

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.

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of