Introduction to SQL
Flat File Databases
You may be familiar with a flat-file database; it is usually represented by patterns of columns and rows. A spreadsheet such as those created in Microsoft excel or Google sheets can be considered a flat-file database.
Relational Databases
Big companies such as Google, Meta, Amazon all use relational databases to store their information at scale. Relational databases store data in columns and rows in structures called tables.
Relational databases reference each other through the use of primary keys and foreign keys.
A primary key is always a unique value; such as a unique ID for each person, using a primary key ensures no two people have the same ID.
A foreign key is a reference to another table; if you have a table of user_logins and users, the user_id in the user_logins table would be a foreign key, referencing the primary key (unique ID) in the users table. This connects the login attempts to the specific user who attempted it.
Primary keys are most commonly stored as an integer, this is for performance, numeric comparisons are faster than string comparisons, faster to index, smaller in size and easy to auto-increment, all of this becomes especially important when working with data at scale.
Structured query language (SQL) is a standard language for accessing and manipulating databases, this can be done with 4 types of operations;
- Create
- Read
- Update
- Delete
(CRUD)
For the rest of this post, I will be demonstrating commands via sqlite3, a lightweight version of SQL that can be run from the command line.
Creating your database
Filename.db (Creating a database) - creates a .db database file on the filesystem.
database.dbAfter confirming with the user, will create a database named database.db.
.mode - changes the output mode for the command line, also determines how data being imported by .import is interpreted.
.mode csvChanges the output of sqlite3 to match that of a .csv file If using .import, sqlite3 will expect imported data to be CSV format and will parse accordingly.
.mode ?Displays the current output mode.
.import - imports a file or database.
.import file.csvWhile set to .mode csv, will correctly import a csv file into the database.db. If .mode is set to sqlite3, sqlite3 shell compatible files are expected, complex operations such as importing entire databases can be accomplished.
.schema - Displays the structure of the database.
.schemaAlong with SELECT * FROM column; can be used to gain a high level overview of the data contained within the database to quickly understand what is contained therein.
Accessing Data
SELECT FROM - Used to retrieve information from a database, FROM indicates which table to query and is required to perform this action.
SELECT id_number
FROM employeesdisplays the id_number column from the employees table.
sqlite3 commands themselves are not case sensitive; but it is convention and strongly recommended to capitalize these commands for readability (in other words, mandatory).
WHERE - Filters rows based on a specific condition
SELECT *
FROM login_attempts
WHERE country != USADisplays all login attempts originating from outside the USA.
Wildcards - *, % and _. Used to match 1 or many number of characters.
SELECT *
FROM employees* (wildcard) matches any number of characters, causing sqlite to display ALL rows from the employees table. % (percentage) is similar to * and will also replace 1 or more characters. __ (underscore) will only substitute 1 character.
Different SQL languages use different wildcards, check the documentation!
SELECT *
FROM users
WHERE name = 'Cale F%';Select any user where their first name is Cale and Surname starts with F
AND - Allows filtering of more rows
SELECT *
FROM employees
WHERE office = 'East-Office'
AND department = 'finance';Filters employees to return only those from the finance department working at the East Office. You can string together as many AND statements as you like.
OR - retrieve data that matches either filter.
SELECT *
FROM employees
WHERE office = 'East-Office'
AND department = 'finance'
OR department = 'sales';Selects employees from both the finance and sales departments working at the East Office.
NOT - excludes data, the logical != can be used also.
SELECT *
FROM employees
WHERE department != 'human resources'
--WHERE NOT department = 'human resources'Returns all employees not belonging to human resources; both WHERE statements are equivalent, either can be used.
Filtering Data
AVG - Calculates the average value of a numeric column.
SELECT AVG(age)
FROM employeesCalculates the average age of employees.
COUNT - Counts the number of rows or values in a column.
SELECT COUNT(*)
FROM login_attempts;Displays the total number of login attempts.
DISTINCT - returns unique values from a column
SELECT DISTINCT country
FROM customers;lists unique countries of customers
MAX - Returns the maximum (highest) value of a column
SELECT MAX(price)
FROM products;returns the highest product price
MIN - Returns the minimum (lowest) value of a column
SELECT MIN(price)
FROM products;returns the lowest product price
LIKE - used to match patterns in a string
SELECT *
FROM employees
WHERE full_name LIKE 'John%';Returns all employee full names starting with John.
ORDER BY - Sorts the result set by one or more columns
SELECT *
FROM users
ORDER BY last_loginsorts users by most recent login.
LIMIT - Limits the number of rows returned
SELECT *
FROM employees
LIMIT 10;selects the first 10 employees.
GROUP BY - Groups rows based on one or more columns
SELECT country, COUNT(*)
FROM employees
GROUP BY country;counts employees by country.
–comment - Adds a comment to the code.
SELECT *
-- this query selects all
FROM employees
-- the above determines which table is being queriedNested queries
One query is placed inside another, the inner query runs first producing a result set, this result set is then used by the outer query. This allows for complex filtering, structuring and aggregation of your data and is an essential skill in performing sophisticated data analysis.
SELECT user_name
FROM users
WHERE user_id IN (
SELECT user_id
FROM login_logs
GROUP BY user_id
HAVING COUNT(*) > 500
);Inner query identifies user IDs with more than 500 login attempts. Outer query selects the names of those users.
Joining tables
JOIN - Combines tables temporarily (tables with a many to many relationship.)
SELECT column1, column2, ...
--Specifies the columns you want to retrieve from the joined tables.
FROM table1
--Specifies the first table to join
JOIN table2 ON table1.column = table2.column
--Specifies the second table to join and the condition for joining.
--ON defines the relationship between the two tables based on a common column.
WHERE condition
--optionally filters the resultsSELECT user_name, login_time
FROM users
JOIN login_attempts ON users.user_id = login_attempts.user_id
WHERE login_successful = TRUE
ORDER BY login_time DESC
LIMIT 5;This example joins users and login_attempts tables based on their user_id.
The results are filtered to only show successful logins, order results by latest login time and limit to the 5 most recent successful login attempts.
This will provide a snapshot of the last few successful logins for the user.
There are different types of JOIN.
INNER JOIN - returns only rows that have matching values in both tables.
LEFT JOIN - returns all rows from the left table as well as matched rows from the right table.
RIGHT JOIN - returns all rows from the right table, and matched rows from the left table.
FULL OUTER JOIN - returns all rows when there is a match in either the left or right tables.
SELF JOIN - Joins a table to itself, allowing you to compare rows within the same table.
Nested JOIN query
Using the 2 techniques described above, we can find top 3 customers with the highest order value
SELECT customer_name, total_spent
FROM (
SELECT customer_name, SUM(order_total) AS total_spent
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
GROUP BY customer_name
) AS customer_totals
ORDER BY total_spent DESC
LIMIT 3;Inner query calculates the total spent by each customer Outer query ranks customers based on their total spending and displays the top 3.
Data types
When creating a table, using the right data type ensures data integrity by enforcing a specific format. Using the correct type also ensures storage efficiency and enables accurate analysis.
BLOB - Binary data, such as images or documents
CREATE TABLE images (
id INT,
image BLOB
);stores images in the image column
INTEGER - integer number
CREATE TABLE products (
id INTEGER,
price INTEGER
);Stores product IDs and prices as integers
NUMERIC(precision, scale) – Best used for precise representation of numeric values, such as for currency or measurements. Precision specifies the total number of digits stored, both before and after the decimal point. Scale indicates the number of digits that can be stored after the decimal point.
CREATE TABLE orders (
id INTEGER,
total_price NUMERIC(10,2)
);Stores order totals with 2 decimal places
REAL - floating point number
CREATE TABLE products (
id INTEGER,
weight REAL
);TEXT - character strings
CREATE TABLE users (
id INTEGER,
name TEXT
);stores user names as text strings.
Special constraints for columns
NOT NULL - Ensures a columns cannot contain null values
CREATE TABLE users (
id INTEGER NOT NULL,
email TEXT NOT NULL
);Ensures the id and email fields cannot be empty
UNIQUE - ensures that all values in the column are unique
CREATE TABLE products (
sku INTEGER PRIMARY KEY,
name TEXT UNIQUE
);Ensures product names are unique.
Some useful resources to help learn SQL:
An interactive book, practice queries against real data, only takes a few hours and is completely free. This resource explores data relating to executions in Texas from 1976 and it is very interesting to analyze in its own right.
Harvard’s CS50 lecture on SQL (week 7, 2024)
A lecture on SQL that is part of Harvard’s introduction to computer programming. A great course to take if you want to gain a bottom-up understanding of programming transferable to any language.