SQL — One-Page Study Guide
Core idea: SQL (Structured Query Language) is used to create, retrieve, modify, and manage data stored in relational databases.
1. Database & Table Basics
Database = organized collection of related data. Table = rows (records) + columns (fields). Primary key uniquely identifies each row. Foreign key links one table to
another.
Common data types: INT, DECIMAL, VARCHAR, DATE, DATETIME, BOOLEAN.
2. Essential SQL Commands
CREATE DATABASE db_name; CREATE TABLE table_name (...); INSERT INTO table_name (...) VALUES (...);
SELECT columns FROM table; UPDATE table SET column=value WHERE condition; DELETE FROM table WHERE condition;
ALTER TABLE changes a table's structure. DROP removes a database/table. Use DROP carefully because it removes the object and its data.
3. SELECT — Retrieving Data
SELECT * returns all columns. Choose specific columns to return only what you need.
WHERE filters rows. Operators: =, <>, >, <, >=, <=. Combine conditions with AND, OR, and NOT.
ORDER BY sorts results: ASC (ascending) or DESC (descending). DISTINCT removes duplicate result values.
LIKE searches patterns: 'A%' starts with A; '%A' ends with A; '%A%' contains A. IN checks a list of values. BETWEEN checks a range.
4. Aggregate Functions
COUNT() counts rows/values; SUM() totals numeric values; AVG() calculates an average; MIN() finds the smallest; MAX() finds the largest.
GROUP BY groups rows before aggregate calculations. HAVING filters groups after GROUP BY; WHERE filters rows before grouping.
5. Joins
INNER JOIN returns matching rows from both tables. LEFT JOIN keeps every row from the left table plus matching rows from the right. Joins normally connect a
primary key to a related foreign key.
6. NULL & Constraints
NULL means missing/unknown—not zero or an empty string. Test with IS NULL / IS NOT NULL. Common constraints: PRIMARY KEY, FOREIGN KEY, NOT NULL,
UNIQUE, CHECK, DEFAULT.
7. Query Order to Remember
SELECT → FROM → JOIN → WHERE → GROUP BY → HAVING → ORDER BY
Quick Practice
1) Return all customers from California. 2) Find the average order amount. 3) Count customers by state. 4) Join customers with their orders using the customer ID.