SQL Basics Cheat Sheet

The examples use a table named students with columns id, name, city and marks.

Read data

SELECT name, marks FROM students;
SELECT * FROM students WHERE city = 'Pune' AND marks >= 60;
SELECT DISTINCT city FROM students;
SELECT * FROM students ORDER BY marks DESC LIMIT 5;

Filtering

OperatorExampleMeaning
= <>city <> 'Delhi'Equal, not equal
< > <= >=marks > 40Comparisons
BETWEENmarks BETWEEN 40 AND 60In a range, both ends included
INcity IN ('Pune','Goa')Matches any in the list
LIKEname LIKE 'A%'Pattern match, % is any text
IS NULLcity IS NULLMissing value

Summaries

SELECT COUNT(*) FROM students;
SELECT city, AVG(marks) AS average FROM students GROUP BY city;
SELECT city, COUNT(*) AS total FROM students GROUP BY city HAVING COUNT(*) > 10;

WHERE filters rows before grouping and HAVING filters groups after it.

Joins

JoinReturns
INNER JOINOnly rows with a match in both tables
LEFT JOINAll rows from the left table, matched rows from the right
RIGHT JOINAll rows from the right table, matched rows from the left
FULL JOINAll rows from both, where supported
SELECT s.name, c.title
FROM students s
INNER JOIN courses c ON c.student_id = s.id;

Change data

INSERT INTO students (name, city, marks) VALUES ('Asha', 'Pune', 82);
UPDATE students SET marks = 90 WHERE id = 7;
DELETE FROM students WHERE id = 7;

Always include a WHERE clause with UPDATE and DELETE, or every row changes. Test on a copy first.

Dialects differ. For example, LIMIT is replaced by TOP in SQL Server.

↑ ↓ navigateEnter openEsc close