Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the difference between results of two count(*) queries based on 2 tables in PostgreSQL

Tags:

sql

postgresql

I want to calculate the difference between the results of 2 count(*)-type SELECT queries executed on 2 separate tables of my PostgreSQL database.

This what I'm currently using (however I should be able to wrap it all up into a single SELECT statement):

SELECT "count"(*) AS val1 FROM tab1; SELECT "count"(*) AS val2 FROM tab2; SELECT val2-val1; 

Thanks in advance

like image 827
Ucef Avatar asked Feb 11 '14 11:02

Ucef


People also ask

How do I find the difference between two tables in postgresql?

SELECT * FROM tbl1 FULL OUTER JOIN tbl2 USING (col) WHERE tbl2 col IS NULL OR tbl1. col IS NULL; Overview over basic techniques in a later post: Select rows which are not present in other table.

How do you find the difference between two query results in SQL?

The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query.

How do you find the difference between two fields in SQL?

To calculate the difference between two dates in different columns, we use the two columns createdDate and LastLogin of the registration table and apply the DATEDIFF function on these columns. To find the difference between the two dates in different columns, we need two dates from the different columns.

What is the difference between count and distinct count?

COUNT(column_name) will include duplicate values when counting. In contrast, COUNT (DISTINCT column_name) will count only distinct (unique) rows in the defined column.


2 Answers

Try this way:

select    (     SELECT        "count"(*) as val1      from        tab1   ) - (     SELECT        "count"(*) as val2      from        tab2   ) as total_count 
like image 148
Robert Avatar answered Oct 19 '22 02:10

Robert


for same table you can do this.

select (count(abc)-count(DISTINCT xyz)) from tab;

like image 22
Aditya Tomar Avatar answered Oct 19 '22 02:10

Aditya Tomar