SQL Basics for Security, Explained
If you are reading this, you have probably seen SQL in a job description, in an analyst's screenshots, or in a vulnerability report about SQL injection, and you want to read and write it well enough to use it.
By the end you will be able to explain what a database table, row, column and key are; write queries that filter, sort, count and group data; join two tables; handle missing values (NULL) correctly; change data without wiping out a whole table; and use a few queries to spot a brute-force attack and a password-spraying attack in a login log. You will also see, in one short experiment, exactly why SQL injection happens and what the fix looks like.
You do not need to know any programming. You will need a terminal. If you are not comfortable there, read Linux Fundamentals first.
1. Why a security person needs SQL
Databases hold the things attackers want and the things defenders need: user accounts, orders, messages, audit logs. Two jobs follow:
- Defender and analyst work: asking questions of stored data. "Which addresses failed to log in more than five times today?" is a SQL question.
- Understanding attacks: SQL injection (see SQL Injection) is the most famous database attack, and you cannot understand it without reading SQL.
SQL is also part of beginner security training. Google's Cybersecurity Certificate lists a whole course called "Tools of the Trade: Linux and SQL", and describes the skills as using "Python, Linux, and SQL for security tasks" (Google Career Certificates).
2. The ideas: databases, tables, rows and keys
A relational database stores data in tables. SQL (Structured Query Language) is the language you use to ask a database questions and to change its data.
A table looks like a spreadsheet:
- A column is one kind of information (for example
username). - A row is one record (one login attempt).
- A primary key is a column (or columns) whose value identifies one row. Usernames in a users table are a natural example, because no two users share one.
Tables are linked by shared values. A login table can hold username, and a users table can hold the same username plus the person's role. Joining the two lets you ask "which failed logins were against administrators?".
Dialects
Databases such as SQLite, MySQL, PostgreSQL and SQL Server all use SQL, but each has its own small differences. This post uses SQLite, which is a self-contained engine that keeps a whole database in one file, so you can practise without installing a server. The core commands you learn here (SELECT, WHERE, GROUP BY, JOIN, INSERT, UPDATE, DELETE) carry over, but function names and data types can differ, so check the documentation of the database you use.
3. Set up a practice database
Everything below is a made-up login log. It uses the IP addresses 192.0.2.x, 198.51.100.x and 203.0.113.x, which RFC 5737 reserves for examples in documents, so none of them belongs to a real machine. Using these blocks in your own practice data is a good habit.
First check that SQLite is available:
sqlite3 --version
If it prints a version number you are ready. (macOS includes sqlite3. Otherwise download it from the SQLite site.) Then save the following as setup.sql:
CREATE TABLE users (
username TEXT PRIMARY KEY,
role TEXT NOT NULL
);
CREATE TABLE login_attempts (
id INTEGER PRIMARY KEY,
ts TEXT NOT NULL,
username TEXT,
source_ip TEXT NOT NULL,
success INTEGER NOT NULL
);
INSERT INTO users (username, role) VALUES
('alice', 'staff'),
('bob', 'staff'),
('carol', 'admin'),
('admin', 'admin');
INSERT INTO login_attempts (ts, username, source_ip, success) VALUES
('2026-11-05 09:00:11', 'alice', '192.0.2.10', 1),
('2026-11-05 09:02:40', 'bob', '192.0.2.11', 0),
('2026-11-05 09:02:52', 'bob', '192.0.2.11', 1),
('2026-11-05 09:15:03', 'carol', '192.0.2.12', 1),
('2026-11-05 10:01:00', 'admin', '203.0.113.5', 0),
('2026-11-05 10:01:02', 'admin', '203.0.113.5', 0),
('2026-11-05 10:01:04', 'admin', '203.0.113.5', 0),
('2026-11-05 10:01:06', 'admin', '203.0.113.5', 0),
('2026-11-05 10:01:08', 'admin', '203.0.113.5', 0),
('2026-11-05 10:01:10', 'admin', '203.0.113.5', 0),
('2026-11-05 11:30:00', 'alice', '198.51.100.7', 0),
('2026-11-05 11:30:30', 'bob', '198.51.100.7', 0),
('2026-11-05 11:31:00', 'carol', '198.51.100.7', 0),
('2026-11-05 11:31:30', 'admin', '198.51.100.7', 0),
('2026-11-05 11:32:00', 'dave', '198.51.100.7', 0),
('2026-11-05 12:10:00', NULL, '192.0.2.99', 0);
Create the database and open it with headers on and column layout. (If you run the first command twice you will get "table already exists" errors; delete lab.db and start again.)
sqlite3 lab.db < setup.sql
sqlite3 -header -column lab.db
You are now at a sqlite> prompt. Type each query below, ending with a semicolon, and .quit to leave. (You can also run one query without the prompt: sqlite3 -header -column lab.db "SELECT COUNT(*) FROM login_attempts;".)
The table has 16 rows. The story hidden in it: alice, bob and carol log in normally in the morning; at 10:01 one address hammers the admin account; at 11:30 another address tries five different usernames once each; and one failed attempt has no username at all.
4. Asking questions: SELECT, WHERE, ORDER BY, LIMIT
SELECT chooses columns, FROM names the table.
SELECT * FROM login_attempts LIMIT 3;
id ts username source_ip success
-- ------------------- -------- ---------- -------
1 2026-11-05 09:00:11 alice 192.0.2.10 1
2 2026-11-05 09:02:40 bob 192.0.2.11 0
3 2026-11-05 09:02:52 bob 192.0.2.11 1
* means "all columns". LIMIT caps the number of rows, which is a good habit on large tables. Notice success is 0 or 1: SQLite has no separate true/false type and stores Booleans as the integers 0 and 1 (SQLite datatypes). Similarly, SQLite has no date type and stores dates as text, numbers or integers (same page). Here the timestamps are text in the YYYY-MM-DD HH:MM:SS form, which sorts correctly as text.
Filtering with WHERE
WHERE keeps only rows for which a condition is true. Combine conditions with AND, OR and NOT.
SELECT ts, username, source_ip
FROM login_attempts
WHERE success = 0 AND source_ip = '203.0.113.5'
LIMIT 3;
ts username source_ip
------------------- -------- -----------
2026-11-05 10:01:00 admin 203.0.113.5
2026-11-05 10:01:02 admin 203.0.113.5
2026-11-05 10:01:04 admin 203.0.113.5
Text goes in single quotes ('203.0.113.5'); numbers do not. Keep that in mind: it is exactly the detail SQL injection abuses.
More ways to match
| Tool | Meaning | Example |
|---|---|---|
IN (...) |
Value is one of a list | username IN ('alice', 'bob') |
BETWEEN a AND b |
Value in a range (inclusive) | ts BETWEEN '2026-11-05 10:00:00' AND '2026-11-05 10:59:59' |
LIKE |
Pattern match. % matches any run of characters and _ matches exactly one |
username LIKE 'ad%' |
DISTINCT |
Remove duplicate rows from the result | SELECT DISTINCT source_ip FROM login_attempts |
ORDER BY |
Sort. Add DESC for highest first |
ORDER BY ts DESC |
SQLite's documentation says that LIKE ignores upper/lower case for ordinary (ASCII) letters by default, so 'AD%' also matches admin (SQLite expressions). Other databases may treat case differently, which is one more reason to check your database's documentation.
5. Counting and grouping: where the security questions start
COUNT(*) counts rows. GROUP BY splits the rows into groups first, so you get one answer per group. Here is "how many failed logins did each address make?":
SELECT source_ip, COUNT(*) AS failures
FROM login_attempts
WHERE success = 0
GROUP BY source_ip
ORDER BY failures DESC;
source_ip failures
------------ --------
203.0.113.5 6
198.51.100.7 5
192.0.2.99 1
192.0.2.11 1
WHERE filters rows before grouping. To filter after counting, use HAVING:
SELECT source_ip, COUNT(*) AS failures
FROM login_attempts
WHERE success = 0
GROUP BY source_ip
HAVING COUNT(*) >= 5
ORDER BY failures DESC;
source_ip failures
------------ --------
203.0.113.5 6
198.51.100.7 5
Two addresses stand out. But are they doing the same thing? Not quite. Add COUNT(DISTINCT username), the number of different usernames each address tried:
SELECT source_ip,
COUNT(DISTINCT username) AS usernames_tried,
COUNT(*) AS failures
FROM login_attempts
WHERE success = 0
GROUP BY source_ip
HAVING COUNT(DISTINCT username) >= 4;
source_ip usernames_tried failures
------------ --------------- --------
198.51.100.7 5 5
Now the two stories separate:
- 203.0.113.5: six failures, all against one account (
admin). Many guesses at one account is the shape of a brute-force attack. - 198.51.100.7: five failures, five different accounts, one each. Few guesses spread across many accounts is the shape of password spraying.
Brute Force vs Password Spraying explains why attackers choose each and why spraying avoids lockout. The queries above are how an analyst would look for both in a log.
A caution about the numbers. The thresholds here (5 failures, 4 usernames) are for a tiny practice log. A real investigation would also consider the time window, many users behind one shared address, and attackers who rotate addresses. A query shows a pattern; a human decides what it means.
6. NULL: the value that is not a value
A NULL means "no value / unknown". One login attempt (id 16) has no username. NULL behaves unexpectedly:
SELECT * FROM login_attempts WHERE username = NULL;
This returns no rows, even though a row with a missing username exists. A comparison with NULL using = is never true. Use IS NULL:
SELECT id, ts, source_ip FROM login_attempts WHERE username IS NULL;
id ts source_ip
-- ------------------- ----------
16 2026-11-05 12:10:00 192.0.2.99
Counting also treats NULL specially. The SQLite documentation says count(X) counts the number of times X is not NULL, while count(*) returns the total number of rows (SQLite aggregate functions):
SELECT COUNT(*) AS all_rows, COUNT(username) AS with_username
FROM login_attempts;
all_rows with_username
-------- -------------
16 15
This matters in security because missing values are often where the interesting rows hide.
7. Joining two tables
The login log only has usernames. The users table knows each person's role. A JOIN matches rows from two tables on a shared column.
Which failed logins targeted administrator accounts?
SELECT l.ts, l.username, u.role, l.source_ip
FROM login_attempts AS l
JOIN users AS u ON u.username = l.username
WHERE l.success = 0 AND u.role = 'admin'
ORDER BY l.ts
LIMIT 4;
ts username role source_ip
------------------- -------- ----- -----------
2026-11-05 10:01:00 admin admin 203.0.113.5
2026-11-05 10:01:02 admin admin 203.0.113.5
2026-11-05 10:01:04 admin admin 203.0.113.5
2026-11-05 10:01:06 admin admin 203.0.113.5
AS l and AS u are short names (aliases) so you do not have to repeat the table names.
A plain JOIN keeps only rows that have a match on both sides. A LEFT JOIN keeps every row from the left table and fills in NULL where there is no match. That gives a neat way to find attempts against usernames that do not exist:
SELECT l.id, l.username, u.role
FROM login_attempts AS l
LEFT JOIN users AS u ON u.username = l.username
WHERE u.username IS NULL;
id username role
-- -------- ----
15 dave
16
Row 15 tried dave, who is not in the users table, and row 16 had no username at all. Attempts on accounts that do not exist can mean someone is guessing names. (Whether to log those attempts, and how, is a design decision for the system owner.)
8. Changing data: INSERT, UPDATE, DELETE, and the missing WHERE
Everything above only reads. Three commands change data:
INSERT INTO users (username, role) VALUES ('erin', 'staff');
UPDATE users SET role = 'admin' WHERE username = 'erin';
DELETE FROM users WHERE username = 'erin';
The danger is the WHERE. The SQLite documentation is blunt about it:
- For
UPDATE: "If the UPDATE statement does not have a WHERE clause, all rows in the table are modified" (SQLite UPDATE). - For
DELETE: "If the WHERE clause is not present, all records in the table are deleted" (SQLite DELETE).
Try it on a copy, never on data you care about:
cp lab.db copy.db
sqlite3 copy.db "UPDATE login_attempts SET success = 1; SELECT COUNT(*) FROM login_attempts WHERE success = 1;"
# 16 (every failed attempt now looks like a success)
That is a log-tampering attack in one line, and an accident waiting to happen for anyone who forgets WHERE. Good habits:
- Write the
WHEREfirst, then run it as aSELECTto see exactly which rows match. - Use a transaction so you can undo. SQLite's documentation explains that commands run inside a transaction, and
ROLLBACKundoes the changes (SQLite transactions):
cp lab.db copy.db
sqlite3 copy.db "BEGIN; DELETE FROM login_attempts; SELECT COUNT(*) FROM login_attempts; ROLLBACK; SELECT COUNT(*) FROM login_attempts;"
# 0 (inside the transaction, everything looks deleted)
# 16 (after ROLLBACK, the rows are back)
- Keep backups. A transaction only helps before you commit.
- Give database accounts only the rights they need. A web application that only reads products should not be able to
DELETE. This is the least privilege rule applied to databases.
9. Where SQL meets attacks: injection, in one experiment
Remember that text goes in quotes. Imagine a program that looks up a username typed by a user, building the query by gluing text together:
import sqlite3
con = sqlite3.connect("lab.db")
name = "alice' OR '1'='1" # what an attacker might type
q = "SELECT username, success FROM login_attempts WHERE username = '" + name + "'"
print(q)
print("rows:", len(con.execute(q).fetchall()))
Output:
SELECT username, success FROM login_attempts WHERE username = 'alice' OR '1'='1'
rows: 16
The attacker's single quote ended the text early, and OR '1'='1' is always true, so all 16 rows came back, not just alice's two. The database received one string and could not tell which part was the developer's code and which part was the user's data. That is SQL injection (the full story, with types and real cases, is in SQL Injection).
The fix is to keep code and data separate with a parameterized query: the SQL has a placeholder, and the value is sent alongside it:
rows = con.execute(
"SELECT username, success FROM login_attempts WHERE username = ?",
(name,),
).fetchall()
print("rows:", len(rows)) # rows: 0
Now the whole string alice' OR '1'='1 is treated as a username to look for, and no user has that name, so zero rows come back. Python's own documentation gives this exact advice: "Always use placeholders instead of string formatting to bind Python values to SQL statements, to avoid SQL injection attacks" (Python sqlite3). Other languages and libraries have the same feature under names such as prepared statements or bind variables.
(This experiment ran on Python 3.12 with SQLite 3.54. Any recent Python 3 will do.)
10. Practise safely
- Re-run every query in this post against your own
lab.db. - Add rows to
setup.sql, such as a second address with six failures againstcarol, and rewrite the brute-force query to also show the first and last timestamp per address (MIN(ts)andMAX(ts)). - Write a query that lists addresses with both failures and at least one success. Hint:
GROUP BY source_ipwithSUM(success)andSUM(1 - success). - Break something on a copy (
cp lab.db copy.db), then repair it from your untouchedlab.db. - Only ever run SQL against databases you own or have written permission to test. Security Testing explains why.
11. Common mistakes
| Mistake | The facts |
|---|---|
"I'll run UPDATE or DELETE and add the WHERE later" |
Without WHERE, every row is changed or deleted. Write it first, test it as a SELECT |
WHERE username = NULL |
Never matches. Use IS NULL or IS NOT NULL |
"COUNT(*) and COUNT(column) are the same" |
COUNT(column) skips NULLs; COUNT(*) counts every row |
"WHERE and HAVING are interchangeable" |
WHERE filters rows before grouping; HAVING filters groups after counting |
"LIKE is case-sensitive everywhere" |
In SQLite it ignores case for ASCII letters by default. Other databases differ |
| "One query proves an attack" | A query shows a pattern. Shared addresses, time windows and context all matter |
| "I'll build the query by joining strings, it's only a small tool" | That is how injection happens. Use parameterized queries |
| "Escaping quotes is enough" | Parameters keep data and code apart by design. See SQL Injection on why escaping is the wrong fix |
| "A web app needs full database rights" | Give it only the rights it needs, so a flaw does less damage |
| "I'll test on production data" | Practise on a copy or a lab, and keep backups |
Closing
SQL is a small language with a big payoff for a security learner. SELECT and WHERE let you ask questions; COUNT and GROUP BY turn a log into patterns; JOIN adds context from another table; and knowing how queries are built is what lets you understand, test for and prevent SQL injection.
Keep these points:
- Tables, rows, columns and keys are the vocabulary. A primary key identifies a row.
SELECT ... FROM ... WHERE ...is the core. Text goes in single quotes.GROUP BYplusCOUNTturns logs into patterns such as brute force (many guesses, one account) and password spraying (one guess each, many accounts).NULLneedsIS NULL.= NULLnever matches.- A missing
WHEREchanges or deletes everything. Test withSELECTfirst, use transactions, keep backups. - Never glue user input into SQL. Use parameterized queries.
- Least privilege applies to databases too.
If you can take the login log, find who is brute-forcing and who is spraying, and explain in one sentence why gluing strings together is dangerous, you have the foundation.
Related: SQL Injection takes the one-line injection above and shows the types, real cases and defences; Brute Force vs Password Spraying covers the attacks you just found in the log; and Security Operations shows how logs like this feed monitoring and incident response.