bhylu.com

Advertisements

SQL Default

A default supplies a value when an INSERT leaves a column out. It can make ordinary inserts simpler, but the default should represent a real business choice rather than hide missing information.

Understand the idea

Our products.stock column defaults to zero. A newly listed product therefore starts unavailable unless a stock count is supplied. A default is applied on insertion; it is not a rule that continually resets a column. Explicit NULL does not mean use the default when the column is NOT NULL.

Where to try it

Run this example in the SQL playground. The lesson link loads the shop tables and sample rows before this query. Select Run when you are ready. Every run starts fresh, so your changes do not affect the website or a previous run.

SQLite sample data · MySQL / MariaDB sample data · See the sample tables

A worked example

SQLite

INSERT INTO products (product_id, name, category, price_cents)
VALUES (5, 'Binder clips', 'Stationery', 300);
SELECT name, stock FROM products WHERE product_id = 5;

Read the result

Binder clips has stock 0 even though stock was omitted from the INSERT. The other values came from the supplied column list.

Try one change

Insert another product with stock explicitly set to 6. Compare that stored value with the defaulted row.