You are on page 1of 109

Unit II

Relational Data Model and


Relational Database Constraints
What is Relational Model?

• RELATIONAL MODEL (RM) represents the


database as a collection of relations.
• A relation is nothing but a table of values.
• Every row in the table represents a collection of
related data values.
• These rows in the table denote a real-world
entity or relationship.
Relational Model Concepts

• Attribute: Each column in a Table. Attributes are the properties


which define a relation.
e.g., Student_Rollno, NAME,etc.

• Tables – In the Relational model the, relations are saved in the table
format. It is stored along with its entities. A table has two properties
rows and columns. Rows represent records and columns represent
attributes.

• Tuple – It is nothing but a single row of a table, which contains a


single record.

• Relation Schema: A relation schema represents the name of the


relation with its attributes.
• Degree: The total number of attributes which in the relation is called
the degree of the relation.

• Cardinality: Total number of rows present in the Table.

• Column: The column represents the set of values for a specific


attribute.

• Relation instance – Relation instance is a finite set of tuples in the


RDBMS system. Relation instances never have duplicate tuples.

• Relation key - Every row has one, two or multiple attributes, which is
called relation key.

• Attribute domain – Every attribute has some pre-defined value and


scope which is known as attribute domain
Relational Integrity constraints
• Relational Integrity constraints is referred to
conditions which must be present for a valid
relation. These integrity constraints are derived
from the rules in the mini-world that the
database represents.

There are many types of integrity constraints.


• Domain constraints
• Key constraints
• Referential integrity constraints
• Domain Constraints: 
These are attribute level constraints. An attribute
can only take values which lie inside the domain
range.
e.g; If a constrains AGE>0 is applied on STUDENT
relation, inserting negative value of AGE will result
in failure.
• Key Integrity: 
Every relation in the database should have atleast
one set of attributes which defines a tuple
uniquely. Those set of attributes is called key.

e.g.; ROLL_NO in STUDENT is a key. No two


students can have same roll number.

So a key has two properties:


• It should be unique for all tuples.
• It can’t have NULL values.
• Referential Integrity: 
When one attribute of a relation can only take
values from other attribute of same relation or
any other relation, it is called referential integrity.
Suppose let us have 2 relations.
SQL Commands and its Types
SQL commands are instructions. It is used to communicate with the
database. It is also used to perform specific tasks, functions, and
queries of data.
DDL (Data Definition Language)
• In SQL,  DDL  are the set of commands used to
define database schema. These commands are
use to change the structure of database objects.
• In simple words, DDL commands are mainly used
for creating or modifying a database/table
structure and schema.
– CREATE
– ALTER
– TRUNCATE
– DROP
CREATE Command: The  CREATE  command is used to create a new database
object. It can be used to create a new table, view, function, stored procedure, etc.
in the database.

Syntax to create a new table in the database:

CREATE TABLE Table_Name


(
Column_Name1 Data_Type (Size),
Column_Name2 Data_Type (Size),
……………..
Column_NameN Data_Type (Size)
);

Example:

CREATE TABLE Employee


(
    Id INT PRIMARY KEY,
    Name  VARCHAR(50),
    Salary DECIMAL(18, 2)
);
ALTER Command :The  ALTER  command in SQL is used to
add, modify, or delete, columns or constraints in an existing
table.
This command is used to change the structure of an
existing table in the database.

Add a new column in an existing table


Syntax to add a new column in an existing table:

ALTER TABLE Table_Name ADD New_Column_Name Data_Type (Size);

Example:
ALTER TABLE Employee ADD City VARCHAR(20)
Change data type and size of an existing column
Syntax to change the existing column datatype and size:

ALTER TABLE Table_Name ALTER COLUMN


Column_Name New_Data_Type (New_Size)

Example: The following Alter statement is used to


change the data type and size of an existing column
‘City’.

ALTER TABLE Employee ALTER COLUMN City VARCHAR


(100);
Delete existing column from a table:
Syntax to delete an existing column from a table:

ALTER TABLE Table_Name DROP COLUMN Column_Name;

Example: The following Alter statement is used to


drop the existing column ‘City’ from the table
employee.

ALTER TABLE Employee DROP COLUMN City;


Truncate Command
The  TRUNCATE  command is to delete all the records from a
table, but not the table itself. It doesn’t support the ‘where’
clause, that’s why we can’t delete a specific record.

Delete all the data from a table


Syntax to use the truncate command:

TRUNCATE TABLE Table_Name;

Example: The following TRUNCATE statement is used to


delete all the rows from a table.

TRUNCATE TABLE Employee;


DROP Command
The  DROP  command is used to remove an object from the
database.

If we use drop command on a table, the table including all the


records and constraints will be removed from the database.

Remove a table from the database


Syntax to use the drop command:

DROP TABLE Table_Name;

Example: The following DROP statement is used to delete the


‘EmployeeDetails’ table from the database.

DROP TABLE EmployeeDetails ;


DML (Data Manipulation Language)

• The  DML  commands in SQL Server are used to


manipulate or modify the data stored in the
database. These commands can be used to
insert, update, or delete the records from the
database.
– INSERT
– UPDATE
– DELETE
DCL (Data Control Language)
• The  DCL  commands mainly deal with the right, permissions,
and other security-related issues.
• Using DCL commands a user can be allowed to access the
information from a database.

• We can grant a user with various privileges on single or


multiple tables. These permissions can be applicable for a user
to use the commands
such as SELECT, INSERT, UPDATE, DELETE, REFERENCES, ALTER,
or ALL on a table.

• Following are the DCL Commands:


– GRANT
– REVOKE
GRANT Command In SQL Server
 GRANT  : Grant command in SQL server is used for granting a user access privileges or other
privileges to the database.

Grant privileges on a table


Syntax to use the GRANT command:

GRANT privileges ON object TO user;

For example, If we want to grant a user ‘john’ for the SELECT, INSERT, UPDATE, and DELETE
privileges on a table called ‘Employee’, we should run the following GRANT statement.

GRANT SELECT, INSERT, UPDATE, DELETE ON Employee TO john ;

Grant user to create any table:

GRANT CREATE ANY TABLE TO user.

Grant user to drop any table:

GRANT DROP ANY TABLE TO user.


REVOKE Command

  REVOKE  – Withdraws or take back some or all the user’s access privileges to
the database given by using the GRANT command.

Revoke privileges on a table


Syntax to use the Revoke command:

REVOKE privileges ON object FROM user;

Example to revoke the privileges SELECT, INSERT, UPDATE, and DELETE from a
user on a table ;

REVOKE SELECT, INSERT, UPDATE, DELETE ON Employee FROM john;

To take back privileges.

REVOKE CREATE, DROP TABLE FROM user.


TCL (Transaction Control Language)

• The  TCL  commands in SQL Server is used to


manage the transaction or the changes made by
DML statements like INSERT, UPDATE and
DELETE in a table.

• The following are the TCL commands:


– COMMIT
– ROLLBACK
– SAVEPOINT (SAVE TRANSACTION)
COMMIT command

• COMMIT command is used to permanently save any


transaction into the database.
• When we use any DML command
like INSERT, UPDATE or DELETE, the changes made by
these commands are not permanent, until the current
session is closed, the changes made by these
commands can be rolled back.
• To avoid that, we use the COMMIT command to mark
the changes as permanent.

Following is commit command's syntax,


• COMMIT;
ROLLBACK command
• This command restores the database to last
commited state. It is also used
with SAVEPOINT command to jump to a
savepoint in an ongoing transaction.

Following is rollback command's syntax,


• ROLLBACK TO savepoint_name;
SAVEPOINT command

• SAVEPOINT command is used to temporarily


save a transaction so that you can rollback to
that point whenever required.

Following is savepoint command's syntax,


• SAVEPOINT savepoint_name;
Student Table
id name

1 Abhi

2 Adam

4 Alex
Lets use some SQL queries on the table:

• INSERT INTO student VALUES(5, 'Rahul');


• COMMIT;

• UPDATE student SET name = 'Abhijit' WHERE id = '5';


• SAVEPOINT A;

• INSERT INTO student VALUES(6, 'Chris');


• SAVEPOINT B;

• INSERT INTO student VALUES(7, 'Bravo');


• SAVEPOINT C;

• SELECT * FROM student;


The resultant table :
id name

1 Abhi

2 Adam

4 Alex

5 Abhijit

6 Chris

7 Bravo
Now let's use the ROLLBACK command to roll
back the state of data to the savepoint B.

• ROLLBACK TO B;
• SELECT * FROM student;
Student table at savepoint B
id name

1 Abhi

2 Adam

4 Alex

5 Abhijit

6 Chris
• Now let's again use the ROLLBACK command to
roll back the state of data to the savepoint A

• ROLLBACK TO A;
• SELECT * FROM student;
Student table at savepoint A
id name

1 Abhi

2 Adam

4 Alex

5 Abhijit
Data Query Language
DQL is used to fetch the data from the database.
It uses only one command:
SELECT

SELECT: This is the same as the projection operation of relational


algebra. It is used to select the attribute based on the condition
described by WHERE clause.

Syntax:
SELECT expressions    
FROM TABLES    
WHERE conditions; 
 
For example:
SELECT emp_name  
FROM employee  
WHERE age > 20;  
Class Table
SQL queries:
• INSERT into CLASS VALUES (101, ‘Rahul);
• Commit;

• UPDATE CLASS SET NAME= ‘Tyler’ where id= 101


• SAVEPOINT A;

• INSERT INTO CLASS VALUES (102, ‘Zack’);


• Savepoint B;

• INSERT INTO CLASS VALUES (103, ‘Bruno’)


• Savepoint C;

• Select * from Class;


Result:
Now rollback to savepoint B

• Rollback to B;

• SELECT * from Class;


Class table at savepoint B
Now rollback to savepoint A

• rollback to A;

• SELECT * from class;


Class table at savepoint A
TEACHERS table:

CREATE TABLE TEACHERS (


   CODE INT NOT NULL,
   SUBJECT VARCHAR (15) NOT NULL,
   NAME VARCHAR (15) NOT NULL,     
   PRIMARY KEY (CODE)
);

• INSERT INTO TEACHERS VALUES (1, 'SELENIUM', 'TOM');

• INSERT INTO TEACHERS VALUES (2, 'UFT', 'SAM');

• INSERT INTO TEACHERS VALUES (3, 'JMETERE', 'TONK');

• COMMIT;

• SELECT * FROM TEACHERS;


Result:
Statement to implement of ROLLBACK WITH SAVEPOINT:

• INSERT INTO TEACHERS VALUES (4, 'CYPRESS', 'MICHEAL');


• SAVEPOINT s;

• INSERT INTO TEACHERS VALUES (5, 'PYTHON', 'STEVE');

• INSERT INTO TEACHERS VALUES (6, 'PYTEST', 'ARNOLD');


• ROLLBACK TO s;

• INSERT INTO TEACHERS VALUES (7, 'PROTRACTOR', 'FANNY');


• COMMIT;    

• SELECT * FROM TEACHERS;


Result
SQL - Data Types
• SQL Data Type is an attribute that specifies the
type of data of any object.
• Each column, variable and expression has a
related data type in SQL.
• We can use these data types while creating
your tables.
• We can choose a data type for a table column
based on our requirement.
A UNICODE character uses multiple bytes to store the data in the database.
Constraints in SQL
•Constraints are the rules that we can apply on the type of data in a table. That is, we can specify the
limit on the type of data that can be stored in a particular column in a table using constraints.

Constraints in SQL are:

•NOT NULL: This constraint tells that we cannot store a null value in a column. That is, if a column is
specified as NOT NULL then we will not be able to store null in this particular column any more.

•UNIQUE: This constraint when specified with a column, tells that all the values in the column must be
unique. That is, the values in any row of a column must not be repeated.

•PRIMARY KEY: A primary key is a field which can uniquely identify each row in a table. And this
constraint is used to specify a field in a table as primary key.

•FOREIGN KEY: A Foreign key is a field which can uniquely identify each row in a another table. And this
constraint is used to specify a field as Foreign key.

•CHECK: This constraint helps to validate the values of a column to meet a particular condition. That is, it
helps to ensure that the value stored in a column meets a specific condition.

•DEFAULT: This constraint specifies a default value for the column when no value is specified by the user.
• We can specify constraints at the time of creating the table
using CREATE TABLE statement.
• We can also specify the constraints after creating a table using
ALTER TABLE statement.

Syntax:
CREATE TABLE sample_table
( column1 data_type(size) constraint_name,
column2 data_type(size) constraint_name,
column3 data_type(size) constraint_name, .... );

sample_table: Name of the table to be created.


data_type: Type of data that can be stored in the field.
constraint_name: Name of the constraint.
for example- NOT NULL, UNIQUE, PRIMARY KEY etc.
Let us see each of the constraint with example:

NOT NULL

Example:

CREATE TABLE Student


(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
ADDRESS varchar(20)
);
UNIQUE

Example:

CREATE TABLE Student


(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20)
);
PRIMARY KEY

Example:

CREATE TABLE Student


(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20),
PRIMARY KEY(ID)
);
FOREIGN KEY

Example:

CREATE TABLE Orders


(
O_ID int NOT NULL,
ORDER_NO int NOT NULL,
C_ID int,
PRIMARY KEY (O_ID),
FOREIGN KEY (C_ID) REFERENCES Customers(C_ID)
);
CHECK

Example:

CREATE TABLE Student


(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int NOT NULL CHECK (AGE >= 18)
);
DEFAULT
Example:

CREATE TABLE Student


(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int DEFAULT 18
);
Schema Change Statement in SQL
Schema Change Statement in SQL, which can be
used to alter a schema by adding or dropping
tables, attributes, constraints, and other schema
elements.

1) DROP Command.
2) ALTER Command.
DROP Command:
The DROP command can be used to drop named
schema elements, such as tables, domains, or
constraints.

There are two drop behaviour options:


CASCADE and RESTRICT.

For example, to remove the COMPANY database


schema and all its tables, domains, and other
elements, the CASCADE option is used as follows:

DROP SCHEMA COMPANY CASCADE;


• If the RESTRICT option is chosen in place of CASCADE, the schema
is dropped only if it has no elements in it;
otherwise, the DROP command will not be executed.

• If a base relation within a schema is no longer needed, the relation


and its definition can be deleted by using the DROP TABLE
command.
DROP TABLE DEPENDENT CASCADE;

• With the CASCADE option, all such constraints, views, and other
elements that reference the table being dropped are also dropped
automatically from the schema, along with the table itself.

• The DROP TABLE command not only deletes all the records in the
table successful, but also removes the table definition from the
catalog
ALTER Command:
The definition of a base table or of other named schema
elements can be changed by using the ALTER command.

• The possible alter table actions:


1) Add
2) Drop a column (attribute)
3) Alter (or changing) a column definition

To Add a column Syntax:


Alter Table Add Column …..;

ALTER TABLE COMPANY.EMPLOYEE


ADD COLUMN Job VARCHAR(12);
• To drop a column, we must choose either CASCADE
or RESTRICT for drop behaviour.

Syntax:
Alter Table Drop Column .. cascade;

Ex:
ALTER TABLE COMPANY.EMPLOYEE DROP
COLUMN Address CASCADE;
It is also possible to alter a column definition by
dropping an existing default clause or by defining a
new default clause.

Syntax:
Alter Table Alter Column ….;

Ex:
ALTER TABLE COMPANY.DEPARTMENT
ALTER(modify) COLUMN Mgr_ssn Varchar(10);
View in SQL
• Views in SQL are kind of virtual tables.
• A view also has rows and columns as they are in a
real table in the database.
• We can create a view by selecting fields from one or
more tables present in the database.
• A View can either have all the rows of a table or
specific rows based on certain condition.
• We can create View using CREATE VIEW statement.
• A View can be created from a single table or
multiple tables.
Syntax:

CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE condition;

•  view_name: Name for the View


• table_name: Name of the table
• condition: Condition to select rows
– Marks
Creating View from a single table:
Query:

CREATE VIEW AgeDetail AS


SELECT NAME, AGE
FROM Marks
WHERE S_ID < 4;

To see the data in the View, we can query the view


in the same manner as we query a table.

• SELECT * FROM AgeDetail;


AgeDetail

Name Age
1 19
2 20
3 19
• Example:
Department
Dept_ID Stream Stud_id
1 CS 1
2 IT 1
3 ECE 2
4 ECE 9

• Create a view table to display the dept_id greater


than dept_id =2.
Create view stud_details as
Select stream, stud_id
From department
Where dept_id>2;
 
Select * from stud_details;

Stud_details

Stream Stud_id
ECE 2
ECE 9
Creating View from multiple tables:
• To create a View from multiple tables we can simply
include multiple tables in the SELECT statement.

Syntax :

CREATE VIEW view_name AS


SELECT table_name1.column1, table_name2.column3.....
FROM table_name1, table_name 2….
WHERE condition;

view_name: Name for the View


table_name: Name of the table
condition: Condition to select rows
Student

Marks
CREATE VIEW MarksView AS
SELECT Student.NAME, Student.ADDRESS, Marks.MARKS
FROM Student, Marks
WHERE Student.NAME = Marks.NAME;

Select * from MarksView;


Output:
MarksView
Deleting View
A view can be deleted using the Drop View
statement.

Syntax
DROP VIEW view_name;  

Example:
If we want to delete the View MarksView, we can
do this as:

DROP VIEW MarksView;  
- Create View containing name, item name and quantity from the following tables.

- Create View containing all the id details from the following tables.
Create view containing customer name with
corresponding customer’s account number
Joins in SQL
• An SQL join is a join operation in relational
algebra – combines columns from one or more
tables in a relational database.

• A JOIN is a means for combining columns from


two or more tables by using values common to
each.
Types of Join in SQL
Student
StudentCourse
• INNER JOIN: The INNER JOIN keyword selects all rows from
both the tables as long as the condition satisfies.
This keyword will create the result-set by combining all rows
from both the tables where the condition satisfies i.e value of
the common field will be same.

Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 INNER JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
• SELECT StudentCourse.COURSE_ID, Student.NAME,
Student.AGE
FROM Student INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
• LEFT JOIN: This join returns all the rows of the table on the left
side of the join and matching rows for the table on the right side
of join.
• The rows for which there is no matching row on right side, the
result-set will contain null.
• LEFT JOIN is also known as LEFT OUTER JOIN.

Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

• table1: First table.


• table2: Second table
• matching_column: Column common to both the tables.
• SELECT Student.NAME, StudentCourse.COURSE_ID
FROM Student LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
• RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns
all the rows of the table on the right side of the join and
matching rows for the table on the left side of join.
• The rows for which there is no matching row on left side, the
result-set will contain null.
• RIGHT JOIN is also known as RIGHT OUTER JOIN.

Syntax:
• SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

• table1: First table.


• table2: Second table
• matching_column: Column common to both the tables.
• SELECT Student.NAME, StudentCourse.COURSE_ID
FROM Student RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
• FULL JOIN: FULL JOIN creates the result-set by combining
result of both LEFT JOIN and RIGHT JOIN.
• The result-set will contain all the rows from both the
tables. The rows for which there is no matching, the result-
set wil contain NULL values.

Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 FULL JOIN table2
ON table1.matching_column = table2.matching_column;

• table1: First table.


• table2: Second table
• matching_column: Column common to both the tables.
• SELECT Student.NAME, StudentCourse.COURSE_ID
FROM Student FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Assertions
• An assertion is a statement in SQL that ensures a
certain condition will always exist in the database. 
• Assertions are like column and table constraints.
• However, assertions are checked only when
UPDATE or INSERT actions are performed against
the table.
Syntax –
CREATE ASSERTION [ assertion_name ]
CHECK ( [ condition ] );

CREATE TABLE sailors (sid int, sname varchar(20),


rating int, primary key(sid),
CHECK(rating >= 1 AND rating <=10)
CHECK((select count(s.sid) from sailors s) +
(select count(b.bid)from boats b)<100) );
• We can use Assertions when we know that the
given particular condition is always true.

• When the SQL condition is not met then there


are chances to an entire table or even Database
to get locked up.

• Assertions do not maintain any track of changes


made in table.

• Modern databases do not use Assertions.


Triggers
• Triggers are the SQL codes that are automatically
executed in response to certain events on a
particular table.

• These are used to maintain the integrity of the data. 

• The trigger can be executed when we run the


following statements:
– INSERT
– UPDATE
– DELETE
Syntax –
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
Example –
create trigger t1 before UPDATE on sailors
for each row
begin
if new.age>60 then
set new.age=old.age;
else
set new.age=new.age;
end if;
end;

In the above example we are creating trigger before update.


so, if the new age is greater than 60 we should not update
else we should update.
• We can use Triggers even for particular condition
may or may not be true.
• Triggers can catch errors if the condition of the
query is not true.
• Triggers maintain track of all changes occurred in
table.
• Triggers are very well used in modern databases.

You might also like