Beginners Guide to SQL – SQL Constraints

(SQL Tutorials for Citizen Data Scientist)

SQL Constraints

In this tutorial you will learn how to use SQL constraints.

What is Constraint?

A constraint is simply a restriction placed on one or more columns of a table to limit the type of values that can be stored in that column. Constraints provide a standard mechanism to maintain the accuracy and integrity of the data inside a database table.

There are several different types of constraints in SQL, including:

  • NOT NULL
  • PRIMARY KEY
  • UNIQUE
  • DEFAULT
  • FOREIGN KEY
  • CHECK

Now, let’s discuss each of these constraints in detail.

NOT NULL Constraint

The NOT NULL constraint specifies that the column does not accept NULL values.

This means if NOT NULL constraint is applied on a column then you cannot insert a new row in the table without adding a non-NULL value for that column.

The following SQL statement creates a table named persons with four columns, out of which three columns, idname and phone do not accept NULL values.

Example

CREATE TABLE persons (
    id INT NOT NULL,
    name VARCHAR(30) NOT NULL,
    birth_date DATE,
    phone VARCHAR(15) NOT NULL
);

Note: A null value or NULL is different from zero (0), blank, or a zero-length character string such as ''NULL means that no entry has been made.


PRIMARY KEY Constraint

The PRIMARY KEY constraint identify the column or set of columns that have values that uniquely identify a row in a table. No two rows in a table can have the same primary key value. Also, you cannot enter NULL value in a primary key column.

The following SQL statement creates a table named persons and specifies the id column as the primary key. That means this field does not allow NULL or duplicate values.

Example

CREATE TABLE persons (
    id INT NOT NULL PRIMARY KEY,
    name VARCHAR(30) NOT NULL,
    birth_date DATE,
    phone VARCHAR(15) NOT NULL
);

Tip: The primary key typically consists of one column in a table, however more than one column can comprise the primary key, e.g. either the employee’s email address or assigned identification number is the logical primary key for an employee table.


UNIQUE Constraint

The UNIQUE constraint restricts one or more columns to contain unique values within a table.

Although both a UNIQUE constraint and a PRIMARY KEY constraint enforce uniqueness, use a UNIQUE constraint instead of a PRIMARY KEY constraint when you want to enforce the uniqueness of a column, or combination of columns, that is not the primary key.

The following SQL statement creates a table named persons and specifies the phone column as unique. That means this field does not allow duplicate values.

Example

CREATE TABLE persons (
    id INT NOT NULL PRIMARY KEY,
    name VARCHAR(30) NOT NULL,
    birth_date DATE,
    phone VARCHAR(15) NOT NULL UNIQUE
);

Note: Multiple UNIQUE constraints can be defined on a table, whereas only one PRIMARY KEY constraint can be defined on a table. Also, unlike PRIMARY KEY constraints, the UNIQUE constraints allow NULL values.


DEFAULT Constraint

The DEFAULT constraint specifies the default value for the columns.

A column default is some value that will be inserted in the column by the database engine when an INSERT statement doesn’t explicitly assign a particular value.

The following SQL statement creates a default for the country column.

Example

CREATE TABLE persons (
    id INT NOT NULL PRIMARY KEY,
    name VARCHAR(30) NOT NULL,
    birth_date DATE,
    phone VARCHAR(15) NOT NULL UNIQUE,
    country VARCHAR(30) NOT NULL DEFAULT 'Australia'
);

Note: If you define a table column as NOT NULL, but assign the column a default value, then in the INSERT statement you don’t need to explicitly assign a value for that column in order to insert a new row in the table.


FOREIGN KEY Constraint

A foreign key (FK) is a column or combination of columns that is used to establish and enforce a relationship between the data in two tables.

Here’s a sample diagram showing the relationship between the employees and departments table. If you look at it carefully, you will notice that the dept_id column of the employees table matches the primary key column of the departments table. Therefore, the dept_id column of the employees table is the foreign key to the departments table.

Foreign Key Relationship Diagram

In MySQL you can create a foreign key by defining a FOREIGN KEY constraint when you create a table as follow. The following statement establishes a foreign key on the dept_id column of the employees table that references the dept_id column of the departments table.

Example

CREATE TABLE employees (
    emp_id INT NOT NULL PRIMARY KEY,
    emp_name VARCHAR(55) NOT NULL,
    hire_date DATE NOT NULL,
    salary INT,
    dept_id INT,
    FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
);

CHECK Constraint

The CHECK constraint is used to restrict the values that can be placed in a column.

For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows values only from 3,000 to 10,000. This prevents salaries from being entered beyond the regular salary range. Here’s an example:

Example

CREATE TABLE employees (
    emp_id INT NOT NULL PRIMARY KEY,
    emp_name VARCHAR(55) NOT NULL,
    hire_date DATE NOT NULL,
    salary INT NOT NULL CHECK (salary >= 3000 AND salary <= 10000),
    dept_id INT,
    FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
);

Note: MySQL does not support SQL check constraint. The CHECK clause is parsed however but ignored by all storage engines of the MySQL.

 

Beginners Guide to SQL – SQL Constraints

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!