0% found this document useful (0 votes)
84 views8 pages

Bs (Se) F 2019: C T: D S C C: CSS 2062 2019/Comp/AFN/BS (SE) /1925 S B: S T: M - S O

This document discusses different types of constraints in SQL including: - Foreign key constraints which link data between tables based on primary keys. - Check constraints which limit column values based on logical expressions. - Default constraints which provide default values for columns if no value is specified. - Composite primary keys which use two or more columns as a primary key. - Examples are provided for defining each type of constraint when creating or altering tables.

Uploaded by

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

Bs (Se) F 2019: C T: D S C C: CSS 2062 2019/Comp/AFN/BS (SE) /1925 S B: S T: M - S O

This document discusses different types of constraints in SQL including: - Foreign key constraints which link data between tables based on primary keys. - Check constraints which limit column values based on logical expressions. - Default constraints which provide default values for columns if no value is specified. - Composite primary keys which use two or more columns as a primary key. - Examples are provided for defining each type of constraint when creating or altering tables.

Uploaded by

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

BS(SE)FALL 2019

COURSE TITLE: DATABASE SYSTEM


COURSE CODE: CSS 2062
ENROLMENT NUMBER: 2019/Comp/AFN/BS(SE)/1925
SUBMITTED BY: ERAJ IRFAN
SUBMITTED TO: MS. SURRAYA OBAID

DEPARTMENT OF COMPUTER SCIENCE AND SOFTWARE ENGINEERING


JINNAH UNIVERSITY FOR WOMEN
5-C NAZIMABAD, KARACHI 74600
LAB SESSION 9: MORE CONSTRAINTS
FOREIGN KEY Constraints
A foreign key (FK) is a column or combination of columns used to establish and enforce a link
between the data in two tables. A link is created between two tables by adding the column or
columns that hold one table's primary key values to the other table. This column becomes a
foreign key in the second table.

You can create a foreign key by defining a FOREIGN KEY constraint when you create or alter a
table. A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in
another table; it can also be defined to reference the columns of a UNIQUE constraint in another
table.

Examples on Defining a FOREIGN KEY constraint


Consider following Orders table to define a foreign key (Please refer to the exercise # 5 for
customers and products table). In this table we have two foreign keys, we will create both
of these foreign key constraint in two different ways, one at the time of table creation and
another with the table modification statement.

Orders:
Column Name Data Type Size Constraints
Orderid Nchar 5 NOT NULL
Customerid Nchar 5 NOT NULL
Productid Int 4 NOT NULL
OrderDate Datetime - NULL
Create Table Orders
(
OrderId nchar(5) NOT NULL CONSTRAINT order_id PRIMARY
KEY, CustomerId nchar(5) NOT NULL
CONSTRAINT cust_id_fk FOREIGN KEY REFERENCES customers
(customerid), ProductId int NOT NULL,
OrderDate datetime NULL )

ALTER TABLE orders


ADD CONSTRAINT fk_pro
FOREIGN KEY (ProductId)
REFERENCES Products(ProductId)

CHECK Constraints
CHECK constraints enforce domain integrity by limiting the values that are accepted by a
column. They are similar to FOREIGN KEY constraints in that they control the values that
are placed in a column. The difference is in how they determine which values are valid:
FOREIGN KEY constraints get the list of valid values from another table, and CHECK
constraints determine the valid values from a logical expression that is not based on data
in another column.

For example, it is possible to limit the range of values for a salary column by creating a
CHECK constraint that allows only data that ranges from $15,000 through $100,000. This
prevents salaries from being entered beyond the normal salary range. You can create a

CHECK constraint with any logical (Boolean) expression that returns TRUE or FALSE based
on the logical operators. For the previous example, the logical expression is:

salary >= 15000 AND salary <= 100000

It is possible to apply multiple CHECK constraints to a single column. These are evaluated
in the order in which created. It is also possible to apply a single CHECK constraint to
multiple columns by creating it at the table level.

Examples on Defining a CHECK constraint


CHECK constraints can be created when the table is created, as part of the table definition
or added to an existing table. To apply the above salary constraint, we have added a new
salary column to the Employees table of exercise # 5 with the following table structure.
Observe the two different ways of defining the check constraint given below.

Employees:
Column Name Data Type Size Constraints
Employeeid Int 4 NOT NULL
LastName Nvarchar 20 NOT NULL
FirstName Nvarchar 20 NOT NULL
Title Nvarchar 10 NULL
BirthDate Datetime 8 NULL
HireDate Datetime 8 NULL
Address Nvarchar 60 NULL
Salary Smallmoney NOT NULL
Note: In the following example, only two columns are added to the employees table
because we are using this example just for demonstration purpose that how a table level
check constraint can be applied, but you have to add other columns shown above as well.
Create Table Employees
(
Employeeid int NOT NULL Constraint emp_pk PRIMARY KEY,
salary smallmoney NOT NULL
CONSTRAINT chk_sal CHECK (salary >= 15000 AND salary <= 100000)
)
ALTER TABLE Employees
ADD CONSTRAINT check_sal
CHECK (salary >= 15000 AND salary <= 100000)

After applying above queries try to perform the following Insert operation on the
Employees table. It will throw error indicating the name of constraint.

Insert into Employees (Employeeid, lastname, firstname, salary)


Values (1212, ‘abc’, ‘xyz’, 10000)

DEFAULT definitions
Each column in a record must contain a value, even if that value is NULL. There are
situations when you need to load a row of data into a table but you do not know the value
for a column, or the value does not yet exist. A better solution can be to define a DEFAULT
definition for the column. For example, it is common to specify zero as the default for
numeric columns, or N/A as the default for string columns when no value is specified.

If a column does not allow null values and does not have a DEFAULT definition, you must
specify a value for the column explicitly or SQL Server will return an error indicating that
the column does not allow null values.

You can also explicitly instruct SQL Server to insert the default value for the column using
the DEFAULT VALUES clause of the INSERT STATEMENT.

Examples on Defining a DEFAULT value


Default definitions can be defined as part of the table definition or as part of the column
definition. Following example adds salary column to the Employees table and assigns a
default value of 15000.

ALTER TABLE employees


ADD salary smallmoney NOT NULL
CONSTRAINT chk_sal
DEFAULT 15000

Following example creates the same orders table with default value assigned to the
orderdate field, which selects the current date from system.

Create Table Orders


(
OrderId nchar(5) NOT NULL CONSTRAINT order_id PRIMARY
KEY, CustomerId nchar(5) NOT NULL
CONSTRAINT cust_id_fk FOREIGN KEY REFERENCES customers (customerid),
OrderDate datetime NULL CONSTRAINT def_date DEFAULT getDate()
)
Defining composite primary key
Example :

CREATE TABLE SHOPS


(SHOPNO INT NOT NULL,
AREACODE INT NOT NULL,
CONSTRAINT COMPK PRIMARY KEY(SHOPNO,AREACODE))

Defining composite primary key as a foreign key in another table


CREATE TABLE CUSTOMERINFO
(CUSTOMERNO INT NOT NULL,
CUSTOMERNAME VARCHAR(40) NOT NULL,
SHOPNO INT NOT NULL,
AREACODE INT NOT NULL,
CONSTRAINT SHOPAREA FOREIGN KEY(SHOPNO,AREACODE) REFERENCES
SHOPS(SHOPNO,AREACODE))
Exercise

1) Create a table in which you can define primary key, check constraint and default
constraint.
Primary Key:

Check Constraint:
Default Constraint:

2) Now create another table in which use above table’s primary key as foreign key.
Primary Key as Foreign Key:

3) Create a third table in which define composite primary key on any two attributes.
Composite Primary Key:
4) Create a fourth table in which use above table’s composite primary key as foreign
key.

Composite Primary Key as Foreign Key:

You might also like