What are SQL constraints and how are they used?

Learn SQL with Udemy

For an instructor lead, in-depth look at learning SQL click below.


SQL constraints are rules that are used to limit the type of data that can be stored in a table. Constraints provide a way to enforce the integrity of a database, ensuring that the data in a table adheres to a certain rule or specification. These constraints can be applied at the column level or the table level.

Types of SQL Constraints

There are several types of SQL constraints that can be applied when creating a table. These constraints include:

  • NOT NULL: This constraint ensures that a column cannot have a NULL value.
  • UNIQUE: The UNIQUE constraint ensures that all values in a column are different.
  • PRIMARY KEY: A PRIMARY KEY constraint uniquely identifies each record in a table.
  • FOREIGN KEY: A FOREIGN KEY is a field (or collection of fields) in one table, which refers to the PRIMARY KEY in another table.
  • CHECK: The CHECK constraint ensures that all values in a column satisfies certain conditions.

Examples of SQL Constraints

Let’s go through some examples on how to use these constraints in SQL queries.

In this example, we have an Employees table with four columns: ID, FirstName, LastName, and Email. The ID field is the primary key and therefore must be unique. The FirstName and LastName fields can’t be NULL, ensuring that these fields will always have values. The Email field is unique, ensuring that no two employees can have the same email.

This is another example where we have an Orders table with an employee id as a FOREIGN KEY. It refers to the Employees table, meaning that all EmployeeIDs in the Orders table must also be present in the Employees table.

The above example demonstrates how to use the CHECK constraint where the quantity of the products should always be greater than 0.

Conclusion

SQL constraints are a powerful way to ensure that the data stored in your database adhere to the rules you set. This also helps to maintain the accuracy and integrity of the data. By using these SQL constraints effectively, you can prevent invalid data entry into your tables and create more robust databases.

Leave a Comment