Code library
Free snippets & functions
Copy, adapt and use them in your own projects.
-- Orders with the customer name
SELECT o.id, o.total, c.name
FROM orders AS o
INNER JOIN customers AS c ON c.id = o.customer_id;
-- All customers, including those who never ordered
SELECT c.name, COUNT(o.id) AS orders
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id, c.name;INNER JOIN returns only matching rows. LEFT JOIN keeps every row from the first table, even without a match.
-- all orders placed in October 2026
SELECT id, total, created_at
FROM orders
WHERE created_at >= '2026-10-01'
AND created_at < '2026-11-01';
-- the last 7 days
SELECT * FROM orders WHERE created_at >= NOW() - INTERVAL 7 DAY;Use a start date and "before the next day" so the whole last day is included.
SET @page = 3;
SET @per = 2;
SELECT id, name
FROM products
ORDER BY id
LIMIT 2 OFFSET 4; -- (page - 1) * per_page = 4
SELECT COUNT(*) AS total_rows FROM products; -- to calculate the page countPage 3 with 2 rows per page skips 4 rows. Always sort so pages are stable.
DELETE FROM order_items WHERE order_id = 1; -- some rows, can use WHERE
TRUNCATE TABLE visits; -- all rows, AUTO_INCREMENT starts again, no WHEREDELETE removes chosen rows and can be rolled back. TRUNCATE empties the table fast and resets the counter.
CREATE TABLE pages (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(120) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
INSERT INTO pages (title) VALUES ('Home');
UPDATE pages SET title = 'Home page' WHERE id = 1; -- updated_at changes by itselfLet the database set the dates so every insert and update is stamped.
SELECT name, 'customer' AS type FROM customers
UNION ALL
SELECT name, 'product' AS type FROM products
ORDER BY name;UNION removes duplicates. UNION ALL keeps them and is faster.
SELECT c.name
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.status = 'paid');EXISTS stops at the first match, so it is fast for "has any" questions.
SELECT name
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE total > 200);
SELECT name FROM products
WHERE price > (SELECT AVG(price) FROM products);The inner query returns a list. The outer query uses it.
SELECT ROUND(19.987, 2) AS two_decimals, -- 19.99
ROUND(1234.5, -2) AS hundreds, -- 1200
CEIL(4.1) AS up, -- 5
FLOOR(4.9) AS down, -- 4
MOD(17, 5) AS remainder, -- 2
ABS(-8) AS absolute; -- 8
SELECT name, ROUND(price * 1.17, 2) AS price_with_tax FROM products;ROUND, CEIL, FLOOR and MOD cover most everyday maths.
SELECT NOW(), CURDATE(),
DATE_FORMAT(created_at, '%d %b %Y') AS pretty,
YEAR(created_at) AS y, MONTH(created_at) AS m,
DATEDIFF(NOW(), created_at) AS days_ago,
created_at + INTERVAL 30 DAY AS plus_30
FROM orders;Format dates, find differences and add time with INTERVAL.
SELECT CONCAT(name, ' <', email, '>') AS contact,
UPPER(name) AS shout,
LENGTH(name) AS bytes,
CHAR_LENGTH(name) AS letters,
SUBSTRING(email, 1, 3) AS start3,
REPLACE(email, '@x.com', '@site.pk') AS new_email,
TRIM(' padded ') AS trimmed
FROM customers;Join, change case, measure and cut text directly in SQL.
SELECT name, price,
CASE
WHEN price < 5 THEN 'Cheap'
WHEN price < 25 THEN 'Medium'
ELSE 'Expensive'
END AS band
FROM products;CASE turns values into labels or groups without changing the data.
SELECT c.name AS customer, o.id AS order_id, p.name AS product, i.qty, i.price
FROM customers c
JOIN orders o ON o.customer_id = c.id
JOIN order_items i ON i.order_id = o.id
JOIN products p ON p.id = i.product_id
ORDER BY o.id, p.name;Follow the keys: customers to orders to order_items to products.
SELECT c.name, COUNT(o.id) AS orders, COALESCE(SUM(o.total), 0) AS spent
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY spent DESC;LEFT JOIN keeps every row from the left table, even customers with no orders.
DROP TABLE IF EXISTS temp_report;
CREATE TABLE temp_report (id INT, label VARCHAR(40));
DROP TABLE temp_report;IF EXISTS avoids an error when the table is already gone. DROP cannot be undone.
ALTER TABLE customers ADD COLUMN phone VARCHAR(30) NULL AFTER email;
ALTER TABLE customers ADD COLUMN country CHAR(2) NOT NULL DEFAULT 'PK';
ALTER TABLE customers DROP COLUMN country;ALTER TABLE changes an existing table. Take a backup before changing a live table.
CREATE TABLE notes (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
title VARCHAR(120) NOT NULL,
body TEXT NULL,
is_public TINYINT(1) NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;Pick the smallest sensible type. Use utf8mb4 so any language and emoji work.
SELECT * FROM customers WHERE city IS NULL;
SELECT * FROM customers WHERE city IS NOT NULL;
SELECT name, COALESCE(city, 'Unknown') AS city FROM customers;
SELECT IFNULL(SUM(total), 0) AS revenue FROM orders WHERE status = 'refunded';NULL means "unknown". Use IS NULL, never = NULL. COALESCE gives a fallback.
SELECT c.name AS customer,
o.total AS amount
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
WHERE o.status = 'paid';Aliases give columns and tables short, readable names.
SELECT status, COUNT(*) AS orders, SUM(total) AS amount
FROM orders
GROUP BY status
ORDER BY amount DESC;
SELECT category, COUNT(*) AS products FROM products GROUP BY category;Every column in SELECT must be either grouped or inside an aggregate function.
SELECT COUNT(*) AS orders,
SUM(total) AS revenue,
AVG(total) AS average,
MIN(total) AS smallest,
MAX(total) AS largest
FROM orders
WHERE status = 'paid';Aggregate functions turn many rows into one value.
SELECT * FROM orders WHERE status = 'cancelled';
DELETE FROM orders
WHERE status = 'cancelled';Same rule as UPDATE: test the WHERE with SELECT, then switch to DELETE.
SELECT * FROM products WHERE id = 1; -- check first
UPDATE products
SET price = price * 1.10, stock = stock - 5
WHERE id = 1;Without WHERE every row changes. Run a SELECT with the same WHERE first.
INSERT INTO products (name, category, price, stock) VALUES
('Eraser', 'Stationery', 0.50, 200),
('Ruler', 'Stationery', 1.20, 150),
('Monitor', 'Electronics', 150.00, 7);One INSERT with several value groups is much faster than many single inserts.
INSERT INTO customers (name, email, city, created_at)
VALUES ('Zara', 'zara@x.com', 'Multan', NOW());
SELECT LAST_INSERT_ID(); -- the new auto-increment idName the columns so the query keeps working when the table gets a new column.
SELECT DISTINCT city FROM customers;
SELECT DISTINCT category FROM products ORDER BY category;
SELECT COUNT(DISTINCT city) AS cities FROM customers;DISTINCT returns each different value once.
SELECT * FROM customers WHERE name LIKE 'A%'; -- starts with A
SELECT * FROM customers WHERE email LIKE '%@x.com'; -- ends with
SELECT * FROM customers WHERE name LIKE '%a%'; -- contains
SELECT * FROM customers WHERE name LIKE '_li'; -- 3 letters ending in li% matches any number of characters, _ matches exactly one.
SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 3; -- the 3 most expensive
SELECT * FROM customers ORDER BY city ASC, name ASC;ORDER BY sorts (ASC is the default). LIMIT keeps only the first rows.
SELECT name, city
FROM customers
WHERE city = 'Lahore' AND active = 1;
SELECT * FROM products WHERE category IN ('Stationery', 'Home');
SELECT * FROM products WHERE price BETWEEN 5 AND 20;
SELECT * FROM orders WHERE status <> 'cancelled' AND (total > 200 OR status = 'pending');Combine conditions with AND / OR, and use IN and BETWEEN to keep queries short.
SELECT id, name, city
FROM customers;
-- all columns (fine while learning)
SELECT * FROM customers;SELECT lists columns. Avoid SELECT * in real code: it is slower and breaks when the table changes.