Select count(*) from multiple tables
Question
How can I select count(*)
from two different tables (call them tab1
and tab2
) having as result:
Count_1 Count_2
123 456
I've tried this:
select count(*) Count_1 from schema.tab1 union all select count(*) Count_2 from schema.tab2
But all I have is:
Count_1
123
456
Answer1
SELECT (
SELECT COUNT(*)
FROM tab1
) AS count1,
(
SELECT COUNT(*)
FROM tab2
) AS count2
FROM dual
Comments
- why do you need dual? what does that mean?
- It's a fake table with one record. You can't have SELECT without FROM in Oracle.
Answer2
As additional information, to accomplish same thing in SQL Server, you just need to remove the "FROM dual" part of the query.
Answer3
Just because it's slightly different:
SELECT 'table_1' AS table_name, COUNT(*) FROM table_1
UNION
SELECT 'table_2' AS table_name, COUNT(*) FROM table_2
UNION
SELECT 'table_3' AS table_name, COUNT(*) FROM table_3
It gives the answers transposed (one row per table instead of one column), otherwise I don't think it's much different. I think performance-wise they should be equivalent.
Answer4
My experience is with SQL Server, but could you do:
select (select count(*) from table1) as count1,
(select count(*) from table2) as count2
In SQL Server I get the result you are after.
Answer5
Other slightly different methods:
with t1_count as (select count(*) c1 from t1),
t2_count as (select count(*) c2 from t2)
select c1,
c2
from t1_count,
t2_count
/
select c1,
c2
from (select count(*) c1 from t1) t1_count,
(select count(*) c2 from t2) t2_count
/
The content is from StackOverflow which is translated and used in accordance with the CCBY-SA 4.0 license agreement. Original link: Select count(*) from multiple tables
There is no comment, let's add the first one.