Skip to content
Advertisement

Checking for different columns OR empty result PostgreSQL

I’m writing some query tests for dbt and I’d like to check that two queries return the same thing and that neither is empty. Since it’s a dbt test, I need to return a row if either of these conditions is false. So far I’ve come up with the following:

Theoretically, this should return a row with 1 if either query is empty and if neither are then it should return any columns that don’t belong to BOTH queries. When only query1 is empty or only query 2 is empty this works but if both are empty then it returns an empty table instead of 1. My hunch is that it’s something to do with the JOIN but I really don’t know enough about SQL to figure out why that’s affecting the original queries.

EDIT: Adding examples

No different rows

Different rows

Either table empty

Advertisement

Answer

I propose that the query returns a value like 0 in case any of the tables is empty because this can be distinguished form a valid id value of 1.

So, use UNION ALL for this case and check with EXISTS if any of the tables is empty:

Note that for the sample data you posted you don’t really need the CTEs because you can select directly from the tables.

See the demo.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement