SQL Default
In SQL, the DEFAULT
constraint is used to specify a default value for a column. If a value is not specified for the column when a new row is inserted, the default value will be used instead.
Here is an example of how to create a table with a DEFAULT
constraint:
CREATE TABLE employees ( employee_id INT PRIMARY KEY, employee_name VARCHAR(50), hire_date DATE DEFAULT GETDATE(), salary DECIMAL(10,2) DEFAULT 50000.00 );
In this example, the employees
table has a DEFAULT
constraint on the hire_date
and salary
columns. If a value is not specified for the hire_date
column, the default value will be the current date and time. If a value is not specified for the salary
column, the default value will be 50000.00.
You can also use the DEFAULT
constraint to specify a column's default value as a function of other columns in the same row. For example:
CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT, order_date DATE DEFAULT GETDATE(), order_total DECIMAL(10,2), discount DECIMAL(4,2) DEFAULT 0.0, total_after_discount AS (order_total - (order_total * discount)) );
In this example, the orders
table has a DEFAULT
constraint on the discount
column. If a value is not specified for the discount
column, the default value will be 0.0. The total_after_discount
column is computed as a function of the order_total
and discount
columns.
You can modify the DEFAULT
constraint for an existing table using the ALTER TABLE
command:
ALTER TABLE employees ALTER COLUMN hire_date SET DEFAULT GETDATE();
In this example, we are modifying the DEFAULT
constraint for the hire_date
column of the employees
table using the ALTER TABLE
command.
By using the DEFAULT
constraint, you can ensure that a column always has a value, even if a value is not specified for it when a new row is inserted. This can help simplify data entry and ensure that data is consistent across multiple rows in the table.