DEFAULT Constraint Example
Let’s create a MySQL table “blog_posts”
CREATE TABLE blog_posts ( post_id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, content TEXT NOT NULL, published_date DATE DEFAULT CURRENT_DATE );
Final Table:
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
post_id | int | NO | PRI | NULL | auto_increment |
title | varchar(255) | NO | NULL | ||
content | text | NO | NULL | ||
published_date | date | YES | CURRENT_DATE |
In this table, we have set the publish_date value to default value of the current date using CURRENT_DATE. So if a new entry doesn’t provide value for publish_date column, MySQL will automatically take the current date.
Let’s try and insert new values into this table.
INSERT INTO
blog_posts (title, content)
VALUES
('My First Blog Post', 'Hello, world! This is my inaugural post.');
Output:
post_id | title | content | published_date |
---|---|---|---|
1 | My First Blog Post | Hello, world! This is my inaugural post. | 2023-03-12 |
MySQL DEFAULT Constraint
The MySQL DEFAULT constraint returns the default value for a table column. The DEFAULT value of a column is a value used in the case, when there is no value specified by the user.
To use this function there should be a DEFAULT value assigned to the column. Otherwise, it will generate an error.