在 SQL 中,DEFAULT
约束用于在我们尝试向列中插入空值时设置默认值。
示例
-- set default value of college_country column to 'US'
CREATE TABLE College (
college_id INT PRIMARY KEY,
college_code VARCHAR(20),
college_country VARCHAR(20) DEFAULT 'US'
);
这里,college_country 列的默认值是 US。
如果尝试在 college_country 列中存储 NULL
值,则其值将默认为 US。
DEFAULT 约束语法
SQL DEFAULT
约束的语法是
CREATE TABLE table_name (
column_name data_type DEFAULT default_value
);
这里,
table_name
是要创建的表的名称column_name
是要实现约束的列的名称data_type
是列的数据类型,例如INT
、VARCHAR
等。default_value
是插入的空值将被替换的值
示例:SQL DEFAULT 约束
-- don't add any value to college_country column
-- thus default value 'US' is inserted to the column
INSERT INTO Colleges (college_id, college_code)
VALUES (1, 'ARP76');
-- insert 'UAE' to the college_country column
INSERT INTO Colleges (college_id, college_code, college_country)
VALUES (2, 'JWS89', 'UAE');
college_country
列的默认值设置为 US
。当我们插入一行而未指定 college_country
列的值时,它将自动默认为 US
。
但是,如果明确为 college_country
列插入一个值,例如 UAE
,则默认值将被忽略,列将设置为 UAE
。
如果为 college_country
列明确提供 NULL
,则该值将设置为 NULL
,从而覆盖默认值。
带有 ALTER TABLE 的 DEFAULT 约束
我们还可以使用 ALTER TABLE 命令将 DEFAULT
约束添加到现有列。例如,
SQL Server
ALTER TABLE College
ADD CONSTRAINT country_default
DEFAULT 'US' FOR college_country;
PostgreSQL
ALTER TABLE College
ALTER COLUMN college_code SET DEFAULT 'US';
MySQL
ALTER TABLE College
ALTER college_country SET DEFAULT 'US';
Oracle
ALTER TABLE College
MODIFY college_country DEFAULT 'US';
这里,如果插入时传入 NULL
,则 college_country
列的默认值设置为 US。
删除默认约束
我们可以使用 DROP
子句来删除列中的 DEFAULT
约束。例如,
SQL Server, PostgreSQL, Oracle
ALTER TABLE College
ALTER COLUMN college_country DROP DEFAULT;
MySQL
ALTER TABLE College
ALTER college_country DROP DEFAULT;
这里,SQL 命令从 college_country 列中删除了 DEFAULT
约束。
另请阅读