MySQL : DEFAULT Constraint

In MySQL, the DEFAULT constraint is used to specify a default value for a column. If no value is provided for the column during an INSERT operation, the default value will be used instead.

Here's how you can use the DEFAULT constraint while creating a table:


CREATE TABLE table_name (
    column_name data_type DEFAULT default_value,
    ...
);

 

For example, suppose you have a table named employees and you want to set a default value of Unknown for the department column:


CREATE TABLE employees (
    id INT PRIMARY KEY,
    name VARCHAR(100),
    department VARCHAR(100) DEFAULT 'Unknown'
);

 

In this example, if no value is specified for the department column during an INSERT operation, the default value Unknown will be inserted into the department column automatically.

You can also use expressions or function calls as default values, as long as they evaluate to a valid value of the specified data type. For example, you can use the CURRENT_TIMESTAMP function to set the default value of a column to the current timestamp:


CREATE TABLE logs (
    id INT PRIMARY KEY,
    message TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

 

In this example, if no value is specified for the created_at column during an INSERT operation, the current timestamp will be inserted into the created_at column automatically.

Using the DEFAULT constraint is useful for ensuring that columns always have a value, even if one is not provided during an INSERT operation. It helps to maintain data integrity and consistency in the database.