Search code examples
databasepostgresqlpgadmin

How to count the the data of specific two columns of different table in PostgreSQL?


I have two tables exactly having same column name but having different data or values. Now I want to count the total number of data of first column of table_1 union data of first column of table_2. How to do this?

____________________                ________________________
|    Table_1        |               |     Table_2           |
---------+----------                -----------+------------|
|arsc_lvl| Dist Name|               | arsc_lvl | Dist_Name  |
---------+----------                -----------+------------| 
|1       | Banke    |               | 5        | Bara       | 
|5       | Banke    |               | 7        | Bara       |
|6       | Bara     |               | 9        | Bara       |
---------+----------+               -----------+------------+ 

select count  ("arsc_lvl")
from "Table_1", "Table_2"
where
"arsc_lvl"<=10

this also did not provide me what I want.

I even used joins like this:

SELECT *
FROM [MyTable] Table_1
    INNER JOIN [MyOtherTable] Table_2
        ON Table_1."arsc_lv" = Table_2."arsc_lv"

It too didn't work for me. I got stuck here, please help.


Solution

  • You want to count the number of rows in the union, so translate it into SQL:

    SELECT count(*)
    FROM (SELECT * FROM table_1
          UNION
          SELECT * FROM table_2) u;
    

    If you don't want to eliminate duplicates, use UNION ALL instead of UNION.