Sub topic 2
Adding a row with `INSERT`
This chapter assumes that you can write basic SELECT ... WHERE queries and understand tables, rows, columns, primary keys, and foreign keys. An INSERT statement adds one or more new rows to a table.
The basic form
Use an explicit column list after the table name. The values then appear in the same order as the columns.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE,
status VARCHAR(20) NOT NULL DEFAULT 'active'
);
INSERT INTO customers (id, name, email, status)
VALUES (1, 'Ada Lovelace', '[email protected]', 'active');The PRIMARY KEY constraint requires id to identify this row uniquely. The NOT NULL constraint requires name and status to have values. The UNIQUE constraint prevents two customers from using the same email address.
The explicit column list makes the statement safer. If someone later adds a column to the table, this INSERT still states exactly which columns it supplies.
Defaults and `NULL`
A default is a value the database supplies when an INSERT omits a column. In the table above, omitting status stores 'active'.
INSERT INTO customers (id, name, email)
VALUES (2, 'Grace Hopper', '[email protected]');
SELECT id, name, email, status
FROM customers
WHERE id = 2;The result includes status = 'active'.
NULL means that a value is missing or unknown. It is different from an empty string ('') and from zero. A column accepts NULL unless it has a NOT NULL constraint.
INSERT INTO customers (id, name, email)
VALUES (3, 'Alan Turing', NULL);This succeeds because email does not have NOT NULL. A condition such as email = NULL does not find this row. Use email IS NULL when testing for a missing value.
Errors that protect the table
The database checks constraints during insertion. For example, this statement fails if customer 1 already exists:
INSERT INTO customers (id, name, email)
VALUES (1, 'Another Person', '[email protected]');It violates the primary key constraint. An existing email would similarly violate the UNIQUE constraint, and omitting name would violate NOT NULL.
Read the error message carefully. It usually identifies the table or constraint that rejected the row. Fix the data or the statement rather than disabling the constraint.
Exercise
Write an INSERT statement for customer 4, named “Katherine Johnson”, with no email address. Let the database provide the default status.
Show answer
INSERT INTO customers (id, name, email) VALUES (4, 'Katherine Johnson', NULL);