Assume you are designing a table in SQL and you want some columns to have specific default values in case the user does not input a value for them. This feature can be very helpful because it allows you to enforce certain requirements for entries and prevent invalid data from being entered into the table.
In SQL, using a default value can help you provide necessary suggestions to users or preset values in the system that are essential for data integrity or are foundational. This process may save time and make programming easier for you.
To define a default value, you simply need to specify the desired default value for the column at the time of table creation. This can be done with the following command:
CREATE TABLE users (
id INT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
Let’s examine this code line by line:
CREATE TABLE users
In this section, we create a table named users
that can store data related to users.
id INT PRIMARY KEY
In this line, a column named id
is defined, which holds an INT
data type and is considered the primary key. This means that each value in this column must be unique to identify each user.
username VARCHAR(50) NOT NULL
The column username
is also defined, which has a VARCHAR
data type with a maximum length of 50 characters, and this column cannot be empty (NOT NULL).
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
Here, we have a new column named created_at
that has a DATETIME
data type. If no value is input by the user, the value CURRENT_TIMESTAMP
will automatically be recorded.