SQL joins combine rows from two tables using a predicate, usually a foreign key. INNER JOIN keeps matches only. LEFT JOIN keeps every left row and fills right columns with NULL when missing. Put extra filters on the right table in the ON clause of a left join, or you accidentally turn it into an inner join.
This SQL cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- INNER: Rows with a match in both tables.
- LEFT: All left rows + matching right (or NULLs). Most “optional child” queries.
- RIGHT: Mirror of LEFT. Usually rewritten as LEFT with tables swapped.
- FULL: All rows from both; unmatched sides NULL. MySQL lacks FULL OUTER — use UNION of LEFT and RIGHT.
- CROSS: Cartesian product. Rare in app code; useful for generating combinations.
- SELF: Join a table to itself (
employee/manager_id). Alias both copies. - ON vs WHERE: ON is the join predicate. WHERE after a LEFT JOIN on a right column removes unmatched left rows.
- Multi: Join several tables in a chain. Keep keys indexed.
Copy-paste examples
Left join without turning it inner
The comment filter stays in ON so posts with zero comments still appear.
SELECT p.id, p.title, c.body AS latest_comment
FROM posts AS p
LEFT JOIN comments AS c
ON c.post_id = p.id AND c.approved = 1
WHERE p.author_id = 41
ORDER BY p.id DESC;Self join managers
Alias both sides. LEFT JOIN if some employees have no manager.
SELECT e.id, e.name AS employee, m.name AS manager
FROM staff AS e
LEFT JOIN staff AS m ON m.id = e.manager_id;Common mistakes
- Putting
WHERE c.id IS NOT NULLafter a LEFT JOIN when you wanted inner — be honest and write INNER. - Joining on
nameinstead of integer keys (duplicates, encoding, indexes). - CROSS JOIN by forgetting the
ONclause in some dialects (FROM a, b). - Selecting
*from a three-table join and fighting duplicate column names in PHP.
FAQ
- Which join is default?
INNERwhen you writeJOINwithout a type in most engines. SpellINNER JOINanyway.
- Join vs subquery? Joins are often clearer for combining columns. Subqueries/
IN/EXISTScan be clearer for “has at least one.” CheckEXPLAINwhen it matters.
- Does join order change results? For inner joins, order is for the optimizer. For outer joins, which table is left vs right changes the result.
Related SQL cheat sheets
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds custom web development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.