SQL Course Introduction
SQL Study Notes
Introduction to Databases and SQL
A database is a collection of data stored in a format that can be easily accessed. To manage databases, we use a Database Management System (DBMS). We connect to a DBMS and send instructions to query or modify data; the DBMS executes them and returns results.
Databases are classified into two categories:
Relational databases – data is stored in tables linked by relationships. Each table stores data about a specific object (e.g., customers, products, orders). SQL (Structured Query Language) is the language used to work with relational DBMS.
Non-relational (NoSQL) databases – do not use tables or relationships. They have their own query languages and do not understand SQL.
Popular relational DBMS include MySQL, SQL Server, and Oracle. Each has a slightly different SQL flavor, but all follow the standard SQL specification, making most code portable. This course uses MySQL, the most popular open-source database.
SQL (often pronounced "sequel") was originally developed at IBM in the 1970s and called SEQUEL (Structured English Query Language). The name was shortened to SQL because SEQUEL was trademarked by an airplane company. Both pronunciations are acceptable.
Installing MySQL
On macOS
Go to mysql.com → Downloads → MySQL Community Edition → MySQL Community Server.
Download the DMG archive for macOS.
Open the DMG and double-click the package installer. Follow the wizard, accept the license, and set a root password.
After installation, download MySQL Workbench (the graphical management tool) from the same downloads page.
Open the DMG and drag MySQL Workbench into the Applications folder.
Launch MySQL Workbench; a default connection may appear. If not, create a new connection:
Connection name:
local instanceConnection method: TCP/IP
Hostname:
127.0.0.1, Port:3306Username:
rootStore the root password in the keychain.
Test the connection.
On Windows
Go to mysql.com → Downloads → MySQL Community Edition → MySQL Community Server.
Download the MySQL Installer for Windows (recommended method).
Run the installer, select Developer Default setup type.
The installer will download and install MySQL Server, MySQL Workbench, and other components. Follow prompts, accept defaults.
Set a password for the root user when prompted.
After installation, the installer will launch MySQL Workbench automatically.
Creating the Course Databases
Download the supplementary SQL script file (e.g.,
create_databases.sql) provided with the course.Open MySQL Workbench, go to File → Open SQL Script, and select the file.
Execute the entire script (click the lightning bolt icon or press ⌘ + Shift + Enter on Mac, or Ctrl + Shift + Enter on Windows).
Refresh the Schemas panel to see the new databases (prefixed with
sql_).
Writing Your First SQL Query
Selecting a Database
Use the USE statement to choose a database:
USE sql_store;After execution, the database name appears bold in the Navigator panel.
Basic SELECT Statement
SELECT *
FROM customers;SELECTspecifies the columns to retrieve. Use*for all columns.FROMspecifies the table.Optional clauses:
WHERE(filter),ORDER BY(sort).Statements are terminated with a semicolon (
;).Line breaks, spaces, and tabs are ignored; capitalize SQL keywords for readability.
Three Optional Clauses in Order
SELECT column(s)
FROM table
WHERE condition
ORDER BY column(s);The SELECT Clause in Detail
Specifying Columns
Instead of *, list column names (improves performance on large tables):
SELECT first_name, last_name, points
FROM customers;Arithmetic Expressions
Use operators: +, -, *, /, % (modulo).
SELECT points, points * 10 + 100 AS discount_factor
FROM customers;Order of operations: multiplication/division before addition/subtraction. Use parentheses to override.
Use the
ASkeyword to create an alias for a column. For aliases with spaces, surround with quotes ('discount factor'or"discount factor").
Removing Duplicates
Use DISTINCT to get unique values:
SELECT DISTINCT state
FROM customers;Exercise: Calculate New Price from Products
SELECT name, unit_price, unit_price * 1.1 AS new_price
FROM products;The WHERE Clause
Comparison Operators
Operator | Meaning |
|---|---|
| Equal to |
| Not equal to |
| Greater than |
| Greater than or equal |
| Less than |
| Less than or equal |
Strings are enclosed in single quotes (case-insensitive by default).
Dates are also enclosed in quotes, using format
YYYY-MM-DD.
Examples
-- Customers with points > 3000
SELECT * FROM customers WHERE points > 3000;
-- Customers in Virginia
SELECT * FROM customers WHERE state = 'VA';
-- Customers born after Jan 1, 1990
SELECT * FROM customers WHERE birth_date > '1990-01-01';Exercise: Orders Placed This Year
SELECT * FROM orders WHERE order_date >= '2019-01-01';Combining Multiple Conditions
AND, OR, NOT
AND: both conditions must be true.
OR: at least one condition must be true.
NOT: negates a condition.
Logical Operator Precedence
AND is evaluated before OR. Use parentheses to change order and increase clarity.
-- Customers born after 1990 OR (points > 1000 AND live in VA)
SELECT *
FROM customers
WHERE birth_date > '1990-01-01'
OR (points > 1000 AND state = 'VA');Simplifying NOT
Apply De Morgan's laws:
-- Instead of NOT (condition1 OR condition2)
-- Rewrite as: NOT condition1 AND NOT condition2Exercise: Order Items with Total > 30 for Order #6
SELECT *
FROM order_items
WHERE order_id = 6 AND unit_price * quantity > 30;The IN Operator
Used to compare an attribute to a list of values. Shorter than multiple OR conditions.
-- Customers in VA, FL, or GA
SELECT *
FROM customers
WHERE state IN ('VA', 'FL', 'GA');
-- Customers NOT in those states
SELECT *
FROM customers
WHERE state NOT IN ('VA', 'FL', 'GA');Exercise: Products with Quantity in Stock 49, 38, or 72
SELECT *
FROM products
WHERE quantity_in_stock IN (49, 38, 72);The BETWEEN Operator
Check if a value falls within a range (inclusive of both ends).
-- Customers with points between 1000 and 3000
SELECT *
FROM customers
WHERE points BETWEEN 1000 AND 3000;Exercise: Customers Born Between 1990-01-01 and 2000-01-01
SELECT *
FROM customers
WHERE birth_date BETWEEN '1990-01-01' AND '2000-01-01';The LIKE Operator
Used for pattern matching on strings.
%– matches any number of characters (zero or more)._– matches exactly one character.
Examples
-- Last names starting with 'b'
SELECT * FROM customers WHERE last_name LIKE 'b%';
-- Last names ending with 'y'
SELECT * FROM customers WHERE last_name LIKE '%y';
-- Last names containing 'e'
SELECT * FROM customers WHERE last_name LIKE '%e%';
-- Last names exactly 6 characters long, ending with 'y'
SELECT * FROM customers WHERE last_name LIKE '_____y';Exercises
Customers whose address contains 'trail' or 'avenue':
SELECT * FROM customers WHERE address LIKE '%trail%' OR address LIKE '%avenue%';Customers whose phone numbers end with 9:
SELECT * FROM customers WHERE phone LIKE '%9';
Regular Expressions (REGEXP)
More powerful than LIKE for complex patterns.
Symbol | Meaning |
|---|---|
| Beginning of string |
| End of string |
| Logical OR (multiple patterns) |
| Match any single character in set |
| Range of characters |
Examples
-- Customers with 'field' in last name (same as LIKE '%field%')
SELECT * FROM customers WHERE last_name REGEXP 'field';
-- Last name starts with 'field'
SELECT * FROM customers WHERE last_name REGEXP '^field';
-- Last name ends with 'field'
SELECT * FROM customers WHERE last_name REGEXP 'field$';
-- Last name contains 'field' or 'mac'
SELECT * FROM customers WHERE last_name REGEXP 'field|mac';
-- Last name contains 'ge', 'ie', or 'me'
SELECT * FROM customers WHERE last_name REGEXP '[gim]e';
-- Last name contains 'e' followed by any letter from f to m
SELECT * FROM customers WHERE last_name REGEXP 'e[f-m]';Exercises
First names are 'Elka' or 'Ambur':
SELECT * FROM customers WHERE first_name REGEXP 'Elka|Ambur';Last names end with 'ey' or 'on':
SELECT * FROM customers WHERE last_name REGEXP 'ey$|on$';Last names start with 'my' or contain 'se':
SELECT * FROM customers WHERE last_name REGEXP '^my|se';Last names contain 'b' followed by 'r' or 'u':
SELECT * FROM customers WHERE last_name REGEXP 'b[ru]'; -- or: last_name REGEXP 'br|bu'
NULL Values
NULL means absence of a value. Use IS NULL or IS NOT NULL to test.
-- Customers without a phone
SELECT * FROM customers WHERE phone IS NULL;
-- Customers with a phone
SELECT * FROM customers WHERE phone IS NOT NULL;Exercise: Orders Not Yet Shipped
SELECT *
FROM orders
WHERE shipped_date IS NULL;
-- Alternatively: shipper_id IS NULLSorting Data with ORDER BY
Default Sorting
Primary key column is used by default. You can sort by any column, not just those in the SELECT clause (MySQL-specific).
SELECT first_name, last_name
FROM customers
ORDER BY birth_date;Ascending and Descending
-- Descending order
SELECT * FROM customers ORDER BY first_name DESC;
-- Multiple columns: first by state, then by first name
SELECT * FROM customers ORDER BY state, first_name;
-- Mix ordering
SELECT * FROM customers ORDER BY state DESC, first_name ASC;Sorting by Alias or Expression
SELECT first_name, last_name, points * 10 AS discount
FROM customers
ORDER BY discount, first_name;Avoid Sorting by Column Position
-- BAD: ORDER BY 1, 2 (positions) – fragile; avoidExercise: Order Items for Order #2 Sorted by Total Price Descending
SELECT *, quantity * unit_price AS total_price
FROM order_items
WHERE order_id = 2
ORDER BY total_price DESC;Limiting Results with LIMIT
-- Get first 3 customers
SELECT * FROM customers LIMIT 3;
-- Get 3 customers after skipping first 6 (paging)
SELECT * FROM customers LIMIT 6, 3;LIMITmust be the last clause (afterORDER BY).
Exercise: Top 3 Most Loyal Customers (Highest Points)
SELECT *
FROM customers
ORDER BY points DESC
LIMIT 3;Joining Tables
INNER JOIN
Combine rows from two tables where a condition is met.
SELECT order_id, first_name, last_name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id;Use table aliases (
o,c) to simplify code.When column names are the same in both tables, qualify them with the table alias (e.g.,
o.customer_id).
Joining Across Databases
SELECT *
FROM order_items oi
JOIN sql_inventory.products p ON oi.product_id = p.product_id;Prefix table name with database name when it's not in the current database.
Self Join
Join a table to itself using different aliases.
SELECT e.employee_id, e.first_name, m.first_name AS manager
FROM employees e
LEFT JOIN employees m ON e.reports_to = m.employee_id;Joining Multiple Tables
SELECT o.order_id, o.order_date, c.first_name, os.name AS status
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
JOIN order_statuses os ON o.status = os.order_status_id;Exercise: Payments with Client and Payment Method
SELECT p.date, p.invoice_id, p.amount, c.name AS client, pm.name AS payment_method
FROM payments p
JOIN clients c USING (client_id)
JOIN payment_methods pm ON p.payment_method = pm.payment_method_id;Compound Join Conditions
When tables have composite primary keys (multiple columns), join on all key columns.
SELECT *
FROM order_items oi
JOIN order_item_notes oin
ON oi.order_id = oin.order_id AND oi.product_id = oin.product_id;Simplifying with USING
If the column names are identical in both tables, replace ON with USING:
SELECT *
FROM order_items oi
JOIN order_item_notes oin USING (order_id, product_id);USING works for both inner and outer joins.
Implicit Join Syntax (Avoid)
-- Implicit inner join – easy to forget WHERE clause, causing cross join
SELECT *
FROM orders o, customers c
WHERE o.customer_id = c.customer_id;Always prefer explicit join syntax (JOIN ... ON).
Outer Joins
LEFT JOIN: returns all rows from the left table, even if no match in the right table. Non-matching rows show
NULLfor right table columns.RIGHT JOIN: returns all rows from the right table. Often swapped for LEFT JOIN for clarity.
Example: All Customers Whether They Have Orders or Not
SELECT c.customer_id, c.first_name, o.order_id
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id;Outer Join with Multiple Tables
SELECT o.order_id, o.order_date, c.first_name AS customer, sh.name AS shipper, os.name AS status
FROM orders o
JOIN customers c USING (customer_id)
LEFT JOIN shippers sh USING (shipper_id)
JOIN order_statuses os ON o.status = os.order_status_id;Use
LEFT JOINfor tables where some rows may not have a matching record (e.g., orders without shippers).
Best Practice: Prefer
LEFT JOINoverRIGHT JOINfor readability.
Natural Joins
The database engine automatically joins tables based on columns with the same name. Not recommended because it may produce unexpected results.
SELECT *
FROM orders
NATURAL JOIN customers;CROSS JOIN
Combines every row from the first table with every row from the second table (Cartesian product). Useful when you need all combinations (e.g., sizes × colors).
Explicit Syntax
SELECT c.first_name, p.name
FROM customers c
CROSS JOIN products p
ORDER BY c.first_name;Implicit Syntax
SELECT c.first_name, p.name
FROM customers c, products p
ORDER BY c.first_name;Exercise: Cross Join Shippers and Products
-- Explicit
SELECT sh.name AS shipper, p.name AS product
FROM shippers sh
CROSS JOIN products p;
-- Implicit
SELECT sh.name AS shipper, p.name AS product
FROM shippers sh, products p;Unions
Combine rows from multiple queries into a single result set. Each query must have the same number of columns. Column names come from the first query.
SELECT order_id, order_date, 'Active' AS status
FROM orders
WHERE order_date >= '2019-01-01'
UNION
SELECT order_id, order_date, 'Archived' AS status
FROM orders
WHERE order_date < '2019-01-01';Exercise: Customer Type Based on Points
SELECT customer_id, first_name, points, 'Bronze' AS type
FROM customers WHERE points < 2000
UNION
SELECT customer_id, first_name, points, 'Silver' AS type
FROM customers WHERE points BETWEEN 2000 AND 3000
UNION
SELECT customer_id, first_name, points, 'Gold' AS type
FROM customers WHERE points > 3000
ORDER BY first_name;Inserting Data
Insert a Single Row
INSERT INTO customers (first_name, last_name, birth_date, address, city, state)
VALUES ('John', 'Smith', '1990-01-01', '123 Main St', 'Los Angeles', 'CA');For auto-increment primary keys, either omit the column or use
DEFAULT.For optional columns, use
NULLorDEFAULT.You can list columns in any order, but values must match.
Insert Multiple Rows
INSERT INTO shippers (name)
VALUES ('Shipper1'),
('Shipper2'),
('Shipper3');Insert Hierarchical Data (Parent-Child)
Insert into the parent table.
Use
LAST_INSERT_ID()to get the newly generated primary key.Insert child rows using that key.
INSERT INTO orders (customer_id, order_date, status)
VALUES (1, '2019-01-02', 1);
INSERT INTO order_items
VALUES (LAST_INSERT_ID(), 1, 1, 2.95),
(LAST_INSERT_ID(), 2, 1, 3.95);Copying Data Between Tables
Using CREATE TABLE AS
CREATE TABLE orders_archive AS
SELECT * FROM orders;Copies structure and data, but primary key, auto-increment, and other attributes are not preserved.
Using INSERT INTO with Subquery
INSERT INTO orders_archive
SELECT *
FROM orders
WHERE order_date < '2019-01-01';Exercise: Create Invoices Archive with Client Name
CREATE TABLE invoices_archive AS
SELECT i.invoice_id, i.number, c.name AS client, i.invoice_total, i.payment_total,
i.invoice_date, i.due_date, i.payment_date
FROM invoices i
JOIN clients c USING (client_id)
WHERE i.payment_date IS NOT NULL;Updating Data
Update Single Row
UPDATE invoices
SET payment_total = 10, payment_date = '2019-03-01'
WHERE invoice_id = 1;Update Using Expressions
UPDATE invoices
SET payment_total = invoice_total * 0.5,
payment_date = due_date
WHERE invoice_id = 3;Update Multiple Rows
-- Update all invoices for client 3
UPDATE invoices
SET payment_total = invoice_total * 0.5, payment_date = due_date
WHERE client_id = 3;Safe Update Mode: In MySQL Workbench, by default you can only update single rows. Disable it in Preferences → SQL Editor → uncheck "Safe Updates", then reconnect.
Using Subqueries in UPDATE
When you only have a client name, find the ID first:
UPDATE invoices
SET payment_total = invoice_total * 0.5, payment_date = due_date
WHERE client_id = (SELECT client_id FROM clients WHERE name = 'Myworks');For multiple IDs, use IN:
UPDATE invoices
SET payment_total = invoice_total * 0.5
WHERE client_id IN (SELECT client_id FROM clients WHERE state IN ('CA', 'NY'));Exercise: Update Comments for Gold Customers
UPDATE orders
SET comments = 'Gold customer'
WHERE customer_id IN (SELECT customer_id FROM customers WHERE points > 3000);Deleting Data
DELETE FROM invoices
WHERE invoice_id = 1;Without a
WHEREclause, all rows are deleted.Can use subqueries as in
UPDATE.
Example: Delete Invoices for a Specific Client by Name
DELETE FROM invoices
WHERE client_id = (SELECT client_id FROM clients WHERE name = 'Myworks');Restoring Databases
After performing data modifications, restore the original databases by executing the course script again:
File → Open SQL Script → select
create_databases.sql.Execute the script.
Refresh the Schemas panel.
This resets all tables to their initial state.

Ask anything
We've read this whole study set, so questions about it get the best answers.