
For an instructor lead, in-depth look at learning SQL click below.
In SQL, the DEFAULT constraint provides a default value for a column whenever there’s an insertion of a new record and no specific value has been assigned to this column. The main purpose is to maintain data integrity and prevent null or erroneous entries from occurring, especially when no value has been specified during a record’s creation.
1. Understanding the DEFAULT constraint
The syntax of the DEFAULT constraint in SQL is fairly straightforward:
1 2 3 4 5 6 7 |
CREATE TABLE Table_name( column1 datatype DEFAULT value, column2 datatype, ... ); |
Typically, the datatype could be INT, VARCHAR, DATE, etc, and value is the default value you want to set for this column.
2. Setting the DEFAULT constraint after table creation
There might be a scenario where you have already created a table and you want to add a DEFAULT constraint. In such cases, you can use the ALTER TABLE statement:
1 2 3 4 5 |
ALTER TABLE Table_name ADD CONSTRAINT Constraint_name DEFAULT value FOR column_name; |
3. A Practical Example
Let’s create a table named ‘Employees’ with a DEFAULT constraint on ‘JoiningDate’ column:
1 2 3 4 5 6 7 8 |
CREATE TABLE Employees ( ID int NOT NULL, LastName varchar(255), FirstName varchar(255), JoiningDate date DEFAULT GETDATE() ); |
This means that if you do not provide a specific joining date when inserting a new record, the current date will be used as a default.
4. Inserting Without a Specific Value for ‘JoiningDate’
Now if we insert a new record without a specific ‘JoiningDate’, SQL Server will automatically use the current date:
1 2 3 4 |
INSERT INTO Employees (ID, LastName, FirstName) VALUES (1, 'Doe', 'John'); |
5. Dropping a DEFAULT constraint
If we want to remove the DEFAULT constraint from a table, we can use the DROP CONSTRAINT command:
1 2 3 4 |
ALTER TABLE Table_name DROP CONSTRAINT Constraint_name; |
In conclusion, the DEFAULT constraint in SQL offers a measure of control over how data is inserted into tables. It assures data integrity and adds another useful tool to the data architect’s toolbox.