SQL Fundamentals
SQL Study Notes
What SQL Is and Why It Matters
SQL, or Structured Query Language, is the primary language used to communicate with relational databases. It allows applications to create, retrieve, update, and delete stored data.
Most backend applications use SQL alongside another programming language such as JavaScript, Python, Go, or TypeScript. The programming language handles application logic, while SQL handles interaction with the database.
Common SQL database systems include:
PostgreSQL
MySQL
SQLite
Microsoft SQL Server
Oracle
CockroachDB
A database is software that stores and organizes large amounts of data in a computer’s file system. It can be viewed as an automated and highly capable version of a spreadsheet:
Spreadsheets require manual actions such as clicking, dragging, and editing.
Databases can be controlled through code.
SQL queries automate data creation, retrieval, modification, and deletion.
SQL is the language used to move data into and out of most relational database systems.
SQL and Web Application Architecture
A typical web application has three major layers:
Frontend
Runs in a browser, mobile application, or other client.
Collects user input and displays results.
Backend server
Receives requests from the frontend.
Applies business logic.
Converts requests into database operations.
Database
Stores persistent application data.
Executes SQL statements sent by the backend.
The communication flow usually looks like this:
A user performs an action in the frontend.
The frontend sends an HTTP request to the backend.
The backend interprets the request.
The backend executes an SQL statement against the database.
The database returns rows or reports the result of the operation.
The backend converts the result into a response, often JSON.
The frontend displays the response.
For example, when a user registers:
The frontend collects a username and password.
It sends an HTTP
POSTrequest to the backend.The backend creates an SQL
INSERTstatement.The database stores the new user.
The backend sends a success response to the frontend.
A frontend normally does not communicate directly with a cloud database. Direct database access from a frontend would expose sensitive credentials and bypass server-side validation and business logic.
Relational Databases and Tables
Tables, Rows, and Columns
Relational databases organize data into tables.
A table contains:
Columns: The attributes or properties stored for each record.
Rows: Individual records or entries.
Cells: Individual values where a row and column intersect.
For example, a users table might contain:
idnameageusernamebalance
Each user is represented by one row, with a value in each column.
The terms column and field are often used interchangeably, although column is the more precise database term. In a programming language, the corresponding property on an object or struct is often called a field.
SQL Statements
SQL statements generally end with a semicolon:
SELECT id FROM users;SQL keywords are generally case-insensitive. These statements are equivalent:
SELECT id FROM users;select id from users;Uppercase keywords are conventional because they make SQL easier to read, but capitalization does not usually affect execution.
The SELECT Statement
SELECT retrieves data from a database. It is the SQL equivalent of a read operation.
Selecting One Column
SELECT id FROM users;This returns the id column from every row in the users table.
Selecting Multiple Columns
Column names are separated by commas:
SELECT id, name FROM users;This returns only the id and name columns.
Selecting Every Column
The asterisk, $*$, is the wildcard operator:
SELECT * FROM users;This returns every column from every row in the table.
Although SELECT * is convenient, production queries often explicitly name the required columns. Selecting only the necessary columns can:
Reduce the amount of returned data.
Improve readability.
Avoid exposing unnecessary information.
Make application code more predictable.
SQL and NoSQL Databases
SQL Databases
An SQL database is any database that can be accessed using Structured Query Language.
Examples include:
PostgreSQL
MySQL
SQLite
Microsoft SQL Server
Oracle
CockroachDB
SQL databases tend to have more in common with one another because they share a standard query language and usually organize data into tables.
Many SQL databases are general-purpose, meaning they can support a wide variety of web applications.
NoSQL Databases
A NoSQL database is a database that does not use SQL as its primary query language. NoSQL databases do not necessarily share one common query language or data model.
Examples include:
MongoDB
Redis
Elasticsearch
Firebase
DynamoDB
NoSQL databases are often specialized:
Redis: In-memory caching and key-value storage.
Elasticsearch: Search and data aggregation.
Firebase: Real-time and mobile applications.
DynamoDB: Scalable data storage in AWS.
MongoDB: Document-oriented storage with relatively general-purpose capabilities.
NoSQL databases may use:
Document structures.
Key-value pairs.
Graphs.
Wide-column structures.
Other specialized models.
SQL databases share a query language. NoSQL databases are grouped mainly because they do not use SQL; they may otherwise be very different from one another.
SQL Versus NoSQL
SQL databases generally
Use tables, rows, and columns.
Support structured query language.
Support relational data and foreign keys.
Tend to be general-purpose.
Often reduce duplicated data through normalization.
NoSQL databases generally
Do not share one universal query language.
Often specialize in a particular use case.
May store nested or duplicated data.
May represent data as documents or key-value structures.
Can be useful when flexibility, distribution, or specialized performance is important.
There are exceptions. SQLite is an SQL database, but it is designed primarily as an embedded database for smaller applications. CockroachDB uses SQL but is designed for distributed operation and scale. MongoDB is NoSQL but can be used for many general-purpose applications.
The best database depends on the project’s requirements. PostgreSQL is often a strong default for traditional web applications, while additional systems can later be added for caching, search, real-time updates, or specialized scaling.
Database Engines and Data Types
SQLite and PostgreSQL
SQLite
SQLite is an embedded database:
The database is stored directly within an application or file.
It is useful when resources are limited.
It works well for mobile applications, small applications, and edge deployments.
It does not require a separate database server.
It has a relatively loose type system.
PostgreSQL
PostgreSQL is a server-based relational database:
It is designed for larger applications.
It supports many advanced features.
It handles large data sets and more complex queries.
It provides stricter type checking.
It is commonly used in production web applications.
SQLite may allow a value of the wrong type to be inserted into a column. PostgreSQL generally rejects such values.
For example, if a column is defined as text, SQLite may permit an integer to be inserted into it. A stricter database such as PostgreSQL would normally produce a type error.
Common SQLite Data Types
SQLite commonly uses these storage classes:
NULL: Represents the absence of a value.
INTEGER: Whole numbers, including negative numbers.
REAL: Numbers with fractional components.
TEXT: Character strings.
BLOB: Binary data.
Boolean values in SQLite are represented internally as integers:
0represents false.1represents true.
SQLite may accept the keywords TRUE and FALSE, but returned values are commonly shown as 1 and 0.
TEXT and VARCHAR
Many database systems support both TEXT and VARCHAR.
A VARCHAR usually specifies a maximum number of characters, such as VARCHAR(36). The term means variable character length.
A length limit can allow a database to make storage or performance optimizations when the maximum size is known. SQLite does not enforce text lengths in the same strict way, so simple SQLite applications often use TEXT.
Creating and Modifying Tables
The CREATE TABLE Statement
The CREATE TABLE statement creates a new table and defines its columns.
CREATE TABLE employees (
id INTEGER,
name TEXT,
age INTEGER,
is_manager BOOLEAN,
salary INTEGER
);The general structure is:
CREATE TABLE table_name (
column_name data_type,
column_name data_type
);A table definition includes:
The table name.
Column names.
Data types.
Optional constraints.
For a payment application, tables might include:
users: People who use the application.transactions: Payments sent between users.
A transactions table might contain:
CREATE TABLE transactions (
id INTEGER,
recipient_id INTEGER,
sender_id INTEGER,
note TEXT,
amount INTEGER
);Each transaction can have:
A unique transaction identifier.
A recipient.
A sender.
An optional note.
An amount of money.
Altering Tables
The ALTER TABLE statement changes an existing table.
Renaming a Table
ALTER TABLE employees
RENAME TO contractors;Renaming a Column
ALTER TABLE contractors
RENAME COLUMN salary TO invoice;Adding a Column
ALTER TABLE contractors
ADD COLUMN department TEXT;Removing a Column
ALTER TABLE contractors
DROP COLUMN department;Renaming tables or columns in production can be dangerous because existing application code may depend on the old names.
Database Schemas
A database schema describes the structure and organization of a database.
A schema includes:
The number of tables.
The names of the tables.
The columns in each table.
The data types of the columns.
Constraints.
Relationships between tables.
The schema is the database’s structural design.
There is no single perfect schema for every application. A good schema should:
Accurately model the application’s data and relationships.
Avoid unnecessary complexity.
Reduce duplicated data.
Preserve data integrity.
Leave room for future changes.
A useful design principle is to begin with the simplest schema that accurately represents the application. Complexity can be added when necessary, but unnecessary complexity is difficult to remove later.
Database Migrations
What a Migration Is
A database migration is an incremental change to a database schema.
Examples include:
Adding a column.
Adding a table.
Removing a column.
Renaming a table.
Renaming a column.
Changing a constraint.
Suppose a production users table already contains:
idusernamepassword
Adding a new birthday column is a migration.
Adding Data Structures
Adding a table or column is usually relatively safe because older application code does not depend on the new structure.
A common sequence is:
Apply the database migration.
Deploy application code that uses the new table or column.
The old application code can generally continue functioning because it does not need to use the new structure.
Removing Data Structures
Removing a table or column is more dangerous.
A safe sequence is:
Update the application code so it no longer reads or writes the resource.
Deploy the updated code.
Remove the table or column from the database.
This prevents old code from trying to access a resource that no longer exists.
Updating or Renaming Data Structures
Renaming a table or column is especially difficult because:
Old code expects the old name.
New code expects the new name.
The database must also change names.
A mismatch can cause errors during deployment.
Possible strategies include:
Scheduled Downtime
The application is temporarily shut down while the database and code are updated.
Simple to execute.
Disrupts users.
Usually a last resort.
Simultaneous Deployment
The database and application code are updated at approximately the same time.
Easy compared with more advanced methods.
May cause a short period of errors.
Risky if active users encounter the mismatch.
Copying the Table
A new table is created with the same data, and the application is gradually moved to the new table.
More robust.
Requires handling records added during the migration.
Requires a more complex migration script.
Aliasing
Some databases allow a table to temporarily have two names.
Keep the old name.
Add the new name as an alias.
Deploy code that uses the new name.
Remove the old name after the transition.
Aliasing can be the safest and simplest approach when supported.
Up and Down Migrations
An up migration moves the database forward to a newer schema version.
Examples:
Create a table.
Add a column.
Rename a column.
Delete a table.
A down migration reverses an earlier up migration.
Examples:
Delete a table that was created.
Remove a column that was added.
Rename a column back to its previous name.
Recreate a deleted table.
Down migrations are useful for rolling back a schema change when something goes wrong. However, reversing a schema does not necessarily restore data that was deleted or transformed.
Migrations should be incremental, carefully planned, and reversible whenever practical.
Constraints
A constraint is a rule enforced by the database. Constraints protect the consistency and validity of stored data.
Constraints are defined after the column’s data type:
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
username TEXT UNIQUE
);Common constraints include:
PRIMARY KEYNOT NULLUNIQUEFOREIGN KEY
Primary Keys
A primary key uniquely identifies each row in a table.
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);A primary key has several properties:
Every row must have a unique primary-key value.
A table can have only one primary key definition.
Primary-key values cannot be
NULL.Primary keys are commonly stored in an
idcolumn.
For example, two users cannot both have id = 1.
A primary key is effectively both:
A uniqueness constraint.
A non-null constraint.
Why an ID Column Is Preferable
An email address or username may appear unique today, but business requirements can change. A system might later allow:
Multiple users to share an email address.
Users to change their email address.
Different accounts to use the same display name.
A dedicated, stable id column avoids coupling the database identity of a row to changeable business data.
Unique Constraints
A UNIQUE constraint prevents duplicate values in a column.
username TEXT UNIQUEA username column with this constraint cannot contain the same username twice.
The difference between PRIMARY KEY and UNIQUE includes:
A table has one primary-key definition but may have multiple unique constraints.
A primary key cannot be null.
A unique column may allow null values depending on the database system.
A primary key is the main identity of a row; a unique constraint simply prevents duplicate values.
Not-Null Constraints
A NOT NULL constraint requires a value to be present.
name TEXT NOT NULLThis prevents a record from being inserted without a name.
Use NOT NULL for information that every valid record must contain, such as:
A user’s name.
A required email address.
A transaction amount.
A required creation timestamp.
NULL Values
Meaning of NULL
NULL represents the absence of a value.
It is different from:
An empty string:
''The number zero:
0The Boolean value false:
FALSE
For example:
username = ''means the username exists but contains zero characters.username = NULLmeans no username value exists.
In most cases, NULL is the correct representation when a value is missing.
Equivalent concepts in other languages include:
Python:
NoneJavaScript:
nullGo:
nil
Filtering NULL Values
SQL uses special syntax to test for nulls.
Finding NULL Values
SELECT name
FROM users
WHERE username IS NULL;Finding Non-NULL Values
SELECT name
FROM users
WHERE username IS NOT NULL;The equality operator should not be used to compare values with NULL, because NULL represents an unknown or absent value rather than an ordinary value.
Keys and Relationships
Foreign Keys
A foreign key is a column that references a primary key in another table.
For example, a transaction may contain a user_id that refers to a row in the users table.
A foreign-key constraint ensures that the referenced row actually exists.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT,
department_id INTEGER,
FOREIGN KEY (department_id)
REFERENCES departments(id)
);If an employee is assigned to department_id = 4, the database checks that a department with id = 4 exists.
Without the constraint, a column may still function conceptually as a reference, but the database will not automatically validate the relationship.
Foreign keys prevent orphaned references, such as:
A transaction referring to a nonexistent user.
An employee referring to a nonexistent department.
A comment referring to a nonexistent post.
Relational and Non-Relational Databases
Relational Databases
A relational database stores data in tables and provides mechanisms for relating records across tables.
Typical properties include:
Data organized into tables.
Columns representing attributes.
Rows representing records.
Primary keys identifying records.
Foreign keys connecting tables.
Queries that combine related data.
For example:
A
studentstable stores students.A
coursestable stores courses.A joining table connects students to courses.
If Sam has student ID 1, and the student-course table contains three rows with student ID 1, Sam is enrolled in three courses.
Non-Relational Databases
A non-relational database does not primarily model relationships through tables and foreign keys.
Many non-relational systems store nested documents, often resembling JSON:
{
"id": 1,
"name": "Elon",
"courses": [
{"id": 1, "name": "SQL"},
{"id": 2, "name": "Go"}
]
}This approach may duplicate course data if multiple users take the same course.
Relational Model
Stores entities separately.
Uses keys to reference related records.
Reduces duplication.
Makes many-to-many relationships explicit.
Often requires joins.
Non-Relational Model
May nest related data.
Can make reads simpler for certain use cases.
May duplicate data.
May require updating multiple copies when shared information changes.
Relational databases typically do not duplicate data, while non-relational databases often tolerate duplication in exchange for simpler or faster access.
CRUD Operations
CRUD stands for:
Create
Read
Update
Delete
These are the fundamental operations performed on stored data.
CRUD and HTTP
CRUD operations commonly correspond to HTTP methods:
Create → SQL
INSERT→ HTTPPOSTRead → SQL
SELECT→ HTTPGETUpdate → SQL
UPDATE→ HTTPPUTorPATCHDelete → SQL
DELETE→ HTTPDELETE
A backend server is often described as a CRUD server because it maps HTTP requests to database operations.
Inserting Data
The INSERT Statement
The INSERT statement adds new rows to a table.
INSERT INTO users (
id,
name,
age,
country_code,
username,
password,
is_admin
)
VALUES (
1,
'David',
34,
'US',
'david_dev',
'insert practice',
FALSE
);The order of values must match the order of the specified columns.
A second record can be inserted with another statement:
INSERT INTO users (
id,
name,
age,
country_code,
username,
password,
is_admin
)
VALUES (
2,
'Samantha',
29,
'BR',
'sammy93',
'adding records',
FALSE
);Specifying the columns explicitly is good practice because it makes the query clear and avoids depending on the table’s physical column order.
Auto-Incrementing IDs
Many SQL databases support automatically generated identifiers.
With SQLite, an integer primary key named id may automatically increment when new rows are inserted. The application can omit the ID:
INSERT INTO users (
name,
age,
country_code,
username,
password,
is_admin
)
VALUES (
'Lane',
20,
'US',
'wagslane',
'password',
FALSE
);The database chooses the next available ID.
Another common approach is using a UUID, or universally unique identifier. A UUID is a very large randomly generated identifier. Because there are so many possible UUID values, the probability of a duplicate is extremely small.
Incrementing IDs
Simple and compact.
Easy to sort.
Common in relational databases.
Usually generated sequentially.
UUIDs
Can be generated without checking the database first.
Useful in distributed systems.
Harder to guess than sequential IDs.
Larger and less human-readable.
Selecting and Filtering Data
The WHERE Clause
The WHERE clause filters rows.
SELECT name
FROM users
WHERE power_level >= 9000;Only rows satisfying the condition are returned.
The WHERE clause can compare:
Numbers.
Text.
Boolean values.
Dates.
Columns against other columns.
Boolean Filtering
SELECT username
FROM users
WHERE is_admin = TRUE;In SQLite, Boolean values may be stored and returned as 1 and 0.
Comparison Operators
Common SQL comparison operators include:
=— equal to<>or!=— not equal to<— less than>— greater than<=— less than or equal to>=— greater than or equal to
SQL uses a single equals sign for equality testing. It does not use the double-equals syntax common in languages such as JavaScript, Python, or Go.
The BETWEEN Clause
BETWEEN checks whether a value falls within an inclusive range.
SELECT name, age
FROM users
WHERE age BETWEEN 13 AND 18;This includes the boundary values 13 and 18.
The opposite can be expressed with NOT BETWEEN:
SELECT name
FROM users
WHERE age NOT BETWEEN 13 AND 18;The IN Clause
IN checks whether a value matches any value in a list.
SELECT name, age, country_code
FROM users
WHERE country_code IN ('US', 'CA', 'MX');This is equivalent to:
WHERE country_code = 'US'
OR country_code = 'CA'
OR country_code = 'MX'IN makes multiple alternatives shorter and easier to read.
The LIKE Operator
LIKE supports pattern matching.
Percent Wildcard
The percent sign matches zero or more characters.
Starts With
SELECT *
FROM users
WHERE name LIKE 'Al%';Matches names such as:
Al
Alan
Albert
Alphonse
Ends With
WHERE name LIKE '%son';Matches values ending in son.
Contains
WHERE name LIKE '%ann%';Matches values containing ann anywhere.
Underscore Wildcard
The underscore matches exactly one character.
SELECT *
FROM users
WHERE name LIKE 'Al___';This matches names that:
Begin with
Al.Contain exactly three additional characters.
Have a total length of five characters.
The patterns Al% and Al___ differ because % allows any number of characters, while each _ represents exactly one character.
Limiting and Ordering Results
The LIMIT Clause
LIMIT restricts the maximum number of rows returned.
SELECT *
FROM transactions
WHERE note LIKE '%lunch%'
LIMIT 5;This returns at most five rows.
LIMIT 5 does not guarantee that five rows are returned. If only two rows match the query, only two rows are returned.
Limiting results is useful because production tables may contain thousands or millions of rows. Retrieving every matching row can:
Consume large amounts of memory.
Slow down the database.
Slow down the backend.
Increase network traffic.
Cause application failures.
It is especially useful when inspecting unfamiliar data manually.
The ORDER BY Clause
ORDER BY sorts the result set.
Ascending Order
Ascending order is the default:
SELECT *
FROM transactions
ORDER BY amount;Numbers increase from smallest to largest.
Descending Order
SELECT *
FROM transactions
ORDER BY amount DESC;Numbers decrease from largest to smallest.
ORDER BY and LIMIT are often used together:
SELECT *
FROM users
ORDER BY completed_exercises DESC
LIMIT 10;This returns the top ten users according to the number of completed exercises.
The order of clauses matters. Sorting should occur before limiting:
SELECT *
FROM transactions
WHERE amount BETWEEN 10 AND 80
ORDER BY amount DESC
LIMIT 4;This returns the four largest matching transactions, not merely four arbitrary matching transactions.
Deleting Data
The DELETE Statement
The DELETE statement removes rows.
DELETE FROM users
WHERE id = 2;The WHERE clause is critical.
This query removes every user:
DELETE FROM users;A missing or incorrect WHERE condition can destroy an entire table’s data.
Safe Deletion Practice
Before executing a production DELETE, first execute the equivalent SELECT:
SELECT *
FROM users
WHERE id = 2;After confirming that the selected rows are exactly the intended rows, change the query to:
DELETE FROM users
WHERE id = 2;Deleting by primary key is safer than deleting by a non-unique value:
DELETE FROM users
WHERE name = 'Samantha';This might delete multiple users with the same name.
A primary-key condition targets one specific record:
DELETE FROM users
WHERE id = 2;Updating Data
The UPDATE Statement
UPDATE changes existing rows.
UPDATE users
SET is_admin = TRUE
WHERE id = 9;Multiple columns can be updated by separating assignments with commas:
UPDATE employees
SET job_title = 'Backend Engineer',
salary = 150000
WHERE id = 251;The WHERE clause determines which rows are changed. Omitting it updates every row:
UPDATE users
SET is_admin = TRUE;This would make every user an administrator and is therefore highly dangerous.
Counting and Aggregations
The COUNT Function
COUNT returns the number of rows or values.
SELECT COUNT(*)
FROM users;COUNT(*) counts rows regardless of whether individual columns contain NULL.
Counting is more reliable than assuming that the largest ID equals the number of records. If rows are deleted, IDs may contain gaps.
For example, IDs may be:
1
2
4
5
The largest ID is 5, but there are only four rows.
Aggregations
An aggregation combines multiple rows into a summarized result.
Common aggregate functions include:
COUNTSUMMAXMINAVG
It is generally preferable to store raw data and calculate summaries when needed. Storing only precomputed results can permanently discard information required for future features.
For example, storing only the number of transactions would prevent the application from later determining:
When each transaction occurred.
Which users were involved.
How much each transaction was worth.
SUM
SUM adds values in a column.
SELECT SUM(amount)
FROM transactions
WHERE user_id = 9;This can calculate a user’s balance if transaction amounts are positive for received funds and negative for sent funds.
In financial applications, amounts are often stored as integers representing the smallest currency unit:
5.67 is stored as 567 cents.
20.00 is stored as 2000 cents.
This avoids floating-point rounding errors.
For example, calculations using real numbers may produce tiny inaccuracies because many decimal fractions cannot be represented exactly in binary floating-point format. Integer arithmetic avoids that problem.
MAX
MAX returns the largest value:
SELECT MAX(amount)
FROM transactions
WHERE user_id = 4;This can find the largest transaction received by a user.
MIN
MIN returns the smallest value:
SELECT MIN(age)
FROM users
WHERE country_code = 'US';This can find the youngest user in a specific country.
AVG
AVG returns the arithmetic mean.
SELECT AVG(age)
FROM users
WHERE country_code = 'US';The average is calculated from non-null values. Null values are ignored rather than treated as zero.
The GROUP BY Clause
GROUP BY divides rows into groups before applying an aggregation.
For example:
SELECT album_id, COUNT(song_id)
FROM songs
GROUP BY album_id;This produces one row per album, showing the number of songs in each album.
Without GROUP BY, COUNT(song_id) would return one total for the entire table. With GROUP BY album_id, the count is calculated separately for every album.
A balance query can group transactions by user:
SELECT
user_id,
SUM(amount) AS balance
FROM transactions
GROUP BY user_id;The result contains one row for each user and the sum of that user’s transactions.
Aliasing Aggregate Results
Aggregate expressions often receive awkward default column names. The AS keyword gives a result a clearer name:
SELECT
user_id,
SUM(amount) AS balance
FROM transactions
GROUP BY user_id;The calculated column is returned as balance.
The HAVING Clause
HAVING filters grouped or aggregated results.
The difference between WHERE and HAVING is based on when filtering occurs:
WHEREfilters individual rows before grouping.GROUP BYforms groups.Aggregate functions calculate results for each group.
HAVINGfilters the grouped results.
Example:
SELECT
album_id,
COUNT(id) AS song_count
FROM songs
GROUP BY album_id
HAVING COUNT(id) > 5;This returns only albums containing more than five songs.
Choosing Between WHERE and HAVING
Use WHERE when filtering ordinary row values:
WHERE class_id = 3Use HAVING when filtering aggregate results:
HAVING COUNT(student_id) > 20A complex transaction query might be:
SELECT
sender_id,
SUM(amount) AS balance
FROM transactions
WHERE note LIKE '%lunch%'
AND sender_id IS NOT NULL
GROUP BY sender_id
HAVING SUM(amount) > 20
ORDER BY balance ASC;This query:
Selects lunch transactions.
Ignores transactions without a sender.
Groups transactions by sender.
Calculates total spending for each sender.
Keeps only senders whose total exceeds 20.
Sorts the results from smallest balance to largest.
Rounding Values
The ROUND function rounds numeric values.
SELECT ROUND(AVG(age)) AS round_age
FROM users
WHERE country_code = 'US';Without a precision argument, SQLite rounds to the nearest whole number.
A precision can also be specified:
SELECT ROUND(AVG(age), 2)
FROM users;This rounds to two decimal places.
Subqueries
What a Subquery Is
A subquery is a query nested inside another query.
The nested query is surrounded by parentheses. Its result is used by the outer query.
Example:
SELECT *
FROM transactions
WHERE user_id = (
SELECT id
FROM users
WHERE name = 'David'
);The inner query finds David’s user ID. The outer query then retrieves transactions belonging to that ID.
A subquery:
Exists only while the query executes.
Does not automatically create a permanent table.
Allows related information to be retrieved in one SQL statement.
Can be used in
WHERE,IN, and other expressions.
IN with a Subquery
If the nested query returns multiple values, IN is appropriate:
SELECT id, song_name, artist_id
FROM songs
WHERE artist_id IN (
SELECT id
FROM artists
WHERE name LIKE 'Rick%'
);The inner query may return several artist IDs, and the outer query retrieves songs belonging to any of them.
If the inner query should return only one value, a direct equality comparison can be used:
WHERE user_id = (
SELECT id
FROM users
WHERE name = 'David'
LIMIT 1
)SQL Without Tables
SQL can perform calculations without reading a table:
SELECT 5 + 10 AS sum;This returns a result containing 15.
This capability can also be used in subqueries or filters:
SELECT *
FROM users
WHERE age_in_days > (
SELECT 40 * 365
);The subquery converts forty years into days using the assumption that each year has 365 days.
Database Relationships
A database design must accurately represent relationships between entities.
The three main relationship types are:
One-to-one.
One-to-many.
Many-to-many.
One-to-One Relationships
In a one-to-one relationship, one record corresponds to exactly one record in another entity.
Examples:
A student and one GPA record.
A transaction and one note.
A class and one official name.
The simplest design is often to place the related value directly in the same table:
students
- id
- name
- gpaA separate table can also be used when organizational or performance concerns justify it:
student_scores
- student_id
- gpa
- test_scoreA one-to-one relationship requires each student ID to appear at most once in the secondary table.
One-to-Many Relationships
A one-to-many relationship occurs when one record can be associated with zero, one, or many records of another type.
Examples:
One user can have many transactions.
One customer can have many orders.
One user can create many posts.
One department can contain many employees.
The foreign key is placed on the table representing the “many” side.
Example:
users
- id
- name
tweets
- id
- text
- user_idThe tweets.user_id column references users.id.
A user can therefore appear in many tweet rows:
tweets
- id: 1, user_id: 1
- id: 2, user_id: 2
- id: 3, user_id: 1User 1 authored tweets 1 and 3.
Many-to-Many Relationships
A many-to-many relationship occurs when:
One entity can relate to many records of another entity.
Each record of the second entity can also relate to many records of the first.
Examples:
Students and courses.
Users and groups.
Products and suppliers.
A foreign key in only one of the two main tables cannot represent this relationship correctly. Instead, a joining table is introduced.
Example:
users
- id
- name
groups
- id
- name
- max_size
user_groups
- user_id
- group_idThe joining table contains the identifiers of the related entities.
If Lane belongs to two groups, the table might contain:
user_id | group_id
1 | 1
1 | 2If John also belongs to group 1:
user_id | group_id
3 | 1The joining table should generally prevent duplicate pairs. A composite uniqueness constraint can enforce this:
UNIQUE (user_id, group_id)This prevents the same user-group relationship from being recorded twice.
Database Normalization
Purpose of Normalization
Database normalization is the process of structuring data to reduce redundancy and improve integrity.
A more normalized database generally has:
Less duplicated data.
Fewer conflicting copies of the same information.
More reliable updates.
Clearer relationships.
For example, if a country’s name is stored once in a countries table, changing the name requires one update. If the name is copied into every user record, the application must update every copy.
The practical goal of normalization is to ensure that each fact is stored in the most appropriate place and does not need to be updated in multiple locations.
Normal Forms
The main normal forms discussed are:
First Normal Form.
Second Normal Form.
Third Normal Form.
Boyce-Codd Normal Form.
Each higher form includes the rules of the previous forms and adds additional requirements.
First Normal Form
A table is in First Normal Form, or 1NF, when:
Every row has a unique primary key.
The table does not contain nested tables.
A table with two completely identical rows violates 1NF because the rows cannot be uniquely distinguished.
Adding an ID column solves the duplicate-row problem:
id | name | age
1 | Lane | 17
2 | Lane | 17The values of the other columns may be identical, but the records themselves are distinct because their primary keys differ.
Second Normal Form
A table is in Second Normal Form, or 2NF, when:
It is already in 1NF.
Every non-key column depends on the entire primary key, not merely part of a composite primary key.
This rule is most relevant when a primary key contains multiple columns.
Suppose a table uses (first_name, last_name) as its composite primary key:
first_name | last_name | first_initial
Lane | Small | L
Lane | Brewer | L
Allen | Small | Afirst_initial depends only on first_name, not on the entire combination of first_name and last_name. This creates redundancy.
A normalized design could move first-name initials to a separate table:
first_names
- first_name
- first_initialThird Normal Form
A table is in Third Normal Form, or 3NF, when:
It is already in 2NF.
Non-key columns depend only on the primary key.
A common violation occurs when one column can be calculated directly from another non-key column.
For example:
companies
- id
- name
- num_employees
- sizeIf size is always:
largewhen the company has more than 100 employees.smallotherwise.
Then size is redundant because it can be calculated from num_employees.
Instead, the query can calculate it when needed:
SELECT *,
IIF(num_employees > 100, 'large', 'small') AS size
FROM companies;The table stores the raw number of employees, while the report derives the size.
Boyce-Codd Normal Form
Boyce-Codd Normal Form, or BCNF, adds another rule:
A column that is part of a primary key cannot depend on a column that is not part of the primary key.
BCNF matters in unusual cases involving multiple possible candidate keys. For example, a table may have several different combinations of columns that could uniquely identify rows. A key column depending on a non-key column can create hidden redundancy even when the table satisfies 3NF.
The practical distinction between 3NF and BCNF is often less important than the general goal of preventing redundant data.
Data Integrity
Data integrity means that stored data remains accurate, consistent, and valid.
Storing a user’s current age can cause integrity problems:
A user is recorded as age 6.
A year passes.
The database still says the user is age 6.
Storing a birth date is more reliable because the birth date does not change. The application can calculate the current age whenever needed.
Raw, stable facts should generally be stored instead of values that become outdated or can be calculated from other stored values.
Data Redundancy
Data redundancy occurs when the same fact is stored in multiple locations.
For example, storing a user’s address in two tables creates a synchronization problem:
The user changes their address.
One copy is updated.
The other copy is forgotten.
The database now contains conflicting information.
Common column names appearing in different tables are not automatically redundant. For example, separate name columns in users and countries are appropriate because they represent different facts.
The problem is duplicated meaning, not merely repeated column names.
Practical Normalization Rules
Give each table a primary key.
Store each fact in one appropriate location.
Avoid duplicating shared metadata.
Use foreign keys to represent relationships.
Store stable raw data rather than outdated calculated values.
Keep joining tables focused on relationships.
Prefer a simple schema unless complexity is justified.
Optimize for correctness before performance.
Joins
What a Join Does
A join combines rows from multiple tables in a single query.
Joins are essential in relational databases because related data is often stored in separate normalized tables.
A join generally matches rows using related columns, such as:
A primary key in one table.
A foreign key in another table.
Inner Joins
An inner join returns rows that have matching records in both tables.
The keyword JOIN usually means INNER JOIN.
SELECT *
FROM employees
INNER JOIN departments
ON employees.department_id = departments.id;This returns employees whose department_id matches an existing department ID. Employees without a matching department are omitted.
The ON clause defines the relationship used for matching rows.
Table Qualification
When multiple tables contain columns with the same name, the table name should be included:
SELECT users.name, countries.name
FROM users
JOIN countries
ON users.country_code = countries.country_code;users.name and countries.name refer to different columns.
This notation is called table qualification or namespacing.
Column Aliases in Joins
The result can rename one of the duplicate columns:
SELECT
users.name,
users.age,
countries.name AS country_name
FROM users
JOIN countries
ON users.country_code = countries.country_code
ORDER BY country_name ASC;This produces columns such as:
User name.
User age.
Country name.
Left Joins
A left join returns every row from the left table, even if there is no matching row in the right table.
SELECT *
FROM users
LEFT JOIN transactions
ON users.id = transactions.user_id;This includes users who have never made a transaction. Their transaction columns contain NULL.
A left join is useful when the primary requirement is to preserve every record from one table.
For example, to report every user and the number and total value of their transactions:
SELECT
users.name,
SUM(transactions.amount) AS total_amount,
COUNT(transactions.id) AS transaction_count
FROM users
LEFT JOIN transactions
ON users.id = transactions.user_id
GROUP BY users.id
ORDER BY total_amount DESC;Using transactions.id inside COUNT ensures that users with no transactions receive a count of zero rather than counting the user row itself.
Right Joins
A right join returns every row from the right table and matching rows from the left table.
Right joins are often unnecessary because the same result can be produced by reversing the table order and using a left join.
For example:
A RIGHT JOIN Bcan usually be rewritten as:
B LEFT JOIN ASQLite does not support right joins, encouraging developers to use the simpler left-join formulation.
Full Joins
A full join returns all rows from both tables:
Matching rows are combined.
Unmatched rows from either table are still included.
Missing values are represented as
NULL.
A full join is useful when every row from both tables must be preserved, regardless of whether a relationship exists.
Multiple Joins
More than two tables can be joined in one query:
SELECT *
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.id
INNER JOIN regions
ON departments.region_id = regions.id;Multiple joins are powerful, but joining large tables can make queries more expensive. Query performance should be monitored when many joins are executed frequently.
Database Backups
Snapshot Backups
A common backup strategy is to take periodic snapshots of the production database.
For example:
An automated task runs every day.
It copies the production database.
The copy is stored separately.
Old snapshots are eventually removed.
Backups are commonly stored in inexpensive object storage such as a cloud storage bucket.
If a catastrophic failure occurs, the database can be restored from the latest snapshot.
Benefits
Simple to configure.
Inexpensive.
Supported by most managed database providers.
Appropriate for many small and medium-sized applications.
Limitation
A daily snapshot may lose the changes made after the most recent snapshot.
If the database fails five hours after the last snapshot, those five hours of data may be lost.
Hourly snapshots reduce the possible loss but do not eliminate it.
Append-Only Logs
A more robust approach records every database change in an append-only log.
Examples:
A record creation is logged.
A record update is logged.
A record deletion is logged.
The log preserves the history of operations. A database can be reconstructed by replaying the events.
Advantages
Very fine-grained recovery.
Minimal data loss.
Preserves historical changes.
Disadvantages
More difficult to implement.
More expensive.
Requires careful event management.
Requires replay and recovery tooling.
Soft Deletes
A soft delete marks a record as deleted without physically removing it.
A table may contain a deleted_at column:
deleted_at = NULLmeans the record is active.
A timestamp in deleted_at means the record has been deleted.
Application queries then exclude soft-deleted rows:
SELECT *
FROM users
WHERE deleted_at IS NULL;Benefits
Data remains recoverable.
Historical information is preserved.
Accidental deletions are easier to undo.
Costs and Risks
Queries must consistently filter deleted rows.
Application logic becomes more complex.
Deleted records continue consuming storage.
Large numbers of soft-deleted rows can slow queries.
Privacy regulations may require actual deletion.
A production database should almost always have an automated backup strategy, even if soft deletes are also used.
Object-Relational Mapping
What an ORM Is
An Object-Relational Mapper, or ORM, is a library that maps objects or structs in a programming language to tables and rows in a database.
For example, a Go structure might look like:
User
- ID
- Name
- IsAdminAn ORM can map an instance of that structure to a database row and generate SQL automatically.
Instead of manually writing:
INSERT INTO users (id, name, is_admin)
VALUES (10, 'Lane', FALSE);the application may call an ORM method such as a create operation.
Advantages of ORMs
Less repetitive code.
Fewer manually written CRUD queries.
Automatic mapping between application objects and database records.
Convenient handling of common operations.
Potentially improved developer productivity.
Disadvantages of ORMs
Less direct control over the generated SQL.
Complex operations may produce inefficient queries.
Low-level debugging can be more difficult.
ORM abstractions may hide database behavior.
Advanced queries may still require raw SQL.
A useful rule is:
An ORM generally trades simplicity for control.
A practical production approach often uses an ORM for routine operations while retaining the ability to write raw SQL for advanced or performance-sensitive queries.
Query Functions and Computed Columns
SQL Functions
SQL supports functions that accept arguments and return values.
For example, SQLite’s IIF function works like a conditional expression:
IIF(condition, value_if_true, value_if_false)Example:
SELECT
product_name,
quantity,
IIF(quantity < 10, 'order more', 'in stock') AS status
FROM products;The query adds a computed status column.
Another example:
SELECT *,
IIF(was_successful,
'no action required',
'perform an audit') AS audit
FROM transactions;The result includes all original transaction columns plus an audit column.
Computed columns are useful for reports because they allow raw data to remain unchanged while generating user-friendly interpretations at query time.
Performance and Indexes
Query Performance
Database performance is important, but schema correctness should usually be addressed first.
A useful order of priorities is:
Correctly model the data.
Avoid unnecessary duplication.
Preserve data integrity.
Build clear queries.
Measure actual performance.
Add indexes or denormalization where justified.
Premature optimization can make a system more complex without solving a real problem.
Indexes
An index is an in-memory data structure maintained by the database to speed up lookups.
A common implementation is a binary tree.
Without an index, the database may need to scan every row to find matching records. With an index, it can search more efficiently.
For a table with n rows:
A full scan may take O(n) time.
A balanced tree index can provide lookup performance around O(logn).
The exact implementation varies by database system, but the essential idea is that indexes make searches faster.
Creating an Index
CREATE INDEX email_idx
ON users(email);This creates an index for queries such as:
SELECT *
FROM users
WHERE email = 'example@example.com';Primary keys are commonly indexed automatically.
When to Add an Index
Add an index when:
A column is frequently used in
WHEREconditions.Queries involving the column have become slow.
The table contains enough rows for scanning to be expensive.
The performance benefit justifies the maintenance cost.
Do not automatically index every column.
Costs of Indexes
Indexes consume resources:
They require memory or storage.
Inserts must update the index.
Updates to indexed columns must update the index.
Excessive indexes can slow write operations.
Unused indexes waste resources.
Indexes generally improve read speed but can reduce write speed.
Multi-Column Indexes
A multi-column index covers several columns:
CREATE INDEX user_recipient_idx
ON transactions(user_id, recipient_id);This is useful for queries that frequently filter using both columns:
SELECT *
FROM transactions
WHERE user_id = 6
AND recipient_id = 9;Column order matters.
An index on (user_id, recipient_id) is highly useful for:
Queries using both
user_idandrecipient_id.Queries using only
user_id.
It is generally less useful for queries using only recipient_id, because the index is organized first by user_id.
A practical rule is to create a multi-column index when the same combination of columns is frequently used for lookups.
Denormalization
What Denormalization Means
Denormalization intentionally introduces duplicated or precomputed data to improve performance.
For example, a normalized design may calculate the number of transactions by counting rows:
SELECT COUNT(*)
FROM transactions
WHERE user_id = 6;A denormalized design might store the current transaction count separately:
transaction_counts
- user_id
- countThe count can then be retrieved with a simple lookup.
Benefits
Faster reads.
Fewer joins.
Fewer aggregations.
Useful for high-traffic pages and dashboards.
Risks
Duplicate data can become inconsistent.
Every write must update multiple locations.
Application logic becomes more complicated.
Bugs can occur if one copy is updated and another is not.
A normalized database is usually the best starting point. Denormalization should be introduced only after measurements show that normalization is causing a real performance problem.
Normalize for correctness first; denormalize only when performance requirements justify the additional complexity.
SQL Injection
What SQL Injection Is
SQL injection is a security vulnerability that occurs when untrusted user input is inserted directly into an SQL query.
Suppose an application builds a query by concatenating user input:
INSERT INTO students (name)
VALUES ('user_input');If the input is not safely handled, an attacker may enter a value that terminates the original statement and adds another SQL command.
A malicious input might transform the query into something conceptually like:
INSERT INTO students (name)
VALUES ('Robert');
DROP TABLE students;The first statement inserts a student. The second deletes the entire students table.
SQL injection can allow attackers to:
Read private data.
Modify records.
Delete tables.
Bypass authentication.
Execute unintended database operations.
Preventing SQL Injection
Applications should use:
Parameterized queries.
Prepared statements.
Trusted database libraries.
ORM APIs that safely bind values.
A parameterized query keeps user data separate from SQL syntax. The database treats the value as data rather than executable SQL.
Application code should not use ordinary string concatenation or generic interpolation to construct SQL queries.
Unsafe approaches include:
JavaScript template literals.
Python f-strings.
Go string formatting.
Manual string concatenation.
These language features do not automatically protect against SQL injection.
A good database client or standard library normally provides safe parameter binding. The application should use that mechanism rather than implementing sanitization from scratch.
User-provided values must be passed as parameters, not manually inserted into SQL strings.
Core Practical Rules
Use SQL to communicate with relational databases.
Use
SELECTto read data.Use
INSERTto create rows.Use
UPDATEto modify rows.Use
DELETEcarefully to remove rows.Always use precise
WHEREclauses for updates and deletes.Prefer primary keys when targeting individual records.
Use
COUNT,SUM,MIN,MAX, andAVGfor aggregations.Use
WHEREbefore grouping andHAVINGafter grouping.Use
GROUP BYto produce one aggregate result per category.Use
JOINto retrieve related data from multiple tables.Use a left join when every row from the first table must remain in the result.
Use foreign keys to enforce relationships.
Use joining tables for many-to-many relationships.
Normalize data to reduce duplication and improve integrity.
Store stable raw facts rather than outdated calculated values.
Back up production databases.
Use soft deletes only when their storage, complexity, and privacy implications are acceptable.
Add indexes to frequently queried columns when performance requires them.
Remember that indexes improve reads but can slow writes.
Begin with a normalized schema and denormalize only when necessary.
Use parameterized queries to prevent SQL injection.

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