SQL Study Guide (Beginner Friendly)
1. What is SQL?
SQL (Structured Query Language) is used to manage and manipulate relational databases. It allows
you to create, read, update, and delete data (CRUD operations).
2. Basic SQL Commands
a. SELECT
Retrieve data from one or more tables.
SELECT column1, column2 FROM table_name;
b. WHERE
Filter results based on a condition.
SELECT * FROM employees WHERE age > 30;
c. INSERT
Add new data to a table.
INSERT INTO employees (name, age, department)
VALUES ('Alice', 28, 'HR');
d. UPDATE
Modify existing data.
UPDATE employees
SET age = 29
WHERE name = 'Alice';
e. DELETE
Remove data.
DELETE FROM employees
WHERE name = 'Alice';
3. Creating Tables
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
age INT,
department VARCHAR(50)
);
4. Data Types
- INT: Integer
- VARCHAR(n): Text of up to n characters
- DATE: Date
- BOOLEAN: True/False
5. Joins
Used to combine rows from two or more tables.
a. INNER JOIN
Returns only matching rows.
SELECT *
FROM employees
INNER JOIN departments ON employees.department_id = departments.id;
b. LEFT JOIN
Returns all rows from the left table, with matched rows from the right.
c. RIGHT JOIN
Returns all rows from the right table, with matched rows from the left.
d. FULL JOIN
Returns all rows when there is a match in either table.
6. Aggregate Functions
- COUNT(): Number of rows
- SUM(): Total sum
- AVG(): Average
- MAX() / MIN(): Largest/Smallest value
SELECT department, COUNT(*) FROM employees GROUP BY department;
7. ORDER BY and LIMIT
SELECT * FROM employees
ORDER BY age DESC
LIMIT 5;
8. GROUP BY and HAVING
Group rows sharing a property and filter with HAVING.
SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
9. Subqueries
A query within another query.
SELECT name FROM employees
WHERE age > (SELECT AVG(age) FROM employees);
10. Practice Tips
- Use sample databases like "Sakila" or "Chinook"
- Practice on platforms like LeetCode, HackerRank, SQLZoo
- Focus on writing and debugging your own queries
Happy querying!