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

Cs8481 Dbms Lab Ex2

The document discusses various SQL constraints that can be used to enforce data integrity when defining database tables. It explains constraints like NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT and INDEXES. It also covers how to add these constraints when creating or altering tables using the CREATE TABLE and ALTER TABLE statements. Finally, it provides examples of the GROUP BY, HAVING and ORDER BY clauses that are used to control how results are grouped and sorted in SQL queries.

Uploaded by

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

Cs8481 Dbms Lab Ex2

The document discusses various SQL constraints that can be used to enforce data integrity when defining database tables. It explains constraints like NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT and INDEXES. It also covers how to add these constraints when creating or altering tables using the CREATE TABLE and ALTER TABLE statements. Finally, it provides examples of the GROUP BY, HAVING and ORDER BY clauses that are used to control how results are grouped and sorted in SQL queries.

Uploaded by

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

CS8481 DATABASE MANAGEMENT SYSTEMS LABORATORY

Ex: 2 CREATING A DATABASE TO SET VARIOUS CONSTRAINTS

 SQL constraints are used to specify rules for the data in a table.

Constraints can be specified


1. When the table is created with the CREATE TABLE statement.
2. After the table is created with the ALTER TABLE statement.

The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in
a table
 FOREIGN KEY - Uniquely identifies a row/record in another table
 CHECK - Ensures that all values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column when no value is specified
 INDEX - Used to create and retrieve data from the database very quickly

1) NOT NULL CONSTRAINT:

 By default, a column can hold NULL values.

 The NOT NULL constraint enforces a column to NOT accept NULL values.

 This enforces a field to always contain a value, which means that you cannot insert a new record, or
update a record without adding a value to this field.

NOT NULL Constraint in Create Table:

create table <tablename> (Attribute1 <Datatype1> not null , Attribute2 <Datatype2>...) ;

NOT NULL Constraint in Alter Table:

alter table <tablename> modify <Attribute2> < Datatype2> not null ;


************************************************************************************

2) UNIQUE CONSTRAINT:

 The UNIQUE constraint ensures that all values in a column are different.

UNIQUE Constraint in Create Table:

i) create table <tablename> (<Attribute1> <Datatype1> unique, <Attribute2> <Datatype2>)

ii) create table <tablename> (<Attribute1> <Datatype1> , <Attribute2> <Datatype2>,

constraint <constraint_name> unique(<Attribute1>) ;

UNIQUE constraint on multiple columns

i) create table <tablename> (<Attribute1> <Datatype1> unique, <Attribute2> <Datatype2> unique)

ii) create table <tablename> (<Attribute1> <Datatype1> , <Attribute2> <Datatype2>,

constraint <constraint_name> unique(<Attribute1> , <Attribute2>) ;

UNIQUE Constraint in Alter Table:

i) alter table <tablename> add unique(<Attribute>) ;


ii) alter table <tablename> add constraint<constraint_name>unique(<Attribute>);

DROP UNIQUE Constraint:

alter table <tablename> drop constraint <constraint_name>;

*********************************************************************************

3) PRIMARY KEY CONSTRAINT:

 The PRIMARY KEY constraint uniquely identifies each record in a table.

 Primary keys must contain UNIQUE values, and cannot contain NULL values.

 Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column
or set of columns.

 A PRIMARY KEY constraint automatically has a UNIQUE constraint.

 However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint
per table.

PRIMARY KEY Constraint in Create Table:

i) create table <tablename> (<Attribute1> <Datatype1> primary key , <Attribute2> <Datatype2>)


ii) create table <tablename> (<Attribute1> <Datatype1> , <Attribute2> <Datatype2>,

constraint <constraint_name> primary key (<Attribute1>) ;

PRIMARY KEY Constraint in Alter Table:

i) alter table <tablename> add primary key (<Attribute>) ;

ii) alter table <tablename> add constraint <constraint_name> primary key (<Attribute>);

DROP PRIMARY KEY Constraint:

alter table <tablename> drop constraint <constraint_name>;


*************************************************************************************

4) FOREIGN KEY CONSTRAINT

 A FOREIGN KEY is a key used to link two tables together.

 A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in
another table.

 The table containing the foreign key is called the child table, and the table containing the candidate
key is called the referenced or parent table.

For Example: Consider the following two tables


 The "PersonID" column in the "Orders" table points to the "PersonID" column in the "Persons" table.

 The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

 The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

 The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

 The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the table it points to.

FOREIGN KEY Constraint in Create Table:

create table Orders (


OrderID int primary key,
OrderNumber int not null,
PersonID int foreign key references Persons(PersonID)
);

FOREIGN KEY Constraint in Alter Table:

To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is already
created, use the following SQL:

i) alter table Orders add foreign key (PersonID) references Persons(PersonID);


ii) alter table Orders
add constraint FK_PersonOrder
foreign key (PersonID) references Persons(PersonID);

Drop a FOREIGN KEY Constraint:

alter table Orders


drop constraint FK_PersonOrder;

************************************************************************************
5) CHECK CONSTRAINT

 The CHECK constraint is used to limit the value range that can be placed in a column.

 If you define a CHECK constraint on a single column it allows only certain values for this column.

 If you define a CHECK constraint on a table it can limit the values in certain columns based on values
in other columns in the row.

CHECK Constraint in Create Table:

create table Persons (


ID int not null,
LastName varchar(255) not null,
FirstName varchar(255),
Age int check (Age>=18)
);

Adding Check Constraint on Multiple Columns

create table Persons (


ID int not null,
LastName varchar(255) not null,
FirstName varchar(255),
Age int,
City varchar(255),
constraint CHK_Person check (Age>=18 and City='Chennai')
);

CHECK Constraint in Alter Table:

alter table Persons add check (Age>=18);

Check Constraint on Multiple Columns

alter table Persons add constraint CHK_PersonAge check (Age>=18 and City='Chennai');

DROP a CHECK Constraint

alter table Persons drop constraint CHK_PersonAge;


*************************************************************************************

6) DEFAULT CONSTRAINT:

 The DEFAULT constraint is used to provide a default value for a column.

 The default value will be added to all new records IF no other value is specified.

DEFAULT Constraint in Create Table:

create table Persons (


ID int not null,
LastName varchar(255) not null,
FirstName varchar(255),
Age int,
City varchar(255) default 'Sandnes'
);

The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():

create table Orders (


ID int not null,
OrderNumber int not null,
OrderDate date default GETDATE()
);
DEFAULT Constraint in Alter Table:

alter table Persons modify City default 'Sandnes';

DROP DEFAULT Constraint:

alter table Persons alter column City drop default;

*************************************************************************************

INDEXES:

 The CREATE INDEX statement is used to create indexes in tables.

 Indexes are used to retrieve data from the database more quickly than otherwise. The users cannot see
the indexes, they are just used to speed up searches/queries.

CREATE INDEX Syntax

create index index_name ON table_name (column1, column2, ...);

CREATE UNIQUE INDEX Syntax


CREATE UNIQUE INDEX index_name ON table_name (column1, column2, ...);

DROP INDEX Statement

DROP INDEX index_name;

*************************************************************************************

SQL Clauses

GROUP BY Clause:
 SQL GROUP BY statement is used to arrange identical data into groups.

 The GROUP BY statement is used with the SQL SELECT statement.

 The GROUP BY statement follows the WHERE clause in a SELECT statement and precedes the
ORDER BY clause.

 The GROUP BY statement is used with aggregation function.

Syntax:

SELECT column FROM table_name WHERE conditions GROUP BY column ;

Example:

select companyname, count(*) from products group by companyname;


HAVING Clause:
 HAVING clause is used to specify a search condition for a group or an aggregate.

 Having is used in a GROUP BY clause. If you are not using GROUP BY clause then you can use
HAVING function like a WHERE clause.

Syntax:

SELECT column1, column2 FROM tablename


WHERE conditions GROUP BY column1, column2 HAVING condition;

Example:

select companyname, count(*) from products group by companyname having count(*)>2;

ORDER BY Clause:
 The ORDER BY clause sorts the result-set in ascending or descending order.

 It sorts the records in ascending order by default. DESC keyword is used to sort the records in
descending order.

Syntax:

SELECT column1, column2 FROM table_name WHERE condition ORDER BY column1, column2... ASC|DESC;

ASC: It is used to sort the result set in ascending order by expression.

DESC: It sorts the result set in descending order by expression.

Example: Sorting Results in Ascending Order

SELECT * FROM CUSTOMER ORDER BY NAME;

Example: Sorting Results in Descending Order

SELECT * FROM CUSTOMER ORDER BY NAME DESC;

*************************************************************************************
SQL Operators

Arithmetic Operators : +, -, *, /, %
Comparison Operators : =, !=, < >, >, <, >=, <=, !<, !>
Logical Operators : ALL, AND, ANY, BETWEEN, IN, NOT, OR, EXISTS, LIKE

SQL Operators Examples:

products(pid, productcode, name, price, quantity)

SELECT name, price FROM products WHERE price < 1.0;


SELECT name, quantity FROM products WHERE quantity <= 2000;
SELECT name, price FROM products WHERE productcode = 'P101';

LIKE and NOT LIKE


SELECT name, price FROM products WHERE name LIKE 'PENCIL%';
SELECT name, price FROM products WHERE name LIKE 'P__ %';

Logical Operators
SELECT * FROM products WHERE quantity >= 5000 AND name LIKE 'Pen %';
SELECT * FROM products WHERE quantity >= 5000 AND price < 1.24 AND name LIKE 'Pen %';
SELECT * FROM products WHERE NOT (quantity >= 5000 AND name LIKE 'Pen %');

IN, NOT IN
SELECT * FROM products WHERE name IN ('Pen Red', 'Pen Black');

BETWEEN, NOT BETWEEN


SELECT * FROM products WHERE (price BETWEEN 1.0 AND 2.0) AND (quantity BETWEEN 1000 AND 2000);

IS NULL, IS NOT NULL


SELECT * FROM products WHERE productcode IS NULL;
**************************************************************************************************

SQL ALIASES

 SQL aliases are used to give a table, or a column in a table, a temporary name.

Alias Column Syntax

SELECT column_name AS alias_name


FROM table_name;

Example:

SELECT CustomerID AS ID, CustomerName AS Customer


FROM Customers;

You might also like