Cheatsheet
SQL Cheatsheet
The SQL I use every day — copy any query, or print the whole sheet.
Read data — SELECT
SELECT * FROM customers;SELECT name, city FROM customers;SELECT DISTINCT city FROM customers;Filter rows — WHERE
SELECT * FROM orders WHERE total > 1000;SELECT * FROM customers WHERE city = 'Chattogram';SELECT * FROM products WHERE price BETWEEN 100 AND 500;SELECT * FROM customers WHERE name LIKE 'S%';Sort & limit — ORDER BY, LIMIT
SELECT * FROM orders ORDER BY created_at DESC;SELECT * FROM products ORDER BY price ASC LIMIT 10;SELECT * FROM customers LIMIT 10 OFFSET 20;Summarise — GROUP BY, HAVING
SELECT COUNT(*) FROM orders;SELECT category, SUM(amount) FROM sales GROUP BY category;SELECT city, COUNT(*) AS n FROM customers GROUP BY city HAVING COUNT(*) > 5;SELECT AVG(price) FROM products;Combine tables — JOIN
SELECT o.id, c.name FROM orders o INNER JOIN customers c ON o.customer_id = c.id;SELECT c.name, COUNT(o.id) FROM customers c LEFT JOIN orders o ON o.customer_id = c.id GROUP BY c.name;Change data — INSERT, UPDATE, DELETE
INSERT INTO customers (name, city) VALUES ('Shoyeb', 'Chattogram');UPDATE customers SET city = 'Dhaka' WHERE id = 1;DELETE FROM orders WHERE id = 99;Always use WHERE with UPDATE and DELETE — without it, every row in the table changes.