SQL Cheatsheet
NOVOSQL cheatsheet covering SELECT, joins, GROUP BY, CTEs, window functions, DDL, upserts and date functions, with MySQL, PostgreSQL and SQL Server differences.
Funciona 100% no seu navegador — o que você insere nunca é enviado nem armazenado nos nossos servidores.
Esta ferramenta ainda não está totalmente traduzida, por isso parte do texto continua em inglês. A ferramenta funciona da mesma forma em todos os idiomas.
101 entradas em 12 seções
SELECT, WHERE, ORDER BY, LIMIT
Table and column names (users, email, ...) are examples. Dialect differences are named in the description.
SELECT * FROM users;Return every column of every row.
SELECT name, email FROM users;Return only the listed columns.
SELECT DISTINCT country FROM users;Return each country once, without duplicates.
SELECT price * qty AS total FROM orders;Give a computed column an alias.
SELECT * FROM users WHERE age >= 18 AND country = 'US';Filter rows with conditions combined by AND / OR.
SELECT * FROM orders WHERE status IN ('new', 'open');Match any value in a list.
SELECT * FROM products WHERE price BETWEEN 10 AND 20;Match a range; both ends are included.
SELECT * FROM users WHERE name LIKE 'A%';Pattern match: % is any run of characters, _ is exactly one character.
SELECT * FROM users WHERE deleted_at IS NULL;Test for NULL with IS NULL; = NULL never matches.
SELECT * FROM users ORDER BY created_at DESC, name ASC;Sort by one or more columns; ASC is the default.
SELECT * FROM users ORDER BY id LIMIT 10 OFFSET 20;Paging in MySQL, PostgreSQL and SQLite: skip 20 rows, return 10.
SELECT * FROM users ORDER BY id OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;Standard paging for SQL Server 2012+ (ORDER BY required) and PostgreSQL.
SELECT TOP 10 * FROM users;SQL Server only: return the first 10 rows.
Joins
SELECT o.id, u.name FROM orders o INNER JOIN users u ON u.id = o.user_id;Only rows that have a match in both tables.
SELECT u.name, o.id FROM users u LEFT JOIN orders o ON o.user_id = u.id;All users, with order columns NULL when a user has no orders.
SELECT u.name, o.id FROM users u RIGHT JOIN orders o ON o.user_id = u.id;All orders, with user columns NULL when no user matches.
SELECT * FROM a FULL OUTER JOIN b ON a.id = b.a_id;All rows from both sides. Supported by PostgreSQL and SQL Server, not by MySQL.
SELECT * FROM sizes CROSS JOIN colors;Every combination of rows from both tables.
SELECT e.name, m.name AS manager FROM employees e JOIN employees m ON m.id = e.manager_id;Self join: join a table to itself under two aliases.
SELECT * FROM orders JOIN users USING (user_id);Shorthand when both tables share the join column name (MySQL, PostgreSQL; not SQL Server).
Aggregates, GROUP BY, HAVING
SELECT COUNT(*) FROM users;Count all rows.
SELECT COUNT(DISTINCT country) FROM users;Count unique non-NULL values.
SELECT SUM(total), AVG(total), MIN(total), MAX(total) FROM orders;Common aggregate functions; NULL values are ignored.
SELECT country, COUNT(*) FROM users GROUP BY country;One result row per group.
SELECT country, COUNT(*) AS n FROM users GROUP BY country HAVING COUNT(*) > 100;HAVING filters groups after aggregation; WHERE filters rows before it.
SELECT region, city, SUM(sales) FROM t GROUP BY ROLLUP (region, city);Subtotals and a grand total. PostgreSQL and SQL Server syntax; MySQL uses GROUP BY region, city WITH ROLLUP.
Subqueries & CTEs
SELECT name FROM users WHERE id IN (SELECT user_id FROM orders);Subquery in WHERE returning a list of values.
SELECT name FROM users u WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);Keep rows for which the subquery returns at least one row.
SELECT name, (SELECT MAX(total) FROM orders o WHERE o.user_id = u.id) AS biggest FROM users u;Scalar subquery: returns a single value for each outer row.
SELECT * FROM (SELECT user_id, SUM(total) AS spent FROM orders GROUP BY user_id) s WHERE spent > 500;Derived table: a subquery in FROM, which needs an alias.
WITH recent AS (SELECT * FROM orders WHERE created_at > '2026-01-01') SELECT COUNT(*) FROM recent;Common table expression (CTE): a named query used by the statement that follows.
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 5) SELECT i FROM n;Recursive CTE counting 1 to 5 (PostgreSQL, MySQL 8+, SQLite). SQL Server omits the RECURSIVE keyword.
Set operations
SELECT email FROM customers UNION SELECT email FROM leads;Combine results and remove duplicates.
SELECT email FROM customers UNION ALL SELECT email FROM leads;Combine results and keep duplicates; faster because there is no de-duplication.
SELECT id FROM a INTERSECT SELECT id FROM b;Rows present in both results (MySQL 8.0.31+).
SELECT id FROM a EXCEPT SELECT id FROM b;Rows in the first result but not the second (Oracle calls it MINUS).
INSERT, UPDATE, DELETE, UPSERT
INSERT INTO users (name, email) VALUES ('Ada', '[email protected]');Insert one row.
INSERT INTO users (name, email) VALUES ('Ada', '[email protected]'), ('Linus', '[email protected]');Insert several rows in one statement.
INSERT INTO archive SELECT * FROM orders WHERE created_at < '2025-01-01';Insert the result of a query.
UPDATE users SET active = false WHERE last_login < '2025-01-01';Change matching rows. Without WHERE, every row is updated.
DELETE FROM sessions WHERE expires_at < CURRENT_TIMESTAMP;Delete matching rows. Without WHERE, every row is deleted.
TRUNCATE TABLE logs;Remove all rows quickly and keep the table; usually cannot be filtered with WHERE.
INSERT INTO t (id, name) VALUES (1, 'x') ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name;Upsert in PostgreSQL and SQLite: insert, or update when the key already exists.
INSERT INTO t (id, name) VALUES (1, 'x') AS new ON DUPLICATE KEY UPDATE name = new.name;Upsert in MySQL 8.0.19+; older versions use VALUES(name) instead of the alias.
MERGE INTO t USING s ON t.id = s.id WHEN MATCHED THEN UPDATE SET t.name = s.name WHEN NOT MATCHED THEN INSERT (id, name) VALUES (s.id, s.name);Upsert in SQL Server (end the statement with a semicolon).
INSERT INTO users (name) VALUES ('Ada') RETURNING id;Get generated values back (PostgreSQL, SQLite). SQL Server uses OUTPUT inserted.id before VALUES.
DDL: create, alter, drop
CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(100) NOT NULL);Create a table with columns and types.
ALTER TABLE users ADD COLUMN age INT;Add a column (SQL Server: ALTER TABLE users ADD age INT, without the COLUMN keyword).
ALTER TABLE users DROP COLUMN age;Remove a column and its data.
ALTER TABLE users RENAME COLUMN name TO full_name;Rename a column in PostgreSQL, MySQL 8+ and SQLite. SQL Server uses sp_rename.
ALTER TABLE users ALTER COLUMN age TYPE BIGINT;Change a column type in PostgreSQL. MySQL: MODIFY COLUMN age BIGINT. SQL Server: ALTER COLUMN age BIGINT.
ALTER TABLE users RENAME TO customers;Rename a table (PostgreSQL, MySQL, SQLite). SQL Server: EXEC sp_rename 'users', 'customers'.
CREATE TABLE users_copy AS SELECT * FROM users;Create a table from a query (PostgreSQL, MySQL). SQL Server: SELECT * INTO users_copy FROM users.
DROP TABLE IF EXISTS users;Delete a table; IF EXISTS avoids an error when it is missing (SQL Server 2016+).
Constraints, keys & indexes
id INT PRIMARY KEYColumn constraint: unique, non-NULL row identifier.
id INT GENERATED ALWAYS AS IDENTITYAuto-incrementing column in PostgreSQL 10+. MySQL: AUTO_INCREMENT. SQL Server: IDENTITY(1,1).
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADELink to another table; CASCADE deletes dependent rows with the parent.
email VARCHAR(255) NOT NULL UNIQUERequire a value and forbid duplicates.
status VARCHAR(10) DEFAULT 'new'Value used when an INSERT omits the column.
CHECK (price >= 0)Reject rows that break the condition (enforced by MySQL 8.0.16+).
ALTER TABLE orders ADD CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users (id);Add a named constraint to an existing table.
CREATE INDEX idx_users_email ON users (email);Speed up lookups and sorts on the column.
CREATE UNIQUE INDEX uq_users_email ON users (email);Index that also enforces uniqueness.
CREATE INDEX idx_orders_user_date ON orders (user_id, created_at);Composite index; column order matters, the leftmost column is used first.
DROP INDEX idx_users_email ON users;Drop an index in MySQL and SQL Server. PostgreSQL and SQLite: DROP INDEX idx_users_email.
Window functions
Available in PostgreSQL, SQL Server, SQLite 3.25+ and MySQL 8+.
ROW_NUMBER() OVER (ORDER BY created_at)Number rows 1, 2, 3 in the given order.
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC)Restart numbering for each user; filter on 1 to get each user's latest row.
RANK() OVER (ORDER BY score DESC)Rank with gaps after ties (1, 1, 3).
DENSE_RANK() OVER (ORDER BY score DESC)Rank without gaps after ties (1, 1, 2).
LAG(total) OVER (ORDER BY created_at)Value from the previous row.
LEAD(total) OVER (ORDER BY created_at)Value from the next row.
SUM(total) OVER (ORDER BY created_at)Running total.
AVG(total) OVER (ORDER BY created_at ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)Moving average over the current and previous six rows.
NTILE(4) OVER (ORDER BY score)Split rows into four equal buckets.
String functions
CONCAT(first_name, ' ', last_name)Join strings; works in MySQL, PostgreSQL and SQL Server 2012+.
first_name || ' ' || last_nameJoin strings with || in PostgreSQL and SQLite. SQL Server uses +.
LENGTH(name)String length in PostgreSQL and SQLite (characters). MySQL counts bytes (use CHAR_LENGTH); SQL Server uses LEN.
SUBSTRING(name, 2, 3)Three characters starting at position 2 (positions start at 1).
UPPER(name) / LOWER(name)Change case.
TRIM(name)Remove leading and trailing spaces.
REPLACE(name, 'old', 'new')Replace every occurrence of a substring.
COALESCE(nickname, name, 'unknown')First non-NULL argument.
CASE WHEN score >= 50 THEN 'pass' ELSE 'fail' ENDConditional value inside a query.
CAST(price AS DECIMAL(10,2))Convert a value to another type.
STRING_AGG(name, ', ')Join values from a group into one string (PostgreSQL, SQL Server 2017+). MySQL: GROUP_CONCAT(name SEPARATOR ', ').
Date & time functions
CURRENT_TIMESTAMPCurrent date and time; standard and supported by all three. NOW() works in MySQL and PostgreSQL, GETDATE() in SQL Server.
created_at + INTERVAL '7 days'Add a period in PostgreSQL. MySQL: DATE_ADD(created_at, INTERVAL 7 DAY).
DATEADD(day, 7, created_at)Add days in SQL Server.
DATEDIFF(end_date, start_date)Days between two dates in MySQL. SQL Server: DATEDIFF(day, start_date, end_date). PostgreSQL: end_date - start_date.
EXTRACT(YEAR FROM created_at)Pull one part out of a date (PostgreSQL, MySQL). SQL Server: DATEPART(year, created_at) or YEAR(created_at).
DATE_TRUNC('month', created_at)Round down to the start of the month in PostgreSQL. SQL Server 2022+: DATETRUNC(month, created_at).
DATE_FORMAT(created_at, '%Y-%m-%d')Format a date in MySQL.
TO_CHAR(created_at, 'YYYY-MM-DD')Format a date in PostgreSQL. SQL Server: FORMAT(created_at, 'yyyy-MM-dd').
Transactions & plans
BEGIN;Start a transaction in PostgreSQL. MySQL: START TRANSACTION. SQL Server: BEGIN TRANSACTION.
COMMIT;Make the changes of the transaction permanent.
ROLLBACK;Undo every change since the transaction began.
SAVEPOINT before_update;Mark a point to roll back to. SQL Server: SAVE TRANSACTION before_update.
ROLLBACK TO SAVEPOINT before_update;Undo only back to the savepoint. SQL Server: ROLLBACK TRANSACTION before_update.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;Choose how strictly concurrent transactions are isolated.
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;Lock the selected rows until the transaction ends (PostgreSQL, MySQL).
EXPLAIN SELECT * FROM users WHERE email = '[email protected]';Show the query plan; PostgreSQL and MySQL 8.0.18+ accept EXPLAIN ANALYZE to also run it.
Exemplos rápidos
Entradas típicas e os resultados que esta ferramenta gera.
Visão geral
SQL is the standard language for querying and changing data in relational databases, but each database adds its own twists. This SQL cheatsheet groups the statements you use most: SELECT and filtering, joins, aggregates, subqueries and CTEs, set operations, INSERT, UPDATE, DELETE and upserts, table design, indexes, window functions and transactions.
Where MySQL, PostgreSQL and SQL Server differ, such as paging, concatenation, date arithmetic and upsert syntax, the description names the dialect. Table and column names are placeholders to adapt. Filter the list and copy any statement with one click. The page is plain text, so it loads quickly, and nothing you type is sent anywhere.
Por que usar esta ferramenta?
- Find a statement in seconds instead of searching the docs
- Dialect differences are named next to each entry
- Covers queries, data changes and table design
- Filter by keyword such as join, upsert or window
- Copy a statement and adapt the table names
Recursos
Live filter
Type a keyword to show only the matching statements and sections.
Copy per statement
Each row has a Copy button for the exact SQL.
Three dialects
Notes for MySQL, PostgreSQL and SQL Server appear where syntax differs.
Window functions
ROW_NUMBER, RANK, LAG, LEAD and running totals in one section.
Upserts and CTEs
ON CONFLICT, ON DUPLICATE KEY, MERGE and recursive CTEs side by side.
Mobile friendly
Long statements wrap, so rows stay readable on a phone.
Como usar
Pick a section
Scroll to Joins, Aggregates, DDL, Window functions or another group.
Or use the filter
Type a word like "upsert" or "date" in the "Filter this cheatsheet" box.
Check the dialect note
Read the description to see which database the syntax works in.
Copy and adapt
Press Copy, paste into your SQL client and replace the example table and column names.