SQL constraints the data that can be in a table. A violation of a constraint causes an action to be aborted. Constraints can be defined upon creation or using the ALTER TABLE statement once created. The general syntax of a CREATE (or use ALTER instead of CREATE) when defining constraints is as follows:
CREATE TABLE tablename
(
columnname datatype(size) constraintname,
columnname datatype(size) constraintname,
columnname datatype(size) constraintname,
columnname datatype(size) constraint name,
columnname datatype(size) constraint name,
);
Obviously, replace columnname with the name of each of your column, datatype with the types of data your column contains and constraint name with the constraint you wish to use. You have the following constraints available:
- CHECK: Verify that values meet the defined condition
- DEFAULT: Sets a default value for new rows in a column
- FOREIGN KEY: Verify referential integrity of data in a table to match values in another
- NOT NULL – Columns cannot store a NULL value (be empty)
- PRIMARY KEY – Columns cannot store a NULL value AND values in rows must be unique
- UNIQUE – Each row in a column must be unique
For example, the NOT NULL constraint would be defined as follows:
CREATE TABLE testingnotnull
(
telephonenumber int NOT NULL,
);
If you have an app sitting in front of a database, then use these with caution, as if SQL just terminates an operation your app might have unexpected integrity issues.