Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find total records in various tables in a single query

Currently I m using this query ,Is there any substitution for this query,which will work more faster .

SELECT 
    SUM(result1),
    SUM(result2),
    SUM(result3)
FROM (
    (
        SELECT 
            0 as result1,0 as result2,COUNT(*) as result3
        FROM 
            table1
    )
    UNION
    (
        SELECT 
            count(*) as result1,0 as result2,0 as result3
        FROM 
         table2
    )
    UNION
    (
        SELECT 
            0 as result1,count(*) as result2,0 as result3
        FROM 
            table3
    )
    ) as allresult
like image 506
nitish koundade Avatar asked Dec 22 '15 12:12

nitish koundade


People also ask

How can I count rows from multiple tables in SQL?

If you are looking to do this yourself. You need to do the following: Use SELECT COUNT (*) on each table to have its rowed total. Use UNION ALL to build a result of the row count of each table.

Can we show data from multiple tables with one query?

There are many ways to display data from more than one table. You can join tables or views by a common column. You can also merge data from two or more tables or views into a single column or create a subquery to retrieve data from several tables. You can use a SELECT statement to join columns in two or more tables.


2 Answers

Alternate solution of above query is as below:

SELECT (SELECT COUNT(1) FROM table2) AS result1, 
       (SELECT COUNT(1) FROM table3) AS result2, 
       (SELECT COUNT(1) FROM table1) AS result3;
like image 91
Saharsh Shah Avatar answered Sep 26 '22 14:09

Saharsh Shah


Add the table names in the WHERE clause and execute the below query:

SELECT 
    T.Name AS TableName,
    S.Row_count AS RecordsCount
FROM 
    sys.dm_db_partition_stats S
INNER JOIN sys.tables T ON T.object_id = S.object_id
Where 
    Object_Name(S.Object_Id) IN ('Employees','Country')
like image 27
Bala Sakthis Avatar answered Sep 26 '22 14:09

Bala Sakthis