Defining Constraints

Constraints are defined during the CREATE TABLE or ALTER TABLE command. They are used to enforce data integrity and ensure that valid data is entered into the columns. Constraints can also ensure that integrity is maintained between tables. A column-level constraint applies to a single column, whereas a table-level constraint applies to multiple columns, even if it does not apply to every column. PRIMARY KEY, UNIQUE, FOREIGN KEY, DEFAULT, and CHECK are all examples of constraints. Both PRIMARY KEY and UNIQUE constraints are used to enforce uniqueness on columns. However, a UNIQUE constraint can allow NULLs.

Tip

If you need to know the constraints already on a table, you can use the stored procedure

sp_helpconstraint table_name ...

Get Sams Teach Yourself Transact-SQL in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.