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
| Operator | Example | Meaning |
|---|---|---|
= <> | city <> 'Delhi' | Equal, not equal |
< > <= >= | marks > 40 | Comparisons |
BETWEEN | marks BETWEEN 40 AND 60 | In a range, both ends included |
IN | city IN ('Pune','Goa') | Matches any in the list |
LIKE | name LIKE 'A%' | Pattern match, % is any text |
IS NULL | city IS NULL | Missing 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
| Join | Returns |
|---|---|
INNER JOIN | Only rows with a match in both tables |
LEFT JOIN | All rows from the left table, matched rows from the right |
RIGHT JOIN | All rows from the right table, matched rows from the left |
FULL JOIN | All 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.