Default Value Constraint

The DEFAULT value constraint specifies a value to write into the constrained column if one is not defined in an INSERT statement. The value may be either a hard-coded literal or an expression that is evaluated at the time the row is created.

Details

  • The data type of the Default Value must be the same as the data type of the column.
  • The DEFAULT value constraint only applies if the column does not have a value specified in the INSERT statement. You can still insert a NULL into an optional (nullable) column by explicitly inserting NULL. For example, INSERT INTO foo VALUES (1, NULL);.

Syntax

You can only apply the DEFAULT value constraint to individual columns.

Note:

You can also add the DEFAULT value constraint to an existing table through ALTER COLUMN.

CREATETABLEtable_name(column_namecolumn_typeDEFAULTdefault_valuecolumn_constraints,column_deftable_constraints))
ParameterDescription
table_nameThe name of the table you're creating.
column_nameThe name of the constrained column.
column_typeThe constrained column's data type.
default_valueThe value you want to insert by default, which must evaluate to the same data type as the column_type.
column_constraintsAny other column-level constraints you want to apply to this column.
column_defDefinitions for any other columns in the table.
table_constraintsAny table-level constraints you want to apply.

Example

  1. > CREATE TABLE inventories (
  2. product_id INT,
  3. warehouse_id INT,
  4. quantity_on_hand INT DEFAULT 100,
  5. PRIMARY KEY (product_id, warehouse_id)
  6. );
  1. > INSERT INTO inventories (product_id, warehouse_id) VALUES (1,20);
  1. > INSERT INTO inventories (product_id, warehouse_id, quantity_on_hand) VALUES (2,30, NULL);
  1. > SELECT * FROM inventories;
  1. +------------+--------------+------------------+
  2. | product_id | warehouse_id | quantity_on_hand |
  3. +------------+--------------+------------------+
  4. | 1 | 20 | 100 |
  5. | 2 | 30 | NULL |
  6. +------------+--------------+------------------+

If the DEFAULT value constraint is not specified and an explicit value is not given, a value of NULL is assigned to the column.

See also

Was this page helpful?
YesNo