Select columns
Pick the columns you need. * returns every column.
SELECT name, email FROM users;
SELECT * FROM users;SQL queries, joins, grouping, subqueries, inserts, updates and tables, with notes where MySQL, PostgreSQL, SQL Server and SQLite differ.
SQL Cheatsheet · Helper-Kit
Examples use standard SQL. Where MySQL, PostgreSQL, SQL Server and SQLite differ, the card shows each version. Text values use single quotes.
52 entries
Pick the columns you need. * returns every column.
SELECT name, email FROM users;
SELECT * FROM users;Give a column or table a shorter or clearer name in the result.
SELECT u.name AS customer, u.email
FROM users AS u;Remove duplicate rows from the result.
SELECT DISTINCT country FROM users;Return only the first rows.
MySQL, PostgreSQL, SQLite
SELECT * FROM users ORDER BY created_at DESC LIMIT 10;SQL Server
SELECT TOP 10 * FROM users ORDER BY created_at DESC;Standard (PostgreSQL, SQL Server 2012+, Oracle)
SELECT * FROM users ORDER BY created_at DESC
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;Skip rows, then take the next page. Always sort first so pages are stable.
MySQL, PostgreSQL, SQLite
SELECT * FROM users ORDER BY id LIMIT 20 OFFSET 40;SQL Server
SELECT * FROM users ORDER BY id
OFFSET 40 ROWS FETCH NEXT 20 ROWS ONLY;Keep only rows that match a condition.
SELECT * FROM users WHERE country = 'UK';Combine conditions. Use brackets to make the order clear.
SELECT * FROM orders
WHERE status = 'paid' AND (total > 100 OR country = 'UK');Equal, not equal, greater, less.
WHERE age >= 18
WHERE status <> 'cancelled'Match any value in the list.
SELECT * FROM users WHERE country IN ('UK', 'IE', 'FR');A range, including both ends.
SELECT * FROM orders
WHERE created_at BETWEEN '2026-01-01' AND '2026-01-31';For timestamps, prefer >= start AND < next day, so the whole last day is included.
% matches any text, _ matches one character.
SELECT * FROM users WHERE email LIKE '%@gmail.com';
SELECT * FROM users WHERE name LIKE 'J_n%';Case sensitivity depends on the database: PostgreSQL LIKE is case-sensitive (use ILIKE); MySQL and SQL Server usually are not.
NULL means “no value”. = NULL never matches; use IS NULL.
SELECT * FROM users WHERE phone IS NULL;
SELECT * FROM users WHERE phone IS NOT NULL;Sort ascending (default) or descending, by one or more columns.
SELECT * FROM users ORDER BY last_name ASC, created_at DESC;COUNT(*) counts rows; COUNT(column) skips NULLs.
SELECT COUNT(*) FROM users;
SELECT COUNT(DISTINCT country) FROM users;Calculate across all matching rows.
SELECT SUM(total), AVG(total), MIN(total), MAX(total) FROM orders;One result row per group.
SELECT country, COUNT(*) AS users
FROM users
GROUP BY country;Filter groups after grouping. WHERE filters rows before grouping.
SELECT country, COUNT(*) AS users
FROM users
GROUP BY country
HAVING COUNT(*) > 100;Only rows that match in both tables.
SELECT o.id, u.name
FROM orders o
INNER JOIN users u ON u.id = o.user_id;Every row from the left table, with matches from the right (or NULL).
SELECT u.name, o.id
FROM users u
LEFT JOIN orders o ON o.user_id = u.id;Users who have never ordered.
SELECT u.*
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE o.id IS NULL;All rows from the right table, or from both tables.
SELECT * FROM a RIGHT JOIN b ON a.id = b.a_id;
SELECT * FROM a FULL OUTER JOIN b ON a.id = b.a_id;MySQL has no FULL OUTER JOIN. SQLite supports RIGHT and FULL from version 3.39.
Join a table to itself, e.g. employees and their managers.
SELECT e.name, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;Stack the results of two queries. UNION removes duplicates; UNION ALL keeps them.
SELECT email FROM customers
UNION
SELECT email FROM newsletter;Use the result of one query inside another.
SELECT * FROM users
WHERE id IN (SELECT user_id FROM orders WHERE total > 500);True if the subquery returns any row. Often faster than IN on big tables.
SELECT * FROM users u
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);Name a subquery so the main query is easier to read.
WITH big_orders AS (
SELECT user_id, SUM(total) AS spent
FROM orders
GROUP BY user_id
)
SELECT u.name, b.spent
FROM users u
JOIN big_orders b ON b.user_id = u.id
WHERE b.spent > 1000;Calculate across related rows without grouping them, e.g. rank within each country.
SELECT name, country, total,
ROW_NUMBER() OVER (PARTITION BY country ORDER BY total DESC) AS rank_in_country
FROM customers;Needs MySQL 8+, SQLite 3.25+; supported by PostgreSQL and SQL Server.
If/then logic inside a query.
SELECT name,
CASE
WHEN total >= 1000 THEN 'gold'
WHEN total >= 100 THEN 'silver'
ELSE 'bronze'
END AS tier
FROM customers;COALESCE returns the first value that is not NULL.
SELECT COALESCE(phone, 'none') FROM users;Combine first and last name.
PostgreSQL, SQLite (and Oracle)
SELECT first_name || ' ' || last_name FROM users;MySQL
SELECT CONCAT(first_name, ' ', last_name) FROM users;SQL Server
SELECT first_name + ' ' + last_name FROM users;
-- or CONCAT(first_name, ' ', last_name)CONCAT() also works in PostgreSQL and SQL Server 2012+.
Change case, trim spaces, and get the length.
SELECT UPPER(name), LOWER(email), TRIM(name), LENGTH(name) FROM users;SQL Server uses LEN() instead of LENGTH().
Today’s date and the current timestamp.
PostgreSQL, MySQL, SQLite
SELECT CURRENT_DATE, CURRENT_TIMESTAMP;SQL Server
SELECT CAST(GETDATE() AS date), GETDATE();Change a value to another type.
SELECT CAST('42' AS INTEGER);
SELECT CAST(price AS DECIMAL(10, 2)) FROM products;Always list the columns, so the query still works if columns are added.
INSERT INTO users (name, email)
VALUES ('Ana', 'ana@example.com');Add multiple rows in one statement.
INSERT INTO users (name, email) VALUES
('Ana', 'ana@example.com'),
('Ben', 'ben@example.com');Copy rows from another table.
INSERT INTO archive_orders (id, total)
SELECT id, total FROM orders WHERE created_at < '2025-01-01';Change existing rows. Without WHERE, every row is changed.
UPDATE users SET country = 'UK' WHERE id = 42;Run the same WHERE as a SELECT first to see which rows will change.
Remove rows. Without WHERE, every row is deleted.
DELETE FROM sessions WHERE expires_at < CURRENT_TIMESTAMP;Insert a row, or update it if the key already exists.
PostgreSQL, SQLite
INSERT INTO settings (key, value) VALUES ('theme', 'dark')
ON CONFLICT (key) DO UPDATE SET value = excluded.value;MySQL
INSERT INTO settings (`key`, value) VALUES ('theme', 'dark')
ON DUPLICATE KEY UPDATE value = VALUES(value);SQL Server
MERGE settings AS t
USING (SELECT 'theme' AS [key], 'dark' AS value) AS s
ON t.[key] = s.[key]
WHEN MATCHED THEN UPDATE SET value = s.value
WHEN NOT MATCHED THEN INSERT ([key], value) VALUES (s.[key], s.value);Define columns, types and rules.
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);Let the database number new rows.
PostgreSQL
id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY
-- older style: id SERIAL PRIMARY KEYMySQL
id INT AUTO_INCREMENT PRIMARY KEYSQL Server
id INT IDENTITY(1,1) PRIMARY KEYSQLite
id INTEGER PRIMARY KEYLink a column to another table’s key.
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id),
total DECIMAL(10, 2) NOT NULL
);SQLite only enforces foreign keys after PRAGMA foreign_keys = ON;
Add, rename or remove a column.
ALTER TABLE users ADD COLUMN phone VARCHAR(20);
ALTER TABLE users RENAME COLUMN phone TO mobile;
ALTER TABLE users DROP COLUMN mobile;SQL Server: ADD without COLUMN, and rename with EXEC sp_rename.
Avoid an error if the table already exists.
CREATE TABLE IF NOT EXISTS logs (id INTEGER PRIMARY KEY, message TEXT);SQL Server 2016+ supports DROP TABLE IF EXISTS, but not CREATE TABLE IF NOT EXISTS.
TRUNCATE empties a table quickly and keeps its structure.
TRUNCATE TABLE logs;SQLite has no TRUNCATE; use DELETE FROM logs;
Delete the table and all its data.
DROP TABLE IF EXISTS old_logs;Speeds up searches and joins on a column. Unique indexes also block duplicates.
CREATE INDEX idx_orders_user ON orders (user_id);
CREATE UNIQUE INDEX idx_users_email ON users (email);Check whether a query uses your indexes.
EXPLAIN SELECT * FROM orders WHERE user_id = 42;SQL Server: use “Display Estimated Execution Plan” or SET SHOWPLAN_TEXT ON. SQLite: EXPLAIN QUERY PLAN.
Save a query and use it like a table.
CREATE VIEW paid_orders AS
SELECT * FROM orders WHERE status = 'paid';Group changes so they all succeed, or none of them apply.
BEGIN;
UPDATE accounts SET balance = balance - 50 WHERE id = 1;
UPDATE accounts SET balance = balance + 50 WHERE id = 2;
COMMIT;SQL Server and MySQL also accept BEGIN TRANSACTION / START TRANSACTION.
Undo everything since BEGIN.
ROLLBACK;Never build SQL by joining user input into the string. Use placeholders.
-- Unsafe
"SELECT * FROM users WHERE email = '" + input + "'"
-- Safe (placeholder filled by the database driver)
SELECT * FROM users WHERE email = ?;Placeholders look like ?, $1 or @email depending on the database driver.
💡 Search matches titles, descriptions and the commands themselves. Copy puts the exact text on your clipboard; Print gives a clean sheet without menus or buttons. Searching happens in your browser; nothing is sent anywhere.
SQL is the language for reading and changing data in relational databases. This cheatsheet covers selecting and filtering rows, sorting, limits and pagination, aggregates and GROUP BY, joins, subqueries and WITH (CTEs), CASE and other functions, inserting, updating and deleting, creating and altering tables, indexes and views, and transactions. The examples use standard SQL with single quotes for text, which works across databases. Where MySQL, PostgreSQL, SQL Server and SQLite need different syntax, such as LIMIT and TOP, joining text, auto-increment IDs and upserts, the card shows each version. Statements that change or delete data are marked Careful. To tidy up a long query, paste it into the SQL Formatter.
INNER JOIN returns only rows that match in both tables. LEFT JOIN returns every row from the left table, with NULL where the right table has no match.
WHERE filters rows before they are grouped. HAVING filters groups after GROUP BY, so it can use aggregates like COUNT(*).
In standard SQL (and PostgreSQL), double quotes mean a column or table name, so WHERE name = "Ana" looks for a column called Ana. Use single quotes for text: WHERE name = 'Ana'.
Use parameterised queries (placeholders) so the database treats user input as data, never as SQL. Do not build queries by joining strings.