A DEFAULT constraint in SQL is used to specify a default value for a column in a table. This constraint ensures that if a value is not explicitly provided for the column when inserting a new row, the default value will be used instead.
Here's a basic example of how to use DEFAULT constraint in SQL:
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50), Gender CHAR(1) DEFAULT 'U', -- U stands for Unknown HireDate DATE DEFAULT GETDATE() -- Sets default value to current date );
In this example:
Gender
column has a DEFAULT constraint set to 'U', meaning if no gender is provided during insertion, 'U' (for Unknown) will be used as the default value.HireDate
column has a DEFAULT constraint set to GETDATE()
, which means the current date will be used as the default value if no hire date is provided during insertion.It's important to note that not all database systems use GETDATE()
; the function for retrieving the current date might differ depending on the SQL flavor you're using. Similarly, the syntax for DEFAULT constraints can vary slightly between different database management systems.