Bookmark this page
Press Ctrl+D (Windows) or Cmd+D (Mac) to bookmark this page.
🗄 SQL

SQL Cheat Sheet

Common SQL patterns for selecting, filtering, joining, grouping and updating rows.

SELECT and WHEREJOIN typesGROUP BY + aggregatesINSERT / UPDATE / DELETE

Select and filter

SELECT id, name
FROM users
WHERE active = 1
ORDER BY created_at DESC
LIMIT 20;

Join tables

SELECT o.id, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
LEFT JOIN coupons cp ON cp.id = o.coupon_id;

Group and aggregate

SELECT category, COUNT(*) AS total, AVG(price) AS avg_price
FROM products
GROUP BY category
HAVING COUNT(*) > 5;

Write data

INSERT INTO users (name, email) VALUES ('Alex', 'a@example.com');
UPDATE users SET active = 0 WHERE last_login < '2025-01-01';
DELETE FROM users WHERE id = 10;

CTEs and transactions

WITH recent_orders AS (
  SELECT customer_id, total
  FROM orders
  WHERE created_at >= '2025-01-01'
)
SELECT customer_id, SUM(total) AS revenue
FROM recent_orders
GROUP BY customer_id;

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
✓ Copied!