⚡
usefultools.dev
SQL

Chuleta de SQL

NUEVO

Chuleta de SQL con SELECT, joins, GROUP BY, CTE, funciones de ventana, DDL, upserts y funciones de fecha, con las diferencias entre MySQL, PostgreSQL y SQL Server.

Es texto estático: nada de lo que escribes en el filtro sale de tu navegador. Las sentencias, la sintaxis y sus descripciones breves se muestran en inglés.

101 entradas en 12 secciones

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 KEY

    Column constraint: unique, non-NULL row identifier.

  • id INT GENERATED ALWAYS AS IDENTITY

    Auto-incrementing column in PostgreSQL 10+. MySQL: AUTO_INCREMENT. SQL Server: IDENTITY(1,1).

  • FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE

    Link to another table; CASCADE deletes dependent rows with the parent.

  • email VARCHAR(255) NOT NULL UNIQUE

    Require 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_name

    Join 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' END

    Conditional 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_TIMESTAMP

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

⚡

Ejemplos rápidos

Entradas típicas y los resultados que produce esta herramienta.

Consulta
Página 3 de usuarios, 10 por página
SELECT * FROM users ORDER BY id LIMIT 10 OFFSET 20;
Join
Usuarios con sus pedidos, conservando los usuarios sin pedidos
SELECT u.name, o.id FROM users u LEFT JOIN orders o ON o.user_id = u.id;
Insert
Insertar una fila y obtener su nuevo id (PostgreSQL)
INSERT INTO users (name) VALUES ('Ada') RETURNING id;
Ventana
Total acumulado del importe de los pedidos
SUM(total) OVER (ORDER BY created_at)
📖

Descripción general

SQL es el lenguaje estándar para consultar y modificar datos en bases de datos relacionales, pero cada motor añade sus propias particularidades. Esta chuleta de SQL agrupa las sentencias que más se usan: SELECT y filtros, joins, agregaciones, subconsultas y CTE, operaciones de conjuntos, INSERT, UPDATE, DELETE y upserts, diseño de tablas, índices, funciones de ventana y transacciones.

Donde MySQL, PostgreSQL y SQL Server se diferencian, por ejemplo en la paginación, la concatenación, la aritmética de fechas o la sintaxis del upsert, la descripción indica el dialecto. Los nombres de tablas y columnas son marcadores que debes adaptar. Los comandos, la sintaxis y las descripciones breves se muestran en inglés; en español están la interfaz y esta explicación. Filtra la lista y copia cualquier sentencia con un clic. La página es texto plano, carga rápido y nada de lo que escribes se envía a ningún sitio.

¿Por qué usar esta herramienta?

  • Encuentra una sentencia en segundos sin buscar en la documentación
  • Las diferencias entre dialectos aparecen junto a cada entrada
  • Cubre consultas, cambios de datos y diseño de tablas
  • Filtra por palabra clave, como join, upsert o window
  • Copia una sentencia y adapta los nombres de las tablas
⭐

Funciones

🔍

Filtro en vivo

Escribe una palabra clave para ver solo las sentencias y secciones que coinciden.

📋

Copiar cada sentencia

Cada fila tiene un botón para copiar el SQL exacto.

🗄️

Tres dialectos

Notas sobre MySQL, PostgreSQL y SQL Server donde la sintaxis cambia.

🪟

Funciones de ventana

ROW_NUMBER, RANK, LAG, LEAD y totales acumulados en una sola sección.

🔁

Upserts y CTE

ON CONFLICT, ON DUPLICATE KEY, MERGE y CTE recursivas, una al lado de otra.

📱

Apta para móvil

Las sentencias largas se ajustan al ancho, así que las filas se leen bien en el teléfono.

🛠️

Cómo se usa

1

Elige una sección

Desplázate hasta Joins, Aggregates, DDL, Window functions u otro grupo. Los títulos de las secciones están en inglés.

2

O usa el filtro

Escribe una palabra como "upsert" o "date" en el cuadro "Filtrar esta chuleta".

3

Revisa la nota del dialecto

Lee la descripción para saber en qué base de datos funciona la sintaxis.

4

Copia y adapta

Pulsa Copiar, pega en tu cliente SQL y cambia los nombres de tabla y columna del ejemplo.

🤔

Preguntas frecuentes