A DEFAULT
constraint is used to provide a default value for a column when no value is specified during an insert operation. This helps maintain data integrity by ensuring that a column always has a valid value.
The basic syntax for defining a DEFAULT constraint is as follows:
CREATE TABLE table_name (
column1 datatype DEFAULT default_value,
column2 datatype,
...
);
Here’s an example of creating a table with a DEFAULT constraint:
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(100),
Age INT DEFAULT 18,
Salary DECIMAL(10, 2) DEFAULT 30000.00
);
In this example, if no age or salary is specified when a new employee is added, the age will default to 18 and the salary to 30,000.00.
You can define DEFAULT constraints on multiple columns in a table:
CREATE TABLE Products (
ProductID INT PRIMARY KEY,
ProductName VARCHAR(100),
Price DECIMAL(10, 2) DEFAULT 0.00,
Quantity INT DEFAULT 0
);
This ensures that if no price or quantity is specified, both will default to 0.
When using the DEFAULT
constraint, keep in mind:
GETDATE()
for current date/time).