SQL Notes
SQL Notes
Topics Covered
• Databases & RDBMS • Tables, Keys & Constraints
• SQL Fundamentals • CRUD Operations
• Queries & Filtering • Aggregate Functions
• Wildcards & UNION • JOINs (all types)
• Nested Queries • ON DELETE rules
• Triggers • ER Diagrams & Schema Design
Contents
1 Introduction to Databases 4
1.1 What is a Database? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Database Management Systems (DBMS) . . . . . . . . . . . . . . . . . . . 4
1.3 Relational vs. Non-Relational Databases . . . . . . . . . . . . . . . . . . . 4
1.4 CRUD The Four Core Operations . . . . . . . . . . . . . . . . . . . . . 4
3 SQL Basics 6
3.1 What is SQL? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2 SQL Sub-languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.3 SQL Data Types (MySQL) . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
8 Aggregate Functions 14
8.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
8.2 GROUP BY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
8.3 HAVING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
8.4 Full SELECT Query Order . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
9 Wildcards 15
1
SQL & Database Complete Notes freeCodeCamp · Mike Dane
10 UNION 16
10.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
11 JOINs 17
11.1 What is a JOIN? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
11.2 Types of JOINs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
11.3 JOIN Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
11.4 Multiple JOINs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
13 ON DELETE Rules 19
13.1 Referential Integrity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
14 Triggers 20
14.1 What is a Trigger? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
14.2 Trigger Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
14.3 Trigger Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
15 ER Diagrams 22
15.1 Entity-Relationship Model . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
15.2 ER Diagram Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
15.3 Relationship Cardinality . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
15.4 Weak Entities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
15.5 Designing an ER Diagram: Step-by-Step . . . . . . . . . . . . . . . . . . . 22
17 Extended Topics 24
17.1 String Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
17.2 Date and Time Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
17.3 CASE Expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
17.4 Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
17.5 Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
17.6 Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
18 Quick Reference 25
18.1 Most-Used Commands at a Glance . . . . . . . . . . . . . . . . . . . . . . 25
19 Practice Questions 26
19.1 Section 1: Database Fundamentals . . . . . . . . . . . . . . . . . . . . . . 26
19.2 Section 2: DDL Creating Tables . . . . . . . . . . . . . . . . . . . . . . 26
19.3 Section 3: DML Inserting, Updating, Deleting . . . . . . . . . . . . . . 27
19.4 Section 4: SELECT Queries . . . . . . . . . . . . . . . . . . . . . . . . . . 27
19.5 Section 5: Aggregate Functions . . . . . . . . . . . . . . . . . . . . . . . . 27
2
SQL & Database Complete Notes freeCodeCamp · Mike Dane
3
SQL & Database Complete Notes freeCodeCamp · Mike Dane
1 Introduction to Databases
Databases are everywhere: phone contacts, social media posts, bank transactions, e-
commerce orders. Even a simple written list in a notebook is technically a database. The
need for computers is to manage large, structured collections of information eciently.
Structure
Schema
Tables with rows & columns Documents, key-value, graphs
Query lang
Fixed, predened Flexible / dynamic
Scaling
SQL (standardized) Varies by system
ACID
Vertical (mostly) Horizontal (mostly)
Best for
Strong guarantees Often relaxed
Structured, consistent data Unstructured / large-scale data
Note: This course focuses entirely on Relational Databases using MySQL . SQL
(Structured Query Language) is the standard language for all relational databases.
4
SQL & Database Complete Notes freeCodeCamp · Mike Dane
name
Has a unique .
columns
Contains (attributes/elds) with specic data types.
rows
Contains (records/tuples) of actual data.
Must be unique no two rows share the same primary key value.
one
A table can have only primary key.
Natural key : A key that has real-world meaning (e.g., a Social Security Number,
ISBN).
5
SQL & Database Complete Notes freeCodeCamp · Mike Dane
Composite key : A primary key composed of two or more columns together (neither
column alone is unique).
Key concept: The foreign key column in the child table must contain only values that
exist in the referenced (parent) table, or NULL.
Candidate Key : Any column (or combination) that could serve as a primary key.
Super Key : Any set of columns that uniquely identies a row (includes candidate
keys and their supersets).
3 SQL Basics
Declarative : You describe what you want, not how to get it.
Standardized : Core SQL works across MySQL, PostgreSQL, Oracle, SQL Server,
etc.
6
SQL & Database Complete Notes freeCodeCamp · Mike Dane
7
SQL & Database Complete Notes freeCodeCamp · Mike Dane
8 SHOW DATABASES;
9
10 -- Delete a database (irreversible!)
11 DROP DATABASE company;
Listing 2: Basic database management
Full example:
1 CREATE TABLE student (
2 student_id INT AUTO_INCREMENT PRIMARY KEY,
3 name VARCHAR(20) NOT NULL,
4 major VARCHAR(20) DEFAULT 'Undecided',
5 gpa DECIMAL(3,2)
6 );
Listing 4: Creating a student table
4.3 Constraints
Constraint Meaning
NOT NULL The column cannot contain a NULL value
UNIQUE All values in the column must be distinct
PRIMARY KEY Combines NOT NULL + UNIQUE; uniquely iden-
ties each row
FOREIGN KEY Value must exist in the referenced table's primary
key
DEFAULT value Sets a default value when none is provided
AUTO_INCREMENT Automatically increments an integer value
(MySQL)
CHECK (expr) Restricts values to those satisfying the expression
8
SQL & Database Complete Notes freeCodeCamp · Mike Dane
5.1 INSERT
1 -- Insert with all columns
2 INSERT INTO student VALUES (1, 'Alice', 'Biology', 3.8);
3
4 -- Insert specific columns (others get default/NULL)
5 INSERT INTO student (name, major)
6 VALUES ('Bob', 'Chemistry');
7
8 -- Insert multiple rows at once
9 INSERT INTO student (name, major, gpa) VALUES
10 ('Claire', 'Biology', 3.9),
11 ('Dave', 'History', 3.1),
12 ('Emma', 'CS', 3.7);
Listing 7: INSERT syntax
9
SQL & Database Complete Notes freeCodeCamp · Mike Dane
Note: When inserting with AUTO_INCREMENT, you can pass NULL or omit the column
entirely MySQL assigns the next integer automatically.
5.2 UPDATE
1 -- General syntax
2 UPDATE table_name
3 SET column1 = value1,
4 column2 = value2
5 WHERE condition;
6
7 -- Example: change Bob's major
8 UPDATE student
9 SET major = 'Computer Science'
10 WHERE name = 'Bob';
11
12 -- Update multiple rows matching condition
13 UPDATE student
14 SET major = 'Biochemistry'
15 WHERE major = 'Biology' OR major = 'Chemistry';
Listing 8: UPDATE syntax
Warning: Omitting the WHERE clause from UPDATE updates every row in the table!
5.3 DELETE
1 -- Delete specific rows
2 DELETE FROM student
3 WHERE student_id = 2;
4
5 -- Delete rows matching a condition
6 DELETE FROM student
7 WHERE major = 'History';
8
9 -- Delete ALL rows (use TRUNCATE instead for large tables)
10 DELETE FROM student;
Listing 9: DELETE syntax
10
SQL & Database Complete Notes freeCodeCamp · Mike Dane
3
4 -- Select specific columns
5 SELECT name, major FROM student;
6
7 -- Select with alias
8 SELECT name AS student_name, gpa AS grade_point
9 FROM student;
10
11 -- Select only distinct values
12 SELECT DISTINCT major FROM student;
Listing 10: SELECT syntax
11
SQL & Database Complete Notes freeCodeCamp · Mike Dane
4 -- Descending
5 SELECT * FROM student ORDER BY gpa DESC;
6
7 -- Sort by multiple columns
8 SELECT * FROM student ORDER BY major ASC, gpa DESC;
Listing 12: ORDER BY
6.4 LIMIT
1 -- Return only the first 3 rows
2 SELECT * FROM student LIMIT 3;
3
4 -- With an OFFSET (skip 5 rows, return next 3)
5 SELECT * FROM student LIMIT 3 OFFSET 5;
6 -- shorthand:
7 SELECT * FROM student LIMIT 5, 3;
Listing 13: LIMIT clause
Table Description
employee All employees; foreign key to branch
and super (manager)
branch Company branches; foreign key to
manager (employee)
client Clients the company works with
works_with Junction table: which employee works
with which client
branch_supplier Suppliers for each branch
12
SQL & Database Complete Notes freeCodeCamp · Mike Dane
9 birth_day DATE,
10 sex CHAR(1),
11 salary INT,
12 super_id INT, -- self-referential FK
13 branch_id INT
14 );
15
16 CREATE TABLE branch (
17 branch_id INT PRIMARY KEY,
18 branch_name VARCHAR(40),
19 mgr_id INT,
20 mgr_start_date DATE,
21 FOREIGN KEY (mgr_id) REFERENCES employee(emp_id)
22 ON DELETE SET NULL
23 );
24
25 -- Now add FK to employee
26 ALTER TABLE employee
27 ADD FOREIGN KEY (branch_id) REFERENCES branch(branch_id)
28 ON DELETE SET NULL;
29
30 ALTER TABLE employee
31 ADD FOREIGN KEY (super_id) REFERENCES employee(emp_id)
32 ON DELETE SET NULL;
33
34 CREATE TABLE client (
35 client_id INT PRIMARY KEY,
36 client_name VARCHAR(40) NOT NULL,
37 branch_id INT,
38 FOREIGN KEY (branch_id) REFERENCES branch(branch_id)
39 ON DELETE SET NULL
40 );
41
42 CREATE TABLE works_with (
43 emp_id INT,
44 client_id INT,
45 total_sales INT,
46 PRIMARY KEY (emp_id, client_id), -- composite PK
47 FOREIGN KEY (emp_id) REFERENCES employee(emp_id) ON DELETE CASCADE,
48 FOREIGN KEY (client_id) REFERENCES client(client_id) ON DELETE CASCADE
49 );
50
51 CREATE TABLE branch_supplier (
52 branch_id INT,
53 supplier_name VARCHAR(40),
54 supply_type VARCHAR(40),
55 PRIMARY KEY (branch_id, supplier_name),
56 FOREIGN KEY (branch_id) REFERENCES branch(branch_id) ON DELETE CASCADE
57 );
Listing 14: Creating tables with self-referential and circular FKs
13
SQL & Database Complete Notes freeCodeCamp · Mike Dane
Circular Foreign Key problem: employee needs branch_id and branch needs
mgr_id (an employee). Neither table can be created rst with both FKs. The
solution is to create both tables rst without the FK, then ALTER TABLE to add it.
8 Aggregate Functions
8.1 Overview
Aggregate functions compute a single result from a set of rows.
Function Description
COUNT(expr) Number of non-NULL values (or rows if *)
SUM(expr) Total sum
AVG(expr) Average value
MIN(expr) Minimum value
MAX(expr) Maximum value
8.2 GROUP BY
GROUP BY splits rows into groups, and aggregates are applied per group.
1 -- Total sales per employee
2 SELECT emp_id, SUM(total_sales) AS total
3 FROM works_with
4 GROUP BY emp_id;
5
6 -- Count employees by sex
7 SELECT sex, COUNT(*) AS count
14
SQL & Database Complete Notes freeCodeCamp · Mike Dane
8 FROM employee
9 GROUP BY sex;
10
11 -- Average salary per branch
12 SELECT branch_id, AVG(salary) AS avg_salary
13 FROM employee
14 GROUP BY branch_id;
Listing 16: GROUP BY
8.3 HAVING
HAVING lters the groups produced by GROUP BY (like WHERE but for groups).
WHERE vs HAVING:
WHERE lters individual rows before grouping.
HAVING lters groups after aggregation.
You cannot use aggregate functions in WHERE; use HAVING instead.
Order Clause
1 FROM (and JOIN)
2 WHERE
3 GROUP BY
4 HAVING
5 SELECT
6 ORDER BY
7 LIMIT
9 Wildcards
15
SQL & Database Complete Notes freeCodeCamp · Mike Dane
Wildcard Meaning
% Matches zero or more characters
_ Matches exactly one character
10 UNION
10.1 Overview
UNION combines the result sets of two or more SELECT statements into a single result set.
Rules:
Each SELECT must return the same number of columns.
Corresponding columns must have compatible data types.
UNION removes duplicates; UNION ALL keeps them.
The column names in the result come from the rst SELECT.
1 -- Combine employee first names with client names
2 SELECT first_name AS name FROM employee
3 UNION
4 SELECT client_name FROM client;
5
6 -- Combine salaries and total sales into one "money" column
7 SELECT salary AS money, 'Salary' AS type
16
SQL & Database Complete Notes freeCodeCamp · Mike Dane
8 FROM employee
9 UNION ALL
10 SELECT total_sales, 'Sales'
11 FROM works_with;
12
13 -- All branch names and client names (with duplicates removed)
14 SELECT branch_name FROM branch
15 UNION
16 SELECT client_name FROM client
17 UNION
18 SELECT supplier_name FROM branch_supplier;
Listing 19: UNION examples
11 JOINs
17
SQL & Database Complete Notes freeCodeCamp · Mike Dane
3 FROM employee AS e
4 LEFT JOIN branch AS b
5 ON e.branch_id = b.branch_id;
Listing 21: LEFT JOIN
12.1 Overview
A subquery (nested query) is a SELECT statement embedded inside another SQL state-
ment. The inner query runs rst and its result is used by the outer query.
18
SQL & Database Complete Notes freeCodeCamp · Mike Dane
3 FROM employee
4 WHERE salary > (
5 SELECT AVG(salary) FROM employee
6 );
Listing 25: Subquery in WHERE
13 ON DELETE Rules
19
SQL & Database Complete Notes freeCodeCamp · Mike Dane
Rule Behaviour
ON DELETE CASCADE Automatically delete the child rows too
ON DELETE SET NULL Set the FK column to NULL in the child rows
ON DELETE SET DEFAULT Set the FK column to its DEFAULT value (less
common)
ON DELETE RESTRICT (default) Prevent the parent deletion if child
rows exist
ON DELETE NO ACTION Same as RESTRICT in MySQL
Rule of thumb:
Use CASCADE for dependent records (junction tables, order items).
Use SET NULL for optional relationships (an employee without a branch still exists).
Use RESTRICT when deletion should never happen (strict data integrity).
14 Triggers
Use cases: auditing changes, enforcing complex business rules, automatic logging, main-
taining derived data.
20
SQL & Database Complete Notes freeCodeCamp · Mike Dane
7 BEGIN
8 -- SQL statements
9 -- Use [Link] to access the new row value
10 -- Use [Link] to access the old row value
11 END$$
12
13 DELIMITER ;
Listing 29: Trigger syntax
1 DELIMITER $$
2 CREATE TRIGGER before_employee_delete
3 BEFORE DELETE ON employee
4 FOR EACH ROW
5 BEGIN
6 IF [Link] > 100000 THEN
7 SIGNAL SQLSTATE '45000'
8 SET MESSAGE_TEXT = 'Cannot delete high-salary employee';
9 END IF;
10 END$$
11 DELIMITER ;
Listing 31: Prevent deletion of important employees
15 ER Diagrams
21
SQL & Database Complete Notes freeCodeCamp · Mike Dane
Notation Meaning
1:1 One-to-One (e.g., one employee has one ID badge)
1:N One-to-Many (e.g., one branch has many employees)
N:M Many-to-Many (e.g., employees work with many clients)
Participation Constraints:
Total participation (double line): every entity instance must participate.
Example: An exam (week 1 exam, week 2 exam) within a class is a weak entity; the
exam is identied by the class it belongs to plus the exam number.
22
SQL & Database Complete Notes freeCodeCamp · Mike Dane
17 Extended Topics
23
SQL & Database Complete Notes freeCodeCamp · Mike Dane
1 SELECT first_name,
2 salary,
3 CASE
4 WHEN salary >= 70000 THEN 'High'
5 WHEN salary >= 50000 THEN 'Medium'
6 ELSE 'Low'
7 END AS salary_band
8 FROM employee;
Listing 35: CASE expression
17.4 Indexes
An index is a data structure that speeds up SELECT queries at the cost of slightly slower
INSERT/UPDATE/DELETE (maintaining the index).
24
SQL & Database Complete Notes freeCodeCamp · Mike Dane
9
10 -- Remove an index
11 DROP INDEX idx_last_name ON employee;
Listing 36: Index management
17.5 Views
A view is a saved SELECT query that behaves like a virtual table.
1 -- Create a view
2 CREATE VIEW employee_details AS
3 SELECT e.first_name, e.last_name,
4 b.branch_name, [Link]
5 FROM employee e
6 JOIN branch b ON e.branch_id = b.branch_id;
7
8 -- Query the view like a table
9 SELECT * FROM employee_details WHERE salary > 60000;
10
11 -- Drop a view
12 DROP VIEW employee_details;
Listing 37: Creating and using views
17.6 Transactions
A transaction is a unit of work that either all succeeds or all fails (ACID).
1 START TRANSACTION;
2
3 UPDATE account SET balance = balance - 500 WHERE acc_id = 1;
4 UPDATE account SET balance = balance + 500 WHERE acc_id = 2;
5
6 -- If everything is OK:
7 COMMIT;
8
9 -- If something went wrong:
10 -- ROLLBACK;
Listing 38: Transaction example
18 Quick Reference
25
SQL & Database Complete Notes freeCodeCamp · Mike Dane
Command Purpose
CREATE DATABASE db; Create a new database
USE db; Switch to a database
SHOW TABLES; List tables
DESCRIBE table; Show table structure
CREATE TABLE t (...); Create a table
ALTER TABLE t ADD col type; Add a column
DROP TABLE t; Delete a table
INSERT INTO t VALUES (...); Insert a row
SELECT * FROM t; Read all rows
SELECT col FROM t WHERE cond; Filtered read
UPDATE t SET col=val WHERE cond; Modify rows
DELETE FROM t WHERE cond; Remove rows
SELECT ...JOIN ...ON ...; Combine tables
SELECT ...GROUP BY col; Aggregate by group
SELECT ...HAVING cond; Filter groups
SELECT ...LIKE 'pat%'; Pattern match
SELECT A UNION SELECT B; Combine result sets
19 Practice Questions
2. Explain the four CRUD operations with their corresponding SQL commands.
3. What distinguishes a surrogate key from a natural key ? Give an example of each.
2. Create a book table with columns: book_id (auto-increment PK), title (max 100
chars, not null), author (max 50 chars), isbn (13 chars, unique), price (decimal, 2
decimal places), published_date (date).
4. Create a member table with member_id (PK), name, email (unique), join_date.
26
SQL & Database Complete Notes freeCodeCamp · Mike Dane
5. Create aloan table linking members and books with loan_date, due_date, and
return_date. Include appropriate foreign keys with ON DELETE CASCADE.
2. Write a LEFT JOIN to nd all members and any loans they have (include members
with no loans).
27
SQL & Database Complete Notes freeCodeCamp · Mike Dane
3. Write a RIGHT JOIN to nd all books and whether they are currently on loan.
4. Write a query joining all three tables to show: member name, book title, loan date,
and due date.
5. Find all books that have never been loaned (hint: LEFT JOIN + WHERE ...IS NULL).
2. Find all members who have borrowed more than one book.
4. Find all books that have been borrowed by at least one member (using IN subquery
and also using EXISTS).
5. Rewrite the EXISTS query from the previous question as a JOIN and compare.
3. Write a UNION query combining member names and book titles into a single list labelled
item.
4. What is the dierence between UNION and UNION ALL? Write an example of each.
2. Write a BEFORE DELETE trigger that prevents books from being deleted if they are
currently on loan.
3. Create a view active_loans that shows all current (unreturned) loans with member
names and book titles.
4. Query the active_loans view to nd loans that are overdue (due date before today).
2. Identify which relationships in the university schema are 1:N and which are N:M.
3. Convert the N:M relationship between Student and Course into a junction table. What
additional attribute(s) might you add?
5. Explain the dierence between total and partial participation with an example.
28
SQL & Database Complete Notes freeCodeCamp · Mike Dane
6. For a 1:1 relationship, on which side should the foreign key be placed, and why?
2. Ranking: Without using window functions, nd the second-highest salary in the
employee table.
3. Pivot: Using conditional aggregation (SUM(CASE WHEN...)), write a query that shows,
for each branch, the count of male and female employees as separate columns.
5. Optimization: You have a table of 10 million orders. The query SELECT * FROM
orders WHERE customer_email = 'test@[Link]' is slow. How would you x it?
Write the SQL.
Answer Hints
Selected Hints
Challenge Q3 (Pivot):
SELECT branch_id,
SUM(CASE WHEN sex = 'M' THEN 1 ELSE 0 END) AS males,
SUM(CASE WHEN sex = 'F' THEN 1 ELSE 0 END) AS females
FROM employee
29
SQL & Database Complete Notes freeCodeCamp · Mike Dane
GROUP BY branch_id;
Notes based on SQL Tutorial Full Database Course for Beginners by Mike Dane /
[Link].
30