Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views14 pages

SQL Constraints

Uploaded by

leitich98
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views14 pages

SQL Constraints

Uploaded by

leitich98
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 14

SQL Constraints

 Home > Databases > DBMS

 « Previous
 Next »
Tutorial

 Database Introduction
 Data Model
 ER Modeling
 EER Model
 Functional Dependency
 Database Normalization
 Structured Query Language
 SQL Data Definition Language
 SQL Data Manipulation Language
 SQL Data Control Language
 SQL TCL
 SQL DRL / DSL
 SQL Joins
 SQL Views
 SQL Stored Procedure
 SQL Trigger
 SQL Cursor
 SQL Index
 SQL Query Processing
 Database Transaction Control
 Database Concurrency Control
 Two-Phase Locking
 Database Deadlock
 Database Backup and Recovery
 Data Warehouse
 Data Mining
 OLTP and OLAP
 CRM and SCM

What is constraints?

 A set of rules are defined to enforce the database integrity, is called


as Constraints.
 The main purpose of constraint is to permit or prohibit the values in
the columns.

Following are the Types of Constraint,


1. Primary Key
2. Foreign Key
3. Unique Key
4. Check Constraint
5. Not Null

 The above constraints are associated only with the tables.


 These constraints are applied to the table at the time of table creation.

Primary Key It identifies each row or record uniquely in a database table.


It cannot have NULL values.
A table can have only one primary key.
It contains unique values.
If a table has a primary key, then you cannot have two records of same value.

For Example: Empid INT PRIMARY KEY,

In the above example, there is one Employee table where Empid have a Primary Key.
When multiple fields are used as a primary key, is called as Composite key.

Syntax: PRIMARY KEY (column1, column2);


Foreign Key Foreign key is a logical rule about values in multiple columns or in tables.
It is a set of columns in a table.
It requires to match at least one primary key of a row in another table.
It defines the relationship between the tables.
The 'references' keyword is used while referencing the column into the another table.

For example: Empid INT PRIMARY KEY, FOREIGN KEY (Empid) references Department (Empid);

In the above example, there are two tables Employee and Department. The 'Empid' in Employee ta
key. In Department table, it takes reference of 'Empid' from Employee table using Foreign key with the ke
'references'.

Unique Key It prevents two records from having identical values in a particular column.
It identifies each record uniquely in a database table.
Primary key and Unique key both provide a guarantee of uniqueness for a column.
Primary key has a unique constraint automatically defined on it.

Note: Important thing to understand about the primary key and unique key, is that a table can have many u
but only one primary key can have per table.

Unique key is declared with 'NOT NULL' constraint at the time of creating a table.
It accepts only one NULL value.
It is a unique non-clustered index.

Check It enables a condition to check the value being entered into a record.
Constraint
For example: Age INT NOT NULL CHECK (Age >= 19)

Multiple Check constraints are used in a single column.


It returns true or false result based on the logical operator according to Boolean (logical) expressio

Null

 Null is a reserved keyword in SQL that indicates a data value does not
exist in the database.
 It identifies the Null special marker.
 Null introduced by E. F. Codd, Creator of the relational database
model.
 A Null value indicates that the value is unknown, not applicable and
has no value, but it does not mean that it has a zero value or a field which
contains spaces.
 It is used to represent a missing value.

For example:

CREATE TABLE employee(empid INT NOT NULL,


ename CHAR NOT NULL,
age INT NOT NULL,
city CHAR(25),
phone_no VARCHAR(20),
PRIMARY KEY (empid));

 In the above example, NOT NULL indicates that the column should
accept explicit value of the given data type. There are two columns
'address' and 'phone_no' which are not assigned with the NOT NULL, which
means that these columns could be NULL.
 Null is not a data value, but it is a marker of an absent value.
 It can cause problems when selecting data, because when comparing
an unknown value to any other value, the result is always unknown and not
included in the final results.
 IS NULL or IS NOT NULL is used to check for a NULL value.

Example of IS NOT NULL:

<employee> Table

empid ename age city phone_


001 ABC 28 Pune 12345678

002 XYZ 30 Mumbai 54687901

003 PQR 35 Kolhapur

SELECT empid, ename, age, city, phone_no


FROM employee
WHERE phone_no IS NOT NULL;

Output:
empid ename age city phone_n

001 ABC 28 Pune 12345678

002 XYZ 30 Mumbai 54687901

Example of IS NULL:
SELECT empid, ename, age, city, phone_no
FROM employee
WHERE phone_no IS NULL;

Output:
empid ename age city phone_

003 PQR 35 Kolhapur

 All aggregate function (min, max, sum, count) ignores the NULL values
except count() function.

When not to use NULL?

 NULL is not specify explicitly in SELECT statement. For eg. SELECT


NULL.
 NULL is not specify explicitly as an operand of scalar expression.
For example, X + NULL, it is illegal.

 NULL is not specify explicitly as an operand of a conditional


expression.
For example, WHERE a = NULL, it is illegal.

SQL Constraints
SQL Constraints are rules used to limit the type of data that can go into a table, to maintain the
accuracy and integrity of the data inside table.
Constraints can be divided into the following two types,

1. Column level constraints: Limits only column data.

2. Table level constraints: Limits whole table data.

Constraints are used to make sure that the integrity of data is maintained in the database.
Following are the most used constraints that can be applied to a table.

 NOT NULL

 UNIQUE

 PRIMARY KEY

 FOREIGN KEY

 CHECK

 DEFAULT

NOT NULL Constraint


NOT NULL constraint restricts a column from having a NULL value. Once NOT
NULL constraint is applied to a column, you cannot pass a null value to that column. It enforces
a column to contain a proper value.
One important point to note about this constraint is that it cannot be defined at table level.

Example using NOT NULL constraint


CREATE TABLE Student(s_id int NOT NULL, Name varchar(60), Age int);
The above query will declare that the s_id field of Student table will not take NULL value.

UNIQUE Constraint
UNIQUE constraint ensures that a field or column will only have unique values.
A UNIQUE constraint field will not have duplicate data. This constraint can be applied at
column level or table level.

Using UNIQUE constraint when creating a Table


(Table Level)
Here we have a simple CREATE query to create a table, which will have a column s_id with
unique values.
CREATE TABLE Student(s_id int NOT NULL UNIQUE, Name varchar(60), Age int);
The above query will declare that the s_id field of Student table will only have unique values
and wont take NULL value.

Using UNIQUE constraint after Table is created


(Column Level)
ALTER TABLE Student ADD UNIQUE(s_id);
The above query specifies that s_id field of Student table will only have unique value.
Primary Key Constraint
Primary key constraint uniquely identifies each record in a database. A Primary Key must
contain unique value and it must not contain null value. Usually Primary Key is used to index the
data inside the table.

Using PRIMARY KEY constraint at Table Level


CREATE table Student (s_id int PRIMARY KEY, Name varchar(60) NOT NULL, Age
int);
The above command will creates a PRIMARY KEY on the s_id.

Using PRIMARY KEY constraint at Column Level


ALTER table Student ADD PRIMARY KEY (s_id);
The above command will creates a PRIMARY KEY on the s_id.

Foreign Key Constraint


FOREIGN KEY is used to relate two tables. FOREIGN KEY constraint is also used to restrict
actions that would destroy links between tables. To understand FOREIGN KEY, let's see its use,
with help of the below tables:
Customer_Detail Table

c_id Customer_Name address

101 Adam Noida


102 Alex Delhi

103 Stuart Rohtak

Order_Detail Table

Order_id Order_Name c_id

10 Order1 101

11 Order2 103

12 Order3 102

In Customer_Detail table, c_id is the primary key which is set as foreign key
in Order_Detail table. The value that is entered in c_id which is set as foreign key
in Order_Detail table must be present in Customer_Detail table where it is set as primary key.
This prevents invalid data to be inserted into c_id column of Order_Detail table.
If you try to insert any incorrect data, DBMS will return error and will not allow you to insert the
data.

Using FOREIGN KEY constraint at Table Level


CREATE table Order_Detail(
order_id int PRIMARY KEY,
order_name varchar(60) NOT NULL,
c_id int FOREIGN KEY REFERENCES Customer_Detail(c_id)
);
In this query, c_id in table Order_Detail is made as foriegn key, which is a reference
of c_id column in Customer_Detail table.
Using FOREIGN KEY constraint at Column Level
ALTER table Order_Detail ADD FOREIGN KEY (c_id) REFERENCES
Customer_Detail(c_id);

Behaviour of Foriegn Key Column on Delete


There are two ways to maintin the integrity of data in Child table, when a particular record is
deleted in the main table. When two tables are connected with Foriegn key, and certain data in
the main table is deleted, for which a record exits in the child table, then we must have some
mechanism to save the integrity of data in the child table.

1. On Delete Cascade : This will remove the record from child table, if that value of foriegn key is

deleted from the main table.

2. On Delete Null : This will set all the values in that record of child table as NULL, for which the

value of foriegn key is deleted from the main table.

3. If we don't use any of the above, then we cannot delete data from the main table for which data

in child table exists. We will get an error if we try to do so.

ERROR : Record in child table exist


CHECK Constraint
CHECK constraint is used to restrict the value of a column between a range. It performs check
on the values, before storing them into the database. Its like condition checking before saving
data into a column.

Using CHECK constraint at Table Level


CREATE table Student(
s_id int NOT NULL CHECK(s_id > 0),
Name varchar(60) NOT NULL,
Age int
);
The above query will restrict the s_id value to be greater than zero.

Using CHECK constraint at Column Level


ALTER table Student ADD CHECK(s_id > 0);

What are SQL Functions?


SQL provides many built-in functions to perform operations on data. These functions
are useful while performing mathematical calculations, string concatenations, sub-
strings etc. SQL functions are divided into two categories,

1. Aggregate Functions

2. Scalar Functions

Aggregate Functions
These functions return a single value after performing calculations on a group of
values. Following are some of the frequently used Aggregrate functions.

AVG() Function
Average returns average value after calculating it from values in a numeric column.
Its general syntax is,
SELECT AVG(column_name) FROM table_name

Using AVG() function


Consider the following Emp table

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000

SQL query to find average salary will be,


SELECT avg(salary) from Emp;
Result of the above query will be,

avg(salary)
8200

COUNT() Function
Count returns the number of rows present in the table either based on some condition
or without condition.
Its general syntax is,
SELECT COUNT(column_name) FROM table-name

Using COUNT() function


Consider the following Emp table

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000

SQL query to count employees, satisfying specified condition is,


SELECT COUNT(name) FROM Emp WHERE salary = 8000;
Result of the above query will be,
count(name)

Example of COUNT(distinct)
Consider the following Emp table

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000

SQL query is,


SELECT COUNT(DISTINCT salary) FROM emp;
Result of the above query will be,

count(distinct salary)

You might also like