SQL 2023 cheatsheet

SQL 2023: Querying

10 common SQL 2023 tasks.

Select columns

Choose the columns to return. Avoid SELECT * in application code.

SELECT id, name, email FROM users;

Filter rows

Return only rows that match a condition.

SELECT * FROM users WHERE active = true AND age >= 18;

Sort and limit

Return the 10 newest rows. SQL Server uses TOP and Oracle uses FETCH FIRST.

SELECT * FROM posts ORDER BY created_at DESC LIMIT 10;

Paginate results

Skip 20 rows and return the next 10. Large offsets get slow, so prefer keyset pagination.

SELECT * FROM posts ORDER BY id LIMIT 10 OFFSET 20;

Remove duplicates

Return each distinct value once.

SELECT DISTINCT country FROM customers;

Match text patterns

Find names that start with Ad. % matches any characters and _ matches one.

SELECT * FROM users WHERE name LIKE 'Ad%';

Match a list or a range

Use IN for a list of values and BETWEEN for an inclusive range.

SELECT * FROM orders WHERE status IN ('paid', 'shipped') AND total BETWEEN 50 AND 200;

Check for NULL

Compare with IS NULL, because = NULL is never true.

SELECT * FROM users WHERE deleted_at IS NULL;

Branch inside a query

Compute a value conditionally.

SELECT name, CASE WHEN age >= 18 THEN 'adult' ELSE 'minor' END AS group_name FROM users;

Replace NULL with a default

Return the first value that isn't NULL.

SELECT COALESCE(nickname, name) AS display_name FROM users;

Was this page helpful?