Sub topic 5
Providing defaults with DEFAULT
A default is a value the database fills in when an INSERT leaves a column out. This chapter assumes you can write basic INSERT and UPDATE statements, know the common data types, and have read the chapter on NOT NULL. It covers the syntax, what counts as a valid default, how defaults interact with NULL, and the errors you are most likely to meet.
What a default does
A column with a DEFAULT clause gets its default value whenever a new row is inserted without a value for that column. The clause goes after the data type, next to any other column constraints.
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INTEGER NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new',
total_amount NUMERIC(10, 2) NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);Here status starts as 'new', total_amount starts at 0, and created_at records the moment of insertion. The caller only has to supply customer_id.
INSERT INTO orders (customer_id) VALUES (1);
SELECT order_id, status, total_amount, created_at FROM orders;The result is one row with status new, total 0.00, and the current timestamp.
A default is applied at insert time only. It is not a rule that the column must always hold that value. Later UPDATE statements can set any value the data type and constraints allow.
What can be a default
The default must be an expression the database can evaluate without looking at other rows or other columns. The common choices are:
| Kind of default | Example | Notes |
|---|---|---|
| Literal | `DEFAULT 'new'`, `DEFAULT 0`, `DEFAULT TRUE` | Must match the column type. |
| Current date or time | `DEFAULT CURRENT_TIMESTAMP`, `DEFAULT CURRENT_DATE` | Evaluated for each inserted row. |
| `NULL` | `DEFAULT NULL` | Same as having no default on a nullable column. |
| Function or expression | `DEFAULT (price * 2)` | Support varies widely by database. |
Strings and dates are quoted like any other literal. Numbers are not quoted. A default that does not fit the column type, such as DEFAULT 'abc' on an INTEGER column, is rejected when you run CREATE TABLE, not later.
Most systems do not allow a default to refer to another column. PostgreSQL rejects it, and MySQL accepts only certain expressions, in parentheses, from version 8.0.13. If a value depends on other columns, use a generated column or a trigger instead. Those are separate features and are outside this chapter.
When the default is used
The default fires in three situations.
- The column is left out of the
INSERTcolumn list. - The column is listed, and the
VALUESclause uses the keywordDEFAULTfor it. - The whole row uses
DEFAULT VALUES, in systems that support it (PostgreSQL, SQL Server, SQLite).
-- 1. Column omitted
INSERT INTO orders (customer_id) VALUES (1);
-- 2. Explicit DEFAULT keyword
INSERT INTO orders (customer_id, status) VALUES (2, DEFAULT);
-- 3. Every column takes its default
-- (fails here because customer_id is NOT NULL and has no default)
INSERT INTO orders DEFAULT VALUES;The third statement shows an important limit. DEFAULT VALUES works only if every column can be filled by a default, an identity, or NULL. Since customer_id is NOT NULL with no default, the statement is rejected.
The explicit DEFAULT keyword is also valid in an UPDATE, where it resets a column to its declared default.
UPDATE orders
SET status = DEFAULT
WHERE order_id = 1;Defaults and NULL
An omitted column and a column explicitly set to NULL are different things. This is the most common source of confusion.
INSERT INTO orders (customer_id, status) VALUES (3, NULL);This statement does not use the default. It tries to store NULL in status. Because status is NOT NULL, the database raises an error. If the column were nullable, the row would silently get NULL rather than 'new'.
The table below summarizes what happens for a column status VARCHAR(20) under each combination.
| Column definition | `status` omitted | `status` set to `NULL` |
|---|---|---|
| No default, nullable | Stores `NULL` | Stores `NULL` |
| No default, `NOT NULL` | Error | Error |
| `DEFAULT 'new'`, nullable | Stores `'new'` | Stores `NULL` |
| `DEFAULT 'new'`, `NOT NULL` | Stores `'new'` | Error |
The last row is the most useful pairing. NOT NULL DEFAULT value guarantees the column always has a meaningful value, whether the caller omits it or not, and rejects an explicit NULL.
A nullable column with no DEFAULT clause has an implicit default of NULL. This is why leaving a nullable column out of an INSERT works.
Defaults that change over time
A literal default is fixed when you create the table. A function default, such as CURRENT_TIMESTAMP, is evaluated again for every row at insert time.
CREATE TABLE audit_log (
log_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
message VARCHAR(200) NOT NULL,
logged_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
logged_on DATE NOT NULL DEFAULT CURRENT_DATE
);Two rows inserted a second apart get different logged_at values. Inside one transaction, PostgreSQL returns the same CURRENT_TIMESTAMP for every statement, because it reports the transaction start time. If you need the actual wall-clock time in PostgreSQL, use clock_timestamp(). Other systems may behave differently, so check the documentation for yours.
Time zones also matter. CURRENT_TIMESTAMP depends on the session or server time zone. For data shared across regions, many teams use TIMESTAMP WITH TIME ZONE in PostgreSQL, or store UTC consistently.
How defaults flow through an insert
Changing defaults with ALTER TABLE
You can add, change, or remove a default on an existing table. The syntax differs slightly by system. PostgreSQL and MySQL use the following form.
ALTER TABLE orders
ALTER COLUMN status SET DEFAULT 'pending';
ALTER TABLE orders
ALTER COLUMN status DROP DEFAULT;Changing a default affects only future inserts. Existing rows keep the values they already hold. If you want existing rows to change, run an UPDATE.
SQL Server stores a default as a named constraint, so you drop it by name. Naming it at creation makes this easier.
-- SQL Server
ALTER TABLE orders
ADD CONSTRAINT df_orders_status DEFAULT 'new' FOR status;Common errors
- Type mismatch.
DEFAULT 'none'on a numeric column fails atCREATE TABLEwith a type or conversion error. - Unexpected NULL. The caller sends
NULLexplicitly and the default is skipped. The result is aNOT NULLerror, or a storedNULL. - Default that breaks a CHECK.
DEFAULT 'draft'on a column withCHECK (status IN ('new', 'paid'))is valid to create in some systems and then fails every insert that relies on it. Keep defaults inside the allowed set. - Assuming defaults apply to old rows. Changing a default does not rewrite existing data. Adding a new column with a default does fill existing rows in most systems, which is a separate behavior from changing the default of an existing column.
- Expensive table rewrites. Older versions of some databases rewrote the whole table when you added a column with a default. PostgreSQL 11 and later avoid this for constant defaults. Check your version before running such a change on a large table.
Exercise
A table has the column status VARCHAR(20) NOT NULL DEFAULT 'new'. What happens for each statement? (a) INSERT INTO orders (customer_id) VALUES (1); (b) INSERT INTO orders (customer_id, status) VALUES (1, NULL); (c) INSERT INTO orders (customer_id, status) VALUES (1, DEFAULT);
Show answer
(a) The row is inserted and status is 'new', because the column is omitted and the default applies. (b) The statement fails with a NOT NULL violation. An explicit NULL is a supplied value, so the default is not used. (c) The row is inserted and status is 'new', because the DEFAULT keyword asks for the declared default.
Exercise
You change a column's default with ALTER COLUMN status SET DEFAULT 'pending'. The table already holds 10,000 rows with status 'new'. What are the statuses afterward, and how would you change the existing rows?
Show answer
The 10,000 existing rows keep 'new', because a changed default affects only future inserts. To change existing rows, run an UPDATE, for example UPDATE orders SET status = 'pending' WHERE status = 'new';, or UPDATE orders SET status = DEFAULT; to reset every row to the current default.