⚡
usefultools.dev
SQL

SQL-Spickzettel

NEU

SQL-Spickzettel zu SELECT, Joins, GROUP BY, CTEs, Fensterfunktionen, DDL, Upserts und Datumsfunktionen, mit den Unterschieden zwischen MySQL, PostgreSQL und SQL Server.

Die Seite besteht aus statischem Text: Was du in den Filter tippst, verlässt deinen Browser nicht. Anweisungen, Syntax und ihre Kurzbeschreibungen werden auf Englisch angezeigt.

101 Einträge in 12 Abschnitten

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.

⚡

Schnelle Beispiele

Typische Eingaben und die Ergebnisse, die dieses Tool liefert.

Abfrage
Seite 3 der Benutzer, 10 pro Seite
SELECT * FROM users ORDER BY id LIMIT 10 OFFSET 20;
Join
Benutzer mit ihren Bestellungen, auch Benutzer ohne Bestellung behalten
SELECT u.name, o.id FROM users u LEFT JOIN orders o ON o.user_id = u.id;
Insert
Eine Zeile einfügen und ihre neue ID erhalten (PostgreSQL)
INSERT INTO users (name) VALUES ('Ada') RETURNING id;
Fenster
Laufende Summe der Bestellwerte
SUM(total) OVER (ORDER BY created_at)
📖

Überblick

SQL ist die Standardsprache, um Daten in relationalen Datenbanken abzufragen und zu ändern, doch jedes System bringt seine eigenen Besonderheiten mit. Dieser SQL-Spickzettel bündelt die Anweisungen, die du am häufigsten brauchst: SELECT und Filter, Joins, Aggregationen, Unterabfragen und CTEs, Mengenoperationen, INSERT, UPDATE, DELETE und Upserts, Tabellenentwurf, Indizes, Fensterfunktionen und Transaktionen.

Wo sich MySQL, PostgreSQL und SQL Server unterscheiden, etwa bei Paginierung, Verkettung, Datumsrechnung oder der Upsert-Syntax, nennt die Beschreibung den jeweiligen Dialekt. Tabellen- und Spaltennamen sind Platzhalter, die du anpassen musst. Befehle, Syntax und Kurzbeschreibungen bleiben auf Englisch; Oberfläche und diese Erklärung sind auf Deutsch. Filtere die Liste und kopiere jede Anweisung mit einem Klick. Die Seite ist reiner Text, lädt schnell, und nichts, was du eingibst, wird irgendwohin gesendet.

Warum dieses Tool?

  • Eine Anweisung in Sekunden finden, statt in der Dokumentation zu suchen
  • Unterschiede zwischen den Dialekten stehen direkt beim Eintrag
  • Deckt Abfragen, Datenänderungen und Tabellenentwurf ab
  • Nach Stichwort filtern, zum Beispiel join, upsert oder window
  • Anweisung kopieren und die Tabellennamen anpassen
⭐

Funktionen

🔍

Live-Filter

Gib ein Stichwort ein, um nur die passenden Anweisungen und Abschnitte zu sehen.

📋

Kopieren pro Anweisung

Jede Zeile hat eine Kopieren-Schaltfläche für das exakte SQL.

🗄️

Drei Dialekte

Hinweise zu MySQL, PostgreSQL und SQL Server überall dort, wo sich die Syntax unterscheidet.

🪟

Fensterfunktionen

ROW_NUMBER, RANK, LAG, LEAD und laufende Summen in einem Abschnitt.

🔁

Upserts und CTEs

ON CONFLICT, ON DUPLICATE KEY, MERGE und rekursive CTEs nebeneinander.

📱

Mobilfreundlich

Lange Anweisungen werden umgebrochen, damit die Zeilen auch auf dem Smartphone lesbar bleiben.

🛠️

So funktioniert’s

1

Abschnitt wählen

Scrolle zu Joins, Aggregates, DDL, Window functions oder einer anderen Gruppe. Die Abschnittstitel sind auf Englisch.

2

Oder den Filter nutzen

Gib ein Wort wie „upsert“ oder „date“ in das Feld „Diesen Spickzettel filtern“ ein.

3

Dialekt-Hinweis beachten

Lies die Beschreibung, um zu sehen, in welcher Datenbank die Syntax funktioniert.

4

Kopieren und anpassen

Klicke auf Kopieren, füge den Text in deinen SQL-Client ein und ersetze die Beispiel-Tabellen- und Spaltennamen.

🤔

Häufig gestellte Fragen