How To Use Default In Sql in SQL
How to Use DEFAULT in SQL
The DEFAULT constraint is used to specify a default value for a column. This value is automatically assigned when no value is provided during an INSERT.
Syntax:
CREATE TABLE table_name ( column_name datatype DEFAULT default_value, ...);Or add a default to an existing column:
ALTER TABLE table_nameALTER COLUMN column_name SET DEFAULT default_value;Example 1: Create Table with DEFAULT
CREATE TABLE employees ( employee_id INT PRIMARY KEY, name VARCHAR(100), status VARCHAR(20) DEFAULT 'active', -- Default status is 'active' created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -- Default to current time);Example 2: Insert Without Specifying Default Column
INSERT INTO employees (employee_id, name) VALUES (101, 'John Doe');-- 'status' will be 'active' automaticallyNotes:
The
DEFAULTvalue can be a constant, expression, or function (likeCURRENT_TIMESTAMP).If you explicitly insert
NULL, the default is not applied unless the column is defined asDEFAULTwithNOT NULL.Syntax to add/change default may vary between databases (e.g., in MySQL use
ALTER TABLE ... ALTER COLUMN ... SET DEFAULTorMODIFY COLUMN).
If you want, I can show you how to add or modify a default value in your database!