Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

SQL DEFAULT Constraint

SQL DEFAULT Constraint

The DEFAULT constraint is used to insert a default value into a column.

If no other value is specified, the default value is added to all new records.

Syntax

** 1. Define a DEFAULT constraint when creating a table:**

CREATE TABLE 表名 (
    列名 数据类型 DEFAULT 默认值
);

2. Add a DEFAULT constraint to an existing table:


ALTER TABLE 表名
ALTER COLUMN 列名 SET DEFAULT 默认值;

Example

1. Define a DEFAULT constraint when creating a table

Example

CREATE

TABLE

Employees

(

    EmployeeID

INT

PRIMARY

KEY

,

    FirstName

VARCHAR

(

50

)

,

    LastName

VARCHAR

(

50

)

,

    HireDate

DATE

DEFAULT

GETDATE

(

)

,

-- The default value is the current date

    Salary

DECIMAL

(

10

,

2

)

DEFAULT

0.00

-- The default value is 0.00

)

;

2. Add a DEFAULT constraint to an existing table


ALTER TABLE Employees
ALTER COLUMN Salary SET DEFAULT 0.00;

3. Use default values when inserting data


INSERT INTO Employees (EmployeeID, FirstName, LastName)
VALUES (1, 'John', 'Doe');

If no values are provided for HireDate and Salary, the database automatically uses the default values.


Drop DEFAULT constraint

The way to drop it differs across databases:

1、SQL Server


ALTER TABLE 表名
DROP CONSTRAINT 约束名;

2、MySQL


ALTER TABLE 表名
ALTER COLUMN 列名 DROP DEFAULT;

3、Oracle


ALTER TABLE 表名
MODIFY 列名 DEFAULT NULL;

4、MS Access


ALTER TABLE 表名
ALTER COLUMN 列名 DROP DEFAULT;

Notes

Applicable scenarios