Helper-KitCheatsheets

SQL Cheatsheet

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

Select

Select columns

Pick the columns you need. * returns every column.

SELECT name, email FROM users;
SELECT * FROM users;

Rename columns (alias)

Give a column or table a shorter or clearer name in the result.

SELECT u.name AS customer, u.email
FROM users AS u;

Unique values

Remove duplicate rows from the result.

SELECT DISTINCT country FROM users;

Limit the number of rows

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;

Pagination

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;

Filter

WHERE

Keep only rows that match a condition.

SELECT * FROM users WHERE country = 'UK';

AND, OR, NOT

Combine conditions. Use brackets to make the order clear.

SELECT * FROM orders
WHERE status = 'paid' AND (total > 100 OR country = 'UK');

Comparison

Equal, not equal, greater, less.

WHERE age >= 18
WHERE status <> 'cancelled'

IN a list

Match any value in the list.

SELECT * FROM users WHERE country IN ('UK', 'IE', 'FR');

BETWEEN

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.

LIKE (pattern)

% 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 checks

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

ORDER BY

Sort ascending (default) or descending, by one or more columns.

SELECT * FROM users ORDER BY last_name ASC, created_at DESC;

Aggregate

Count rows

COUNT(*) counts rows; COUNT(column) skips NULLs.

SELECT COUNT(*) FROM users;
SELECT COUNT(DISTINCT country) FROM users;

Sum, average, min, max

Calculate across all matching rows.

SELECT SUM(total), AVG(total), MIN(total), MAX(total) FROM orders;

GROUP BY

One result row per group.

SELECT country, COUNT(*) AS users
FROM users
GROUP BY country;

HAVING

Filter groups after grouping. WHERE filters rows before grouping.

SELECT country, COUNT(*) AS users
FROM users
GROUP BY country
HAVING COUNT(*) > 100;

Joins

INNER JOIN

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;

LEFT JOIN

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;

Rows with no match

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;

RIGHT and FULL JOIN

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.

Self join

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;

UNION

Stack the results of two queries. UNION removes duplicates; UNION ALL keeps them.

SELECT email FROM customers
UNION
SELECT email FROM newsletter;

Subqueries & CTEs

Subquery with IN

Use the result of one query inside another.

SELECT * FROM users
WHERE id IN (SELECT user_id FROM orders WHERE total > 500);

EXISTS

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);

WITH (common table expression)

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;

Window function

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.

Functions

CASE

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;

Replace NULL with a value

COALESCE returns the first value that is not NULL.

SELECT COALESCE(phone, 'none') FROM users;

Join text together

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+.

Text functions

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().

Current date and time

Today’s date and the current timestamp.

PostgreSQL, MySQL, SQLite

SELECT CURRENT_DATE, CURRENT_TIMESTAMP;

SQL Server

SELECT CAST(GETDATE() AS date), GETDATE();

Convert a type

Change a value to another type.

SELECT CAST('42' AS INTEGER);
SELECT CAST(price AS DECIMAL(10, 2)) FROM products;

Change data

INSERT a row

Always list the columns, so the query still works if columns are added.

INSERT INTO users (name, email)
VALUES ('Ana', 'ana@example.com');

INSERT several rows

Add multiple rows in one statement.

INSERT INTO users (name, email) VALUES
  ('Ana', 'ana@example.com'),
  ('Ben', 'ben@example.com');

INSERT from a query

Copy rows from another table.

INSERT INTO archive_orders (id, total)
SELECT id, total FROM orders WHERE created_at < '2025-01-01';

UPDATE

Careful

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.

DELETE

Careful

Remove rows. Without WHERE, every row is deleted.

DELETE FROM sessions WHERE expires_at < CURRENT_TIMESTAMP;

Insert or update (upsert)

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);

Tables

CREATE TABLE

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
);

Auto-increment ID

Let the database number new rows.

PostgreSQL

id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY
-- older style: id SERIAL PRIMARY KEY

MySQL

id INT AUTO_INCREMENT PRIMARY KEY

SQL Server

id INT IDENTITY(1,1) PRIMARY KEY

SQLite

id INTEGER PRIMARY KEY

Foreign key

Link 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;

ALTER TABLE

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.

Create only if missing

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.

Delete all rows

Careful

TRUNCATE empties a table quickly and keeps its structure.

TRUNCATE TABLE logs;

SQLite has no TRUNCATE; use DELETE FROM logs;

DROP TABLE

Careful

Delete the table and all its data.

DROP TABLE IF EXISTS old_logs;

Indexes & views

Create an index

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);

See how a query runs

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.

Create a view

Save a query and use it like a table.

CREATE VIEW paid_orders AS
SELECT * FROM orders WHERE status = 'paid';

Transactions

All or nothing

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.

Cancel changes

Undo everything since BEGIN.

ROLLBACK;

Avoid SQL injection

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.

About This Cheatsheet

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.

Quick Tips

  • Run a SELECT with the same WHERE before any UPDATE or DELETE, to see which rows will change.
  • Use single quotes for text values. Double quotes are for column and table names in standard SQL.
  • Always add ORDER BY when you use LIMIT, or the rows you get can change between runs.
  • Use IS NULL, not = NULL. Nothing is ever equal to NULL.
  • Never paste user input into SQL. Use your database driver's placeholders instead.

Frequently Asked Questions

What is the difference between INNER JOIN and LEFT JOIN?

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.

What is the difference between WHERE and HAVING?

WHERE filters rows before they are grouped. HAVING filters groups after GROUP BY, so it can use aggregates like COUNT(*).

Why does my query fail with double quotes?

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'.

How do I prevent SQL injection?

Use parameterised queries (placeholders) so the database treats user input as data, never as SQL. Do not build queries by joining strings.

Was this tool helpful?

More in this category