SQL Cheat Sheet for Beginners (With Examples)
1. What is SQL?
SQL (Structured Query Language) is a standard language used to communicate with databases. It allows
you to create, retrieve, update, and delete data.
2. Basic Commands
SELECT - Retrieves data from a database.
INSERT - Adds new data to a database.
UPDATE - Modifies existing data.
DELETE - Removes data.
CREATE - Creates database objects like tables.
DROP - Deletes database objects.
3. SELECT Statement
SELECT column1, column2 FROM table_name;
Example:
SELECT name, age FROM students;
4. WHERE Clause
Used to filter records.
Example:
SELECT * FROM students WHERE age > 18;
5. SQL JOINS
INNER JOIN: Returns records with matching values in both tables.
LEFT JOIN: All records from the left table, and matched records from the right.
RIGHT JOIN: All records from the right table, and matched records from the left.
FULL JOIN: All records when there is a match in either table.
SQL Cheat Sheet for Beginners (With Examples)
6. GROUP BY and HAVING
GROUP BY is used with aggregate functions (COUNT, SUM, AVG, etc.).
HAVING is like WHERE but used for aggregated data.
Example:
SELECT dept, COUNT(*) FROM employees GROUP BY dept HAVING COUNT(*) > 5;
7. Subqueries
A query inside another query.
Example:
SELECT name FROM students WHERE id IN (SELECT student_id FROM scores WHERE mark > 90);
8. WITH Clause (CTE - Common Table Expression)
Simplifies complex joins and subqueries.
Example:
WITH HighScorers AS (
SELECT student_id FROM scores WHERE mark > 90
SELECT name FROM students WHERE id IN (SELECT student_id FROM HighScorers);
9. Beginner Mistakes to Avoid
- Forgetting WHERE in DELETE or UPDATE.
- Using SELECT * in production.
- Not using aliases for table names in complex joins.
- Confusing HAVING with WHERE.
10. Practice Challenge
SQL Cheat Sheet for Beginners (With Examples)
Create a query to find the top 3 departments with the highest average salary.
Bonus: Use a CTE and explain your thought process in steps.