Constraints in SQL must be known Concepts.

Ankush kunwar
2 min readJan 12, 2023

--

In SQL, a constraint is a rule that defines the acceptable values for a column in a table. Constraints can be used to enforce data integrity and ensure that only valid data is entered into the database. For example, you might use a constraint to ensure that a column only contains positive integers or to ensure that a column has a unique value for each row.

There are several different types of constraints that you can use in SQL:

NOT NULL: This constraint ensures that a column cannot contain a NULL value.

UNIQUE: This constraint ensures that all values in a column are unique.

FOREIGN KEY: This constraint is used to enforce a link between the data in two tables. It ensures that the value in a column in one table must exist in a column in another table.

CHECK: This constraint allows you to specify a condition that must be met for a value to be accepted.

DEFAULT: This constraint specifies a default value for a column. If no value is provided for the column when a new row is inserted, the default value will be used.

Here is an example of how you might use constraints in a CREATE TABLE statement:

CREATE TABLE users (
id INTEGER PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
age INTEGER CHECK (age > 0)
);

This statement creates a table called users with four columns: id, username, password, and email. The id column is defined as the primary key, which means it is a unique identifier for each row in the table. The username and email columns are both defined as UNIQUE and NOT NULL, which means that they must have a unique value and cannot contain a NULL value. The age column is defined with a CHECK constraint that ensures that only positive integers are accepted.

Thank you for reading !!!

If you enjoy this article and would like to Buy Me a Coffee, please click here.

you can connect with me on Linkedin.

--

--

No responses yet