SQL DEFAULT Constraint Example
The constraint DEFAULT defines a default value of a column.
- The INSERT statement will insert a record with the default value when a value is explicitly not provided.
In the below example, the column country is defined using the DEFAULT keyword.
CREATE TABLE customers (
customer_id INT NOT NULL PRIMARY KEY,
customer_name VARCHAR(30) NOT NULL,
address VARCHAR(20),
city VARCHAR(20),
country VARCHAR(20) NOT NULL DEFAULT 'USA',
postal_code VARCHAR(10)
);
In case the table already exists, it returns an error message, which can be avoided by including the keyword IF NOT EXISTS
as shown below.
CREATE TABLE IF NOT EXISTS customers (
customer_id INT NOT NULL PRIMARY KEY,
customer_name VARCHAR(30) NOT NULL,
address VARCHAR(20),
city VARCHAR(20),
country VARCHAR(20) NOT NULL DEFAULT 'USA',
postal_code VARCHAR(10)
);
Overall
We now know when and how to use the DEFAULT constraint.