SQL cheat sheet

Find the right syntax, then practise it.

Eleven progressive references, from first queries to window functions.

1. Read and select

Control exactly which columns and rows are returned.

ColumnsSELECT produit, prix FROM produits;
Unique valuesSELECT DISTINCT categorie FROM produits;
LimitLIMIT 10

2. Filter

Narrow the scope before analysing.

ConditionWHERE montant > 100
ListWHERE ville IN ('Tunis', 'Sfax')
RangeWHERE montant BETWEEN 50 AND 200

3. Sort

Make a ranking explicit and reproducible.

AscendingORDER BY date_commande ASC
DescendingORDER BY montant DESC
Two criteriaORDER BY ville ASC, montant DESC

4. Aggregate

Turn rows into metrics.

CountCOUNT(*)
TotalSUM(montant)
By groupGROUP BY ville
Filter groupsHAVING SUM(montant) > 500

5. Join tables

Connect entities through their keys.

Present on both sidesINNER JOIN commandes c ON c.id_client = clients.id_client
Keep the left tableLEFT JOIN commandes c ON c.id_client = clients.id_client

6. Handle NULL

A missing value is neither zero nor an empty string.

TestWHERE telephone IS NULL
ReplaceCOALESCE(telephone, 'Not provided')
Avoid division by zeromontant / NULLIF(quantite, 0)

7. Structure an analysis

Break a long query into named steps.

CTEWITH ventes_ville AS (...) SELECT * FROM ventes_ville;
ConditionCASE WHEN montant >= 200 THEN 'High' ELSE 'Standard' END

8. Analyse over time

Prepare advanced metrics used by Data Analysts.

MonthDATE_TRUNC('month', date_commande)
Running totalSUM(montant) OVER (ORDER BY date_commande)
RankingROW_NUMBER() OVER (PARTITION BY ville ORDER BY montant DESC)

9. Work with text

Clean and combine labels without losing missing values.

CombineCONCAT(prenom, ' ', nom)
CaseLOWER(email)
TrimTRIM(reference)
ExtractSUBSTRING(code FROM 1 FOR 3)

10. Understand order and errors

SQL logically evaluates FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY and then LIMIT.

Unknown columnCheck the schema and spelling
GROUP BY errorGroup or aggregate every selected column
Division by zeroUse NULLIF(divisor, 0)
SyntaxCheck commas, parentheses and single quotes

11. Spot syntax differences

The same operation may use different syntax depending on the system.

LimitHere and MySQL: LIMIT · SQL Server: TOP
ConcatenateHere: || · MySQL: CONCAT · SQL Server: +
Current dateHere: CURRENT_DATE · MySQL: CURDATE() · SQL Server: GETDATE()

Syntax sticks through practice.

Use the free editor or choose a guided exercise with validation.