The DEFAULT constraint in MySQL automatically provides a value for a column when no value is specified during an INSERT operation.
'Active').⭐ Common use: status, created date, flags
INSERT statement.Basic syntax for using the DEFAULT constraint when creating a table:
-- DEFAULT constraint syntax in MySQL
CREATE TABLE table_name (
Status VARCHAR(100) DEFAULT 'Active'
);
Here, if you insert a row without specifying Status, MySQL automatically sets it to 'Active'.
Let’s create an Employees table where the Status column defaults to 'Active' when not provided.
-- Create table with DEFAULT on Status
CREATE TABLE Employees (
ID INT NOT NULL,
Name VARCHAR(100),
Status VARCHAR(100) DEFAULT 'Active',
Salary DECIMAL(10,2)
);
Now insert some data with and without specifying the Status column:
-- Insert rows: with and without Status
INSERT INTO Employees (ID, Name, Salary)
VALUES (1, 'Alice', 50000.00);
INSERT INTO Employees (ID, Name, Status, Salary)
VALUES (2, 'Bob', 'Inactive', 45000.00);
After running the above INSERT statements, the table will look like this:
'Active' (taken from DEFAULT), Salary = 50000.00'Inactive' (explicitly provided), Salary = 45000.00Because the first insert did not mention Status, MySQL used the default value 'Active'. In the second insert, we explicitly set 'Inactive', so the default is not used.
DEFAULT for columns that should almost always have a standard value (e.g., status, flags, creation time).VARCHAR, number for INT).INSERT statement.DEFAULT with NOT NULL to guarantee that the column never stores NULL.Projects with a Status column that defaults to 'Pending'.Projects:
Status (should use the default).Status = 'Completed' (should override the default).DEFAULT value using ALTER TABLE.