I have a requirement. I need to take count of same tables from two different schema. The required output should be like (see screenshot here)
schema | table_name | count |
---|---|---|
sch1 | table1 | 1000 |
sch2 | table1 | 500 |
sch1 | table2 | 3000 |
sch2 | table2 | 1000 |
this is to take count difference of table from schema1 and schema2. so i get an output in above fashion i can use LAG() or LEAD function. Please help
I tried many ways. But all result I’m getting related to group by usage only which will not maintain the expected fashion.
2
Answers
Probably the most straightforward way of doing this is by making
UNION ALL
of 4 subqueries, each retrieving your counts from your four tables.When the list of tables cannot be hard-coded (say you need to iterate on
information_schema.tables
), dynamic SQL must be used. For each table, a query must be generated, and then executed in a second step.You may use this function to generate and execute the row count of a given table:
Then use it in the following query to get in a single result set all row counts of tables that exist with the same name in multiple schemas: