SQL2
SQL2
AP21111200002
BSc CS
DBMS Assignment-2
1. DATABASE CONSTRAINTS:
Integrity constraints:
Integrity constraints ensures that changes made to the database by authorized users do
not result in a loss of data consistency. Thus integrity constraints protects the
accidental damage to the database.
UNIQUE constraint:
The attribute which is enforced with this constraint is restricted to duplicate values.
That means no two tuples in the relation can be equal on all the listed attributes.
It can be NULL. That means attribute which is enforced with this attribute
accepts NULL values.
Syntax:
attribute_name data_type unique
Example:
Let us consider a student table with attributes roll_no,name,email,contact,dept_name
and implement the three constraints NOT NULL, UNIQUE, PRIMARY KEY on
different attributes and see the results. For referential integrity constraint, Let us
consider another table that is department table with attributes dept_name,
d_location,d_head as a parent table and student table as a child table.
Firstly parent table has to created- Department table has to be created.
Department table has the following attributes:
Attribute_name Data_type Constraint
d_name varchar(30) PRMARY KEY
d_location varcahr(50) NOT NULL
d_head varchar(50) NOT NULL
Compilation message:
Let us try to insert values into the table and learn about two constraints- NOT
NULL, PRIMARY KEY.
Compilation message:
insert into Department values("CSE","Admin 1 row(s) 0.125
3 8 19:05:55
Block","M.D.Khallel") affected sec
Compilation message:
insert into Department values("CS","Admin 1 row(s) 0.125
3 10 19:10:51
Block","A.K.Arjun") affected sec
insert into Department values("MECH","Admin 1 row(s) 0.078
3 11 19:10:51
Block2","Jhonas") affected sec
insert into Department values("CIVIL","Admin 1 row(s) 0.140
3 12 19:10:51
Block3","Suresh") affected sec
3. Let us try to violate the rules and see what happens. That is d_location attribute
should not accept NULL value. Let us supply NULL value to it and see what happens.
d_name : ECE, d_location : NULL, d_head : Lakshman
Compilation message:
insert into Department Error Code: 1062. Duplicate
0.000
0 14 19:21:17 values("CS","Admin entry 'CS' for key
sec
Block4","Lakshman") 'department.PRIMARY'
It shows an error. Because duplicate entry is made for dept_name which is a primary
key-Violating UNIQUE constraint on primary key.
Compilation message:
insert into Department Error Code: 1048.
0.000
0 15 19:31:35 values(NULL,"Admin Column 'd_name'
sec
Block4","Lakshman") cannot be null
It shows an error. Because NULL value is supplied made for dept_name which is a
primary key-Violating NOT NULL constraint on primary ley.
Let us create child table- Student table.
Student table has the following attributes:
Attribute_name Data_type Integrity constraint
roll_no varchar(15) PRIMARY KEY
s_name varchar(50) NOT NULL
email varchar(50) UNIQUE
contact varchar(10) NOT NULL
d_name-has to be same varchar(30)-has to be same FOREIGN KEY-
attribute_name as that in data_type and size as that reference from Department
Department table as it is a in Department table as it is table
foreign key a foreign key
Compilation message:
create table Student ( roll_no varchar(15), s_name
varchar(50) not null, e_mail varchar(50) unique,
0 row(s) 0.250
3 21 20:08:35 contact varchar(50) not null, d_name varchar(30),
affected sec
primary key(roll_no), foreign key(d_name) references
Department(d_name) )
Let us insert values into the table and learn about UNIQUE constraint and
FOREIGN KEY
1. roll_no : “AP21111200001”, s_name : “Kalyan Appala”, email:
“kalyan_a@srmap.edu.in”, contact: “9985751897”, d_name : “CSE”
roll_no : “AP21111200002”, s_name : “Bhramara Mutte”, email:
“Bhramara_m@srmap.edu.in”, contact: “7097236199”, d_name : “CSE”
roll_no : “AP21110050001”, s_name : “Abhiram K”, email:
“abhiram_k@srmap.edu.in”, contact: “9985712345”, d_name : “CIVIL”
roll_no : “AP21110050009”, s_name : “Inaya Sulthan”, email:
“inaya_sulthan@srmap.edu.in”, contact: “8917539459”, d_name : “MECH”
Compilation message:
1
0.10
2 21:06:2 insert into Student values("AP21111200001","Kalyan row(s)
3 9
2 5 Appala","kalyan_a@srmap.edu.in","9985751897","CSE") affecte
sec
d
1
insert into Student values("AP21111200002","Bhramara 0.18
2 21:07:1 row(s)
3 Mutte","bhramara_m@srmap.edu.in","7097236199","CSE 8
3 4 affecte
") sec
d
1
0.04
2 21:10:4 insert into Student values("AP21110050001","Abhiram row(s)
3 7
4 1 K","abhiram_k@srmap.edu.in","9985712345","CIVIL") affecte
sec
d
1
insert into Student values("AP21110050009","Inaya 0.04
2 21:10:4 row(s)
3 Sulthan","inaya_sulthan@srmap.edu.in","8917539459","M 7
5 1 affecte
ECH") sec
d
2. Let us try to violate the rules and see what happens. email s a unique attribute that
is it should not allow duplicate values.Let us try to supply duplicate value and see
what happens.
roll_no : “AP21110040002”, s_name : “Aishwarya I”, email:
“inaya_sulthan@srmap.edu.in”, contact: “9441127117”, d_name : “CS”
Compilation message:
0 2 21:20: insert into Student Error Code: 1062. 0.09
6 41 values("AP21110040002","Aishwarya Duplicate entry 4
I","inaya_sulthan@srmap.edu.in","9441127 'inaya_sulthan@srmap. sec
117","CS") edu.in' for key
'student.e_mail'
It shows an error as duplicate entry is made for email which is enforced with
UNIQUE constraint.
Parent table is known as Referenced table and the child table is known as Referencing
table. d_name is a foreign key of the Student table which is referring to the primary
key of the Department table. Referential integrity constraint ensures data consistency.
We could not enter d_name in the Student table that are not in d_name of the
Department table as d_name is a foreign in the Student table that is referring to the
d_name of the Department table which acts as a foreign key. This is known as
referential integrity. Let us try to violate this and see what happens.
Compilation message:
Error Code: 1452.
Cannot add or
update a child row:
a foreign key
constraint fails
insert into Student (`university`.`stude
0.11
2 21:41:3 values("AP21110040002","Aishwarya nt`,
0 0
7 2 I","aishwarya_i@srmap.edu.in","9441127117" CONSTRAINT
sec
,"EIE") `student_ibfk_1`
FOREIGN KEY
(`d_name`)
REFERENCES
`department`
(`d_name`))
This shows an error because d_name “EIE” is not present in the d_name of the
Department table as d_name in the Student table is enforced with FOREIGN KEY
constraint.
2. RELATIONAL ALGEBRA:
Project
Select
Union
Set Intersection
Set Difference
Division
Cartesian product
Rename
Join
SQL is also a procedural query language and is derived from Relational algebra. Let
us implement all these operations in SQL.
It is a unary operation as it takes only one relation as input and produces a resultant
relation as an output. The project SQL operation allows users of the relational model
to retrieve column-specific data from a table. Suppose , there are nine different
columns namely attribute1,attribute2,…. in a table but you only need the attribut1 and
the attribute5 for each individual in the table, you would use a project operation to
retrieve this data.
Syntax:
select attribute_name(s) from table_name
select attribute1,attribute5 from table_name;
Compilation message:
select s_name,d_name from Student 4 row(s) 0.000 sec /
3 29 22:06:29
LIMIT 0, 1000 returned 0.000 sec
2) Select: (works on rows)
It is a unary operation as it takes only one relation as input and produces a resultant
relation as an output. The selection operation targets records (rows), or specific
entities in a table. Entire record gets displayed.
Syntax:
select * from table_name;
This particular statement displays all the data in the table. If we want to display
particular student record then where clause has to be used.
select * from table_name where attribute= “value”;
Query: Find out the information of the student whose name is “Bhramara Mutte”.
Compilation message:
select * from Student where s_name 1 row(s) 0.000 sec /
3 30 22:18:30
="Bhramara Mutte" LIMIT 0, 1000 returned 0.000 sec
3) Union: It is a binary operation which takes two relation as a input and produces a
resultant relation as an output.
The UNION operator is used to combine the result-set of two or
more SELECT statements.
Every SELECT statement within UNION must have the same number of
columns
The columns must also have similar data types
The columns in every SELECT statement must also be in the same order
Syntax:
select column_name(s) from table1 union select column_name(s) from table2;
Consider two tables ece and eie with the following attributes roll,name,contact.
Query: Find out the student names those who belong to both departments.
Compilation message:
select name from ece union select 6 row(s) 0.000 sec / 0.000
3 47 22:44:57
name from eie returned sec
4) Set Difference: It is a binary operation which takes two relation as a input and
produces a resultant relation as an output. It allows us to find out tuples that are in one
relation but not in another relation. MINUS keyword is used to perform this
operation. The Minus Operator in SQL is used with two SELECT statements. The
MINUS operator is used to subtract the result set obtained by first SELECT query
from the result set obtained by second SELECT query. In simple words, we can say
that MINUS operator will return only those rows which are unique in only first
SELECT query and not those rows which are common to both first and second
SELECT queries. EXCEPT operator can also be used in some servers as they do not
accept minus operator.
Syntax:
select attribute_name(s) from table1 minus select attribute_name(s) from table2;
Attributes selected from both the statement should consists of same type of data.
No of attributes selected from table1 should be same as the table2 and has to be
of the same order.
table1 - table2 != table2 - table1
Minus operator do not work on MYSQL workbench. But we can perform Set
difference using left join operation. Let us learn completely the about JOIN
operation later. As of now let us just remember the syntax to perform set
difference operation using left join.
Syntax:
SELECT
attribute_name(s)
FROM
table1
LEFT JOIN table2
ON join_predicate
WHERE
table2.column_name IS NULL;
(or)
SELECT
attribute_name(s)
FROM
table1
LEFT JOIN table2 using(common_attribute)
WHERE
table2.column_name IS NULL;
MYSQL :
select customer_name from depositor
LEFT JOIN borrower using (customer_name)
where borrower.customer_name is NULL;
Compilation message:
0.000
select customer_name from depositor LEFT JOIN
4 row(s) sec /
3 7 21:11:32 borrower using (customer_name) where
returned 0.000
borrower.customer_name is NULL LIMIT 0, 1000
sec
5) Set Intersection: It is a binary operation which takes two relation as a input and
produces a resultant relation as an output. It is used to retrieve the common values
from both the relations. INTERSECT keyword is used to perform this operation.The
INTERSECT keyword is used with two select statements.
Every SELECT statement within INTERSECT must have the same number of
columns
The columns must also have similar data types
The columns in every SELECT statement must also be in the same order
Syntax:
select column_name(s) from table1 intersect select column_name(s) from table2;
But INTERSECT operator does not work on MYSQL workbench. But we can
perform INTERSECT using inner join operation. Let us learn completely the
about JOIN operation later. As of now let us just remember the syntax to perform
set difference operation using inner join.
Syntax:
SELECT DISTINCT column_list FROM table_name1
INNER JOIN table_name2 USING(join_condition);
DISTINCT keyword is used to eliminate duplicate values.
Query: Find out all the customers who have both account and loan.
Using Intersect:
select customer_name from borrower intersect select customer_name from borrower;
IN MYSQL:
select distinct customer_name from depositor
INNER JOIN borrower using(customer_name);
Compilation message:
select distinct customer_name from depositor 0.000 sec
3 row(s)
3 17 22:19:41 INNER JOIN borrower using(customer_name) / 0.000
returned
LIMIT 0, 1000 sec
6) Division: The division operation is suited to those queries that include the phrase
“for all”. When you wish to identify the entities that are interacting with every
other entity of a group of entities of various types, then division is necessary. But
it is not possible to directly divide two relations T1, T2 as T1 divides T2. This
division operation involve multiple operations.
Example queries that require division operation:
Which person has account in all the banks of a particular city?
Which students have taken all the courses required to graduate?
Query: Find out all the customers who have an account at all the branch located in”
Brookyn”
Since there is a presence of phrase “at all”, we need to perform division operation.
The division operation involves intermediate queries called as sub queries. On the
result of these sub queries, we perform division operation. This division operation can
be performed using advanced aggregate functions and join operation. Let us see how
this works on the above query.
The result of the sub-query1 has to be stored in a new relation. Without simply
displaying the resultant relation, we store this relation as a new relation using the
following syntax: (creating an intermediate table)
create table resultant_table_name
select column_name from table_name where condition;
Compilation message:
create table r1 select branch_name 2 row(s) affected
0.218
3 53 16:12:54 from branch where Records: 2 Duplicates:
sec
branch_city="Brookyn" 0 Warnings: 0
Resultant r1 relation:
select * from r1;
Sub-Query2: Find out all the customer_name, branch_name for which the customer
has an account at a branch.
Compilation message:
7 row(s)
create table r2 select affected
depositor.customer_name,account.branch_name Records: 0.719
3 43 16:01:48
from depositor natural join account where 7 Duplicates: sec
account.account_no=depositor.a_no 0 Warnings:
0
Resultant r2 relation:
select * from r2;
Now we have to find out all the customer who appears in r2 with every branch in r1.
This operation which provide those customer is called as division operation.
Equivalent to performing r2/r1
This operation can be achieved by using group by clause, having clause, join
operation and aggregate function ‘count’.
Given two relations (tables): R(x,y) , S(y).
R and S: tables
x and y: column of R
y: column of S
R(x,y) div S(y) means gives all distinct values of x from R that are associated with
all values of y in S.
Syntax:
SELECT distinct R.column_name from R
JOIN S ON R.column_name=S.column_name
GROUP BY S.column_name
HAVING COUNT(*)=(
SELECT COUNT(*) from R
WHERE R.column_name=S,column_name
)
Compilation message:
Syntax:
select attribute_name(s) from table1 cross join table2;
8) Join: When the required data is available in more than one relation, then there is
a need to perform join operation. Join operation is same as performing Cartesian
product with condition. Join clause is used to combine rows from two or more tables
based on a common field between them. There are different types of joins such as
natural join, cross join, outer join, inner join.
Condition:
To perform join operation between two relations, there has to be a common attribute
between two relations.
Compilation message:
0.000
select customer_name,depositor.a_no,borrower.l_no 3 row(s) sec /
3 24 22:07:50
from depositor natural join borrower LIMIT 0, 1000 returned 0.000
sec
Inner Join: The inner join is used to select all matching rows or columns in both
tables or as ling as the defined condition is valid. The inner join is helpful in
performing intersection operation in MYSQL as MYSQL do not support intersect
keyword.
Syntax:
select column_name(s)
from table1
INNER JOIN table2
on table1.matching_column=table2.matching_column;
Cross Join: Also, known as Cartesian join. This join is helpful in performing
Cartesian product.
Syntax:
select attribute_name(s) from table1 cross join table2;
*Examples for Inner join and Cross join cane be referred from Set Intersection and
Cartesian product respectively.
Outer Join: This is the extension of join operation which is used to include the
missing values of the relation. There are three types of Outer Joins. They are:
Left Outer Join
Right Outer Join
Full outer Join
Performming the three operations( Left join, Right join, Full join) on the above
relations and finding out the results.
Left Outer Join: Also, known as Outer join. The left join is used to retrieve all
records from the left table(table1) and the matched rows or columns from right
table(table2). If both tables do not contain any matched rows or columns, it returns the
NULL.
Left join is also used to perform Set Difference in MYSQL as MYSQL do not support
minus and except all keywords.
Syntax:
select column_name(s)
from table1
LEFT JOIN table2
on table1.matching_column=table2.matching_column;
(or)
select column_name(s)
from table1
LEFT JOIN table2 using(common_attribute);
Compilation message:
0.000
select customer_name,depositor.a_no,borrower.l_no
7 row(s) sec /
3 12 21:45:48 from depositor LEFT JOIN borrower using
returned 0.000
(customer_name) LIMIT 0, 1000
sec
Right Outer Join: Also, known as Right join. The Right join returns all the values
from the rows of right table. It also includes the matched values from left table but if
there is no matching in both tables, it returns NULL.
Syntax:
select column_name(s)
from table1
RIGHT JOIN table2
on table1.matching_column=table2.matching_column;
(or)
select column_name(s)
from table1
RIGHT JOIN table2 using(common_attribute);
select column_name(s)
from table1
LEFT JOIN table2 using(common_attribute);
Compilation message:
0.000
select customer_name,depositor.a_no,borrower.l_no
8 row(s) sec /
3 13 21:54:22 from depositor RIGHT JOIN borrower using
returned 0.000
(customer_name) LIMIT 0, 1000
sec
Full Outer Join: Also, known as Full Join. Full join creates the result-set by by
combining results of both Left join and Right join.The joined tables return all records
from both the tables and if no matches are found in the table, it places NULL.
Syntax:
select column_name(s)
from table1
FULL JOIN table2
on table1.matching_column=table2.matching_column;
(or)
select column_name(s)
from table1
LEFT JOIN table2 using(common_attribute)
UNION
select column_name(s)
from table1
RIGHT JOIN table2 using(common_attribute)
Compilation message:
select customer_name,depositor.a_no,borrower.l_no
from depositor LEFT JOIN borrower 0.000
12
using(customer_name) UNION select sec /
3 21 22:00:40 row(s)
customer_name,depositor.a_no,borrower.l_no from 0.000
returned
depositor RIGHT JOIN borrower sec
using(customer_name)
9) Rename:
Sometimes, there is a need to change the name of a table according to the flexibility.
This can be achieved by using Rename in SQL. Not only the table names can be
renamed, column names can also be renamed.
Syntax:
alter table old_table_name rename to new_table_name;
Compilation message:
3 3 11:16:01 alter table emp rename to employee_details 0 row(s) affected 0.156 sec
3. VIEWS:
These are virtual tables in the database. View is the result set of a stored query. They
do not have any physical existence in the memory.We define a view in SQL by using
the “create view” command. To define a view, we must give the view a name and
must state the query that computes the view. There are two types of views- Read-only
and Up-datable views.
Up-datable view: Modification to the view is allowed and it reflects in the original
table too. Only the DML commands insert,update,delete are allowed to work on
views. DDL commands do not work on up-datable views.
Rules to write up-datable views:
Built on only one table.(only data from a single relation is acceptable)
No GROUP BY clause
No HAVING clause
No aggregate functions
No calculated columns
No UNION, INTERSECTION or SET DIFFERENCE
No SELECT DISTINCT clause
View must contain a primary key of the table.
Materialized views: Certain database systems allow view relations to be stored, but
they make sure that actual relations used in the view definition change, the view is
kept up-to-data. Such views are called as materialized views.
Advantages of View:
To restrict data access
To provide data independence
To make complex queries easy
To present different views on the same data.
Syntax:
create view name as <query expression>;
where <query expression> is any legal query expression.
Example:
Creating a view named “CSE” from table student containing information of all the
students who belong to department CSE
Compilation message:
create view cse as select * from student where 0 row(s) 0.062
3 2 10:04:48
d_name="CSE" affected sec
Accessing view:
select column_name(s) from view_name;
select * from cse;
Compilation message:
3 3 10:06:33 select * from cse LIMIT 0, 1000 5 row(s) returned 0.015 sec / 0.000 sec
This is an up-datable because the data is from a single relation ‘student’, we can
modify the values in the view.
Syntax:
update view_name set attribute=”new value” where key_attribute=”value”;
Compilation message:
1 row(s) affected Rows
update cse set contact="7097445596" 0.281
3 4 10:13:27 matched: 1 Changed:
where roll_no="AP21111200002" sec
1 Warnings: 0
Updated view:
Compilation message:
3 1 10:58:02 drop view cse 0 row(s) affected 0.140 sec