SQL 2023 cheatsheet

SQL 2023: Joins and combining queries

7 common SQL 2023 tasks.

Join two tables

Return rows that have a match in both tables.

SELECT o.id, u.name FROM orders o JOIN users u ON u.id = o.user_id;

Keep rows without a match

Return all users, with NULL order columns for users who have no orders.

SELECT u.name, o.id FROM users u LEFT JOIN orders o ON o.user_id = u.id;

Find rows with no match

Return users who have never placed an order.

SELECT u.* FROM users u LEFT JOIN orders o ON o.user_id = u.id WHERE o.id IS NULL;

Check that related rows exist

Return users that have at least one order. EXISTS stops at the first match.

SELECT * FROM users u WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);

Filter with a subquery

Use one query's result inside another.

SELECT * FROM products WHERE price > (SELECT AVG(price) FROM products);

Stack two result sets

Combine rows from two queries and remove duplicates. UNION ALL keeps duplicates and is faster.

SELECT email FROM customers UNION SELECT email FROM leads;

Name a subquery with a CTE

Break a query into readable steps.

WITH recent AS (
  SELECT * FROM orders WHERE created_at > CURRENT_DATE - 30
)
SELECT user_id, COUNT(*) FROM recent GROUP BY user_id;

Was this page helpful?