Skip to main content
Albero Academy

SQL Cheat Sheet

Queries · Joins · Windows

SELECT/WHERE/JOINs, window functions, CTEs, indexes, common patterns and an interview-prep query bank — all on one card.

All sheets
PDF quick reference

SQLCheat sheet

Sections
6
Snippets
12
Pages
2
01

SELECT basics

Filtering & sorting
SELECT name, salary
FROM employees
WHERE department = 'Engineering'
ORDER BY salary DESC
LIMIT 10;
Aggregates
SELECT department,
AVG(salary) AS avg_salary,
COUNT(*) AS headcount
FROM employees
GROUP BY department
HAVING COUNT(*) >= 5;
02

JOINs

INNER JOIN
SELECT o.id, c.name
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id;
LEFT JOIN with NULL filter
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL; -- customers with no orders
03

CTEs

Single CTE
WITH top_products AS (
SELECT product_id, SUM(quantity) AS qty
FROM order_items
GROUP BY product_id
ORDER BY qty DESC
LIMIT 10
)
SELECT * FROM top_products;
04

Window functions

Running total
SELECT order_date,
amount,
SUM(amount) OVER (
ORDER BY order_date
) AS running_total
FROM orders;
Rank within group
SELECT name, salary,
RANK() OVER (
PARTITION BY department
ORDER BY salary DESC
) AS rk
FROM employees;
LEAD / LAG
SELECT user_id, login_at,
LAG(login_at) OVER (
PARTITION BY user_id
ORDER BY login_at
) AS prev_login
FROM logins;
05

Indexes & performance

Create / use index
CREATE INDEX idx_orders_user
ON orders(user_id);
-- queries that filter on user_id will use it automatically
EXPLAIN
EXPLAIN ANALYZE
SELECT * FROM orders
WHERE user_id = 42;
06

Interview classics

2nd highest salary
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
Find duplicates
SELECT email, COUNT(*) c
FROM users
GROUP BY email
HAVING COUNT(*) > 1;