Loading

MySQL DEFAULT Constraint

MySQL DEFAULT Constraint is used to set default values for a data column. When we add a new record and we are not inserting any value of a particular DEFAULT Constraint column, then the default value will specify.

The syntax for DEFAULT Constraint:-

column_name datatype DEFAULT default_value;

Note:- Default value of DEFAULT Constraint must be a literal constant eg. a string or a number.

Note:- Default value of DEFAULT Constraint can be used to insert system values like CURRENT_DATE(), CURRENT_TIMESTAMP, NOW(),  etc.

Note:- The default value does not affect the current data of the table, It only applies to the new rows of the particular column which hold the DEFAULT Constraint of the table.

Example:-

CREATE TABLE Employee(

ID INT AUTO_INCREMENT PRIMARY KEY,

Name varchar(500) NOT NULL,

Department varchar(255),

Sex varchar(5) DEFAULT ‘M”,

Location varchar(255)

);

The syntax for adding DEFAULT CONSTRAINT an existing table:-

ALTER TABLE table_name  ALTER column_name SET DEFAULT default_name;

Example:- ALTER TABLE Emloyee ALTER Location SET DEFAULT CURRENT_TIMESTAMP;

The syntax for deleting DEFAULT Constraint for the existing table:-

ALTER TABLE table_name  ALTER column_name DROP DEFAULT;

Example:- ALTER TABLE Emloyee ALTER Location DROP DEFAULT;

Read Also:-

PRIMARY KEY CONSTRAINT
FOREIGN KEY CONSTRAINT
UNIQUE CONSTRAINT
CHECK CONSTRAINT
NOT NULL CONSTRAINT
DEFAULT CONSTRAINT
CREATE INDEX CONSTRAINT
AUTO_INCREMENT CONSTRAINT
INDEX CONSTRAINT
ENUM CONSTRAINT

For more detail about MySQL constraints please follow here

Share with:


One thought on “MySQL DEFAULT Constraint

Leave a Reply

Connect with:

z35W7z4v9z8w
Verified by ExactMetrics