Sub topic 2
Adding a row with INSERT
This chapter assumes you can write a basic SELECT ... WHERE query. It also assumes you know what tables, rows, columns, primary keys, and foreign keys are. It uses the customers and orders tables from the schema chapter, repeated here so you can run every example.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE,
status VARCHAR(20) NOT NULL DEFAULT 'active'
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (id),
total NUMERIC(10, 2) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new'
);The anatomy of an INSERT
INSERT adds one new row to a table. The most common form has three parts: the target table, a list of columns, and a list of values.
INSERT INTO customers (id, name, email)
VALUES (1, 'Ada Lovelace', '[email protected]');INSERT INTO customersnames the table that receives the row.(id, name, email)is the column list. It says which columns you are supplying.VALUES (1, 'Ada Lovelace', '[email protected]')supplies one value for each listed column.
The database pairs the first column with the first value, the second with the second, and so on. The pairing is by position, not by name. The column list controls which column gets which value.
The statement did not mention status. Because you left it out, the database stores its default, 'active'. You can confirm this:
SELECT id, name, email, status
FROM customers
WHERE id = 1;The result is one row with status set to active. The next chapter covers defaults and NULL in more detail.
Why you should always list the columns
SQL also allows you to skip the column list:
INSERT INTO customers
VALUES (4, 'Katherine Johnson', '[email protected]', 'active');Without a list, the values must cover every column, in the order the table defines them. This works today, but it is fragile in two ways:
- If someone later adds a column to
customers, the statement fails because it supplies too few values. - If someone rebuilds the table with the columns in a different order, the statement may fail or, worse, store values in the wrong columns.
An explicit column list ties the statement to column names. A new column with a default or a nullable column does not break it. Treat the short form as acceptable only for throwaway experiments.
Matching columns, values, and types
The database checks the statement before it writes anything. These mistakes cause an error:
| Mistake | Example | Result |
|---|---|---|
| Different number of columns and values | `(id, name)` with `VALUES (5)` | Error: count mismatch |
| Unknown column name | `(id, fullname)` | Error: column does not exist |
| Value of the wrong type | `'abc'` for an integer column | Error, or in some dialects a silent conversion |
| Omitting a `NOT NULL` column that has no default | Leaving out `name` | Error: null value not allowed |
The last row is worth remembering. A column is only optional in an INSERT if it has a default or allows NULL. In customers, only email and status can be left out.
Dialects differ in how strict they are about types. PostgreSQL rejects text that cannot be converted to a number. SQLite is lenient, because it lets many columns hold values of a type different from the declared one. Do not rely on automatic conversion. Write values in the form the column expects.
Writing literal values
A literal is a value written directly in the statement.
- Text goes in single quotes:
'Ada Lovelace'. Double quotes mean an identifier such as a column name in standard SQL, not text. - A single quote inside text is written twice:
'Miles O''Brien'. - Numbers are written without quotes:
25.00. - Dates and timestamps are usually text in
YYYY-MM-DDorYYYY-MM-DD HH:MM:SSform, such as'2026-11-27'. Some dialects accept aDATE '2026-11-27'prefix for clarity. NULLis a keyword with no quotes. The string'NULL'is ordinary text.
Inserting a child row: order matters
The orders table has a foreign key to customers. A row in orders must point to a customer that exists, so you insert the parent first:
INSERT INTO customers (id, name, email)
VALUES (2, 'Grace Hopper', '[email protected]');
INSERT INTO orders (id, customer_id, total)
VALUES (100, 2, 49.90);If you reverse the two statements, the order insert fails because customer 2 does not exist yet. Here the omitted status column on orders takes its default, 'new'.
The check is all or nothing. A single statement either adds its row or changes nothing. A failed INSERT never leaves a half-written row.
Seeing what happened
Most clients report the number of rows affected, such as INSERT 0 1 in PostgreSQL's psql or 1 row affected in SQL Server. A count of 1 means the row went in. The count is a quick check, but a SELECT shows you the actual stored values:
SELECT id, customer_id, total, status
FROM orders
WHERE id = 100;Check that the defaults were what you expected, not just that the row exists.
Where the id comes from
The examples above supply id by hand. That is fine for a tutorial, but real applications usually let the database generate it. Each dialect has its own mechanism:
- PostgreSQL:
GENERATED ALWAYS AS IDENTITY(or the olderSERIAL). - MySQL:
AUTO_INCREMENT. - SQL Server:
IDENTITY(1,1). - SQLite: an
INTEGER PRIMARY KEYcolumn fills itself in if you omit it.
With a generated key you leave id out of the column list. If you supply your own value for a generated column, the database may reject it or let it collide with a later generated value, depending on the dialect and column definition.
Inserting from application code
When values come from a user or another program, do not build the SQL by joining strings. A name containing a quote breaks the statement, and a malicious value can change its meaning. This attack is called SQL injection. Send the statement with placeholders and pass the values separately. The database driver then treats the values as data only.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("""
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE,
status VARCHAR(20) NOT NULL DEFAULT 'active'
)
""")
conn.execute(
"INSERT INTO customers (id, name, email) VALUES (?, ?, ?)",
(5, "Miles O'Brien", "[email protected]"),
)
conn.commit()
print(conn.execute("SELECT id, name, status FROM customers").fetchall())This prints [(5, "Miles O'Brien", 'active')]. The apostrophe needs no escaping because the driver sends the value separately from the SQL text. The placeholder symbol varies by driver (?, %s, :name), but the idea is the same everywhere.
The conn.commit() call matters. Python's sqlite3 module opens a transaction on your first data change and keeps it open until you commit. Other drivers behave similarly. The transactions chapter explains why.
Common errors
- Duplicate key. Inserting
id1 twice fails on the primary key. Inserting an email that already exists fails on theUNIQUEconstraint. - Missing parent. Inserting an order for customer 999 fails if no such customer exists.
- Missing required value. Leaving out
namefails onNOT NULL. - Count mismatch. Four columns and three values fail before anything is checked against the data.
The error message usually names the constraint or column involved. Read it before changing anything, because it points to the exact cause.
Exercise
You run INSERT INTO orders (id, customer_id, total) VALUES (102, 2, 15.00); and then SELECT status FROM orders WHERE id = 102;. What value do you see for status, and why? Then explain what happens if you run INSERT INTO orders (id, total) VALUES (103, 15.00);.
Show answer
The first query returns new. The statement did not list status, so the database used the column's default, 'new'. The second statement fails. It omits customer_id, which is NOT NULL and has no default, so the database has no valid value to store. Nothing is inserted.
Exercise
A colleague writes INSERT INTO customers VALUES (6, 'Edsger Dijkstra', '[email protected]'); and it works. Name one change to the customers table that would break it, and rewrite the statement so it survives that change.
Show answer
Adding a new column, for example phone, would break it. The statement now supplies fewer values than the table has columns, so it fails. The safer form is INSERT INTO customers (id, name, email) VALUES (6, 'Edsger Dijkstra', '[email protected]');, which names the columns it fills and lets the new column take its default or NULL.