Correlated vs uncorrelated subqueries

A subquery is a query that is used in another query.

SELECT * FROM (SELECT * FROM tableA)

--Outer query: SELECT * FROM 
--Sub query: (SELECT * FROM tableA) 

Another example of subqueries can be as simple as the example below.

SELECT 
		(SELECT COUNT(*) FROM tableA), -- Subquery 1
		(SELECT COUNT(*) FROM tableB)  -- Subquery 2

A correlated subquery is a subquery where a reference is made to the outer query.

SELECT * FROM tableB
	WHERE EXISTS (SELECT 1 FROM tableA WHERE tableB.column1 = tableA.column2) 
-- A column from the outer query with tableB is used in the subquery

An uncorrelated subquery is a subquery where no reference is made to the outer query.

SELECT * FROM tableB
WHERE tableB.column1 = (SELECT MAX(tableA.column2) FROM tableA)
-- No columns from the outer query with tableA are used in the subquery

For the record, in Snowflake you can get away with not giving your subquery an alias, while SQL Server will give you a hard time about it. 

For the recordest, I am not a big fan of subqueries, I find that Common Table Expressions (CTEs) make queries easier to read in most cases. Also, CTEs are reusable. However, you do find these subqueries a lot in the wild so I find it nice to at least know what they are.

Leave Comment

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *