SQL Constraints
Constraints in SQL are the rules applied to the values of individual columns. They add information about how a column can be used after specifying the data type for a column. They can be used to tell the database to reject inserted data that does not adhere to a certain restriction.
Here are some of the constraints that can be set:
PRIMARY KEYcolumns can be used to uniquely identify the row. Attempts to insert a row with an identical value to a row already in the table will result in a constraint violation which will not allow you to insert the new row.UNIQUEcolumns have a different value for every row. This is similar toPRIMARY KEYexcept a table can have many differentUNIQUEcolumns.NOT NULLcolumns must have a value. Attempts to insert a row without a value for aNOT NULLcolumn will result in a constraint violation and the new row will not be inserted.DEFAULTcolumns take an additional argument that will be the assumed value for an inserted row if the new row does not specify a value for that column.
Note: There can be only one PRIMARY KEY column per table, but there can be multiple UNIQUE columns.
The statement below sets constraints on the celebs table:
CREATE TABLE celebs (id INTEGER PRIMARY KEY,name TEXT UNIQUE,grade INTEGER NOT NULL,age INTEGER DEFAULT 10);
idcolumn is thePRIMARY KEY.namecolumn isUNIQUE.gradecolumn isNOT NULL.agecolumn has aDEFAULTof 10.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn SQL on Codecademy
- Learn to analyze data with SQL and prepare for technical interviews.
- Includes 9 Courses
- With Certificate
- Beginner Friendly.17 hours
- In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.
- Beginner Friendly.5 hours