Unit 2
Unit 2
Relational Model was proposed by E.F. Codd to model data in the form of
relations or tables. After designing the conceptual model of Database using
ER diagram, we need to convert the conceptual model in the relational model
which can be implemented using any RDBMS languages like Oracle SQL,
MySQL etc. So we will see what Relational Model is.
What is Relational Model?
Relational Model represents how data is stored in Relational Databases. A
relational database stores data in the form of relations (tables). Consider a
relation STUDENT with attributes ROLL_NO, NAME, ADDRESS, PHONE
and AGE shown in Table 1.
STUDENT
ROLL_NO NAME ADDRESS PHONE AGE
4 SURESH DELHI 18
IMPORTANT TERMINOLOGIES
• Attribute: Attributes are the properties that define a relation.
e.g.; ROLL_NO, NAME
• Relation Schema: A relation schema represents name of the
relation with its attributes. e.g.; STUDENT (ROLL_NO, NAME,
ADDRESS, PHONE and AGE) is relation schema for STUDENT. If
a schema has more than 1 relation, it is called Relational Schema.
• Tuple: Each row in the relation is known as tuple. The above
relation contains 4 tuples, one of which is shown as:
1 RAM DELHI 9455123451 18
4 SURESH DELHI 18 IT
BRANCH
BRANCH_CODE BRANCH_NAME
CS COMPUTER SCIENCE
IT INFORMATION TECHNOLOGY
CV CIVIL ENGINEERING
BRANCH_CODE of STUDENT can only take the values which are present in
BRANCH_CODE of BRANCH which is called referential integrity constraint.
The relation which is referencing to other relation is called REFERENCING
RELATION (STUDENT in this case) and the relation to which other relations
refer is called REFERENCED RELATION (BRANCH in this case).
ANOMALIES
An anomaly is an irregularity, or something which deviates from the expected
or normal state. When designing databases, we identify three types of
anomalies: Insert, Update and Delete.
Insertion Anomaly in Referencing Relation:
We can’t insert a row in REFERENCING RELATION if referencing attribute’s
value is not present in referenced attribute value. e.g.; Insertion of a student
with BRANCH_CODE ‘ME’ in STUDENT relation will result in error because
‘ME’ is not present in BRANCH_CODE of BRANCH.
Deletion/ Updation Anomaly in Referenced Relation:
We can’t delete or update a row from REFERENCED RELATION if value of
REFERENCED ATTRIBUTE is used in value of REFERENCING
ATTRIBUTE. e.g; if we try to delete tuple from BRANCH having
BRANCH_CODE ‘CS’, it will result in error because ‘CS’ is referenced by
BRANCH_CODE of STUDENT, but if we try to delete the row from BRANCH
with BRANCH_CODE CV, it will be deleted as the value is not been used by
referencing relation. It can be handled by following method:
ON DELETE CASCADE: It will delete the tuples from REFERENCING
RELATION if value used by REFERENCING ATTRIBUTE is deleted from
REFERENCED RELATION. e.g;, if we delete a row from BRANCH with
BRANCH_CODE ‘CS’, the rows in STUDENT relation with BRANCH_CODE
CS (ROLL_NO 1 and 2 in this case) will be deleted.
ON UPDATE CASCADE: It will update the REFERENCING ATTRIBUTE in
REFERENCING RELATION if attribute value used by REFERENCING
ATTRIBUTE is updated in REFERENCED RELATION. e.g;, if we update a
row from BRANCH with BRANCH_CODE ‘CS’ to ‘CSE’, the rows in
STUDENT relation with BRANCH_CODE CS (ROLL_NO 1 and 2 in this
case) will be updated with BRANCH_CODE ‘CSE’.
SUPER KEYS:
Any set of attributes that allows us to identify unique rows (tuples) in a given
relation are known as super keys. Out of these super keys we can always
choose a proper subset among these which can be used as a primary key.
Such keys are known as Candidate keys. If there is a combination of two or
more attributes which is being used as the primary key then we call it as a
Composite key.
Introduction of Relational Algebra in
DBMS
Relational Algebra is procedural query language, which takes Relation as
input and generate relation as output. Relational algebra mainly provides
theoretical foundation for relational databases and SQL.
Operators in Relational Algebra
Projection (π)
Projection is used to project required column data from a relation.
Example :
R
(A B C)
----------
1 2 4
2 2 3
3 2 3
4 3 4
π (BC)
B C
-----
2 4
2 3
3 4
Note: By Default projection removes duplicate data.
Selection (σ)
Selection is used to select required tuples of the relations.
for the above relation
σ (c>3)R
will select the tuples which have c more than 3.
Note: selection operator only selects the required tuples but does not display
them. For displaying, data projection operator is used.
For the above selected tuples, to display we need to use projection also.
π (σ (c>3)R ) will show following tuples.
A B C
-------
1 2 4
4 3 4
Union (U)
Union operation in relational algebra is same as union operation in set
theory, only constraint is for union of two relation both relation must have
same set of Attributes.
Rename (ρ)
Rename is a unary operation used for renaming attributes of a relation.
ρ (a/b)R will rename the attribute ‘b’ of relation by ‘a’.
A X B
Name Age Sex Id Course
---------------------------------
Ram 14 M 1 DS
Ram 14 M 2 DBMS
Sona 15 F 1 DS
Sona 15 F 2 DBMS
Kim 20 M 1 DS
Kim 20 M 2 DBMS
Note: if A has ‘n’ tuples and B has ‘m’ tuples then A X B will have ‘n*m’
tuples.
Emp Dep
(Name Id Dept_name ) (Dept_name Manager)
------------------------ ---------------------
A 120 IT Sale Y
B 125 HR Prod Z
C 110 Sale IT A
D 111 IT
Emp ⋈ Dep
Conditional Join
Conditional join works similar to natural join. In natural join, by default
condition is equal between common attribute while in conditional join we can
specify the any condition such as greater than, less than, not equal
Let us see below example
R S
(ID Sex Marks) (ID Sex Marks)
------------------ --------------------
1 F 45 10 M 20
2 F 55 11 M 22
3 F 60 12 M 59
Join between R And S with condition R.marks >= S.marks
ROLL_NO SPORTS
1 Badminton
2 Cricket
2 Badminton
4 Badminton
Table 2: EMPLOYEE
EMP_NO NAME ADDRESS PHONE AGE
Table 3: STUDENT
ROLL_NO NAME ADDRESS PHONE AGE
Selection operator (σ): Selection operator is used to select tuples from a relation
based on some condition. Syntax:
σ (Cond)(Relation Name)
Extract students whose age is greater than 18 from STUDENT relation given in
Table 3
σ (AGE>18)(STUDENT)
RESULT:
ROLL_NO NAME ADDRESS PHONE AGE
ROLL_NO NAME
1 RAM
2 RAMESH
3 SUJIT
4 SURESH
Note: If resultant relation after projection has duplicate rows, it will be removed.
For Example: ∏(ADDRESS)(STUDENT) will remove one duplicate row with value
DELHI and return three rows.
Cross Product(X): Cross product is used to join two relations. For every row of
Relation1, each row of Relation2 is concatenated. If Relation1 has m tuples and
and Relation2 has n tuples, cross product of Relation1 and Relation2 will have m
X n tuples. Syntax:
Relation1 X Relation2
To apply Cross Product on STUDENT relation given in Table 1 and
STUDENT_SPORTS relation given in Table 2,
STUDENT X STUDENT_SPORTS
RESULT:
ROLL_N ADDRES AG ROLL_N
O NAME S PHONE E O SPORTS
945512345 Badminto
1 RAM DELHI 1 18 1 n
945512345
1 RAM DELHI 1 18 2 Cricket
945512345 Badminto
1 RAM DELHI 1 18 2 n
945512345 Badminto
1 RAM DELHI 1 18 4 n
915625313
3 SUJIT ROHTAK 1 20 2 Cricket
915625313 Badminto
3 SUJIT ROHTAK 1 20 2 n
915625313 Badminto
3 SUJIT ROHTAK 1 20 4 n
SURES 915676897
4 H DELHI 1 18 2 Cricket
Union (U): Union on two relations R1 and R2 can only be computed if R1 and R2
are union compatible (These two relation should have same number of
attributes and corresponding attributes in two relations have same domain) .
Union operator when applied on two relations R1 and R2 will give a relation with
tuples which are either in R1 or in R2. The tuples which are in both R1 and R2
will appear only once in result relation. Syntax:
Relation1 U Relation2
Find person who are either student or employee, we can use Union operator
like:
STUDENT U EMPLOYEE
RESULT:
ROLL_NO NAME ADDRESS PHONE AGE
Minus (-): Minus on two relations R1 and R2 can only be computed if R1 and R2
are union compatible. Minus operator when applied on two relations as R1-R2
will give a relation with tuples which are in R1 but not in R2. Syntax:
Relation1 - Relation2
Find person who are student but not employee, we can use minus operator like:
STUDENT - EMPLOYEE
RESULT:
ROLL_NO NAME ADDRESS PHONE AGE
Relational Calculus
o Relational calculus is a non-procedural query language. In the non-procedural query
language, the user is concerned with the details of how to obtain the end results.
o The relational calculus tells what to do but never explains how to do.
Types of Relational calculus:
P(t) may have various conditions logically combined with OR (∨), AND (∧),
NOT(¬).
It also uses quantifiers:
∃ t ∈ r (Q(t)) = ”there exists” a tuple in t in relation r such that predicate Q(t)
is true.
∀ t ∈ r (Q(t)) = Q(t) is true “for all” tuples in relation r.
Example:
Table-1: Customer
Customer name Street City
Saurabh A7 Patiala
Mehak B6 Jalandhar
Sumiti D9 Ludhiana
Ria A5 Patiala
Table-2: Branch
Branch name Branch city
ABC Patiala
DEF Ludhiana
GHI Jalandhar
Table-3: Account
Account number Branch name Balance
Table-4: Loan
Loan number Branch name Amount
Table-5: Borrower
Customer name Loan number
Saurabh L33
Mehak L49
Ria L98
Table-6: Depositor
Customer name Account number
Saurabh 1111
Mehak 1113
Sumiti 1114
Queries-1: Find the loan number, branch, amount of loans of greater than or
equal to 10000 amount.
Loan number
L33
L35
L98
Queries-3: Find the names of all customers who have a loan and an account
at the bank.
{t | ∃ s ∈ borrower( t[customer-name] = s[customer-name])
∧ ∃ u ∈ depositor( t[customer-name] = u[customer-name])}
Resulting relation:
Customer name
Saurabh
Mehak
Queries-4: Find the names of all customers having a loan at the “ABC”
branch.
{t | ∃ s ∈ borrower(t[customer-name] = s[customer-name]
∧ ∃ u ∈ loan(u[branch-name] = “ABC” ∧ u[loan-number] = s[loan-
number]))}
Resulting relation:
Customer name
Saurabh
Table-1: Customer
Customer name Street City
Table-2: Loan
Loan number Branch name Amount
L10 Sub 90
L08 Main 60
Table-3: Borrower
Customer name Loan number
Ritu L01
Debomit L08
Customer name Loan number
Soumya L03
Query-1: Find the loan number, branch, amount of loans of greater than or
equal to 100 amount.
{≺l, b, a≻ | ≺l, b, a≻ ∈ loan ∧ (a ≥ 100)}
Resulting relation:
Query-2: Find the loan number for each loan of an amount greater or equal
to 150.
{≺l≻ | ∃ b, a (≺l, b, a≻ ∈ loan ∧ (a ≥ 150)}
Resulting relation:
Loan number
L01
L03
Query-3: Find the names of all customers having a loan at the “Main” branch
and find the loan amount .
{≺c, a≻ | ∃ l (≺c, l≻ ∈ borrower ∧ ∃ b (≺l, b, a≻ ∈ loan ∧ (b =
“Main”)))}
Resulting relation:
Ritu 200
Debomit 60
Soumya 150
Note:
The domain variables those will be in resulting relation must appear before |
within ≺ and ≻ and all the domain variables must appear in which order they
are in original relation or table.
Difference between Tuple Relational
Calculus (TRC) and Domain Relational
Calculus (DRC)
1. Tuple Relational Calculus (TRC) :
A tuple relational calculus is a non procedural query language which
specifies to select the tuples in a relation. It can select the tuples with range
of values or tuples for certain attribute values etc. The resulting relation can
have one or more tuples.
Notation :
{T | P (T)} or {T | Condition (T)}
-where T is resulting tuples and P(T) is a condition used to fetch T.
Example :
In TRS, the variables represent the tuples In DRS, the variables represent the value drawn
from specified relation. from specified domain.
A tuple is a single element of relation.In A domain is equivalent to column data type and
database term, it is a row. any constraints on value of data.
Tuple Relational Calculus (TRC) Domain Relational Calculus (DRC)
In this filtering variable uses tuple of In this filtering is done based on the domain of
relation. attributes.
Notation : Notation :
{T | P (T)} or {T | Condition (T)} { a1, a2, a3, …, an | P (a1, a2, a3, …, an)}
Example :
{T | EMPLOYEE (T) AND T.DEPT_ID Example :
= 10} { | < EMPLOYEE > DEPT_ID = 10 }
STUDENT
ROLL_NO NAME ADDRESS PHONE AGE
TABLE 1
These are some important terminologies that are used in terms of relation.
Attribute: Attributes are the properties that define a relation.
e.g.; ROLL_NO, NAME etc.
Tuple: Each row in the relation is known as tuple. The above relation
contains 4 tuples, one of which is shown as:
1 RAM DELHI 9455123451 18
ROLL_NO
ROLL_NO NAME
1 RAM
2 RAMESH
3 SUJIT
4 SURESH
ROLL_NO NAME
3 SUJIT
4 SURESH
ADDRESS
DELHI
GURGAON
ROHTAK
If DISTINCT is not used, DELHI will be repeated twice in result set. Before
understanding GROUP BY and HAVING, we need to understand
aggregations functions in SQL.
AGGRATION FUNCTIONS: Aggregation functions are used to perform
mathematical operations on data values of a relation. Some of the common
aggregation functions used in SQL are:
• COUNT: Count function is used to count the number of rows in a
relation. e.g;
SELECT COUNT (PHONE) FROM STUDENT;
COUNT(PHONE)
4
74
In the same way, MIN, MAX and AVG can be used. As we have seen
above, all aggregation functions return only 1 row.
AVERAGE: It gives the average values of the tupples. It is also defined as
sum divided by count values.
Syntax: AVG (attribute name )
OR
Syntax:SUM(attributename)/COUNT(attributename)
The above mentioned syntax also retrieves the average value of tupples.
MAXIMUM:It extracts the maximum value among the set of tupples.
Syntax:MAX(attributename)
MINIMUM:It extracts the minimum value amongst the set of all the tupples.
Syntax:MIN(attributename)
GROUP BY: Group by is used to group the tuples of a relation based on an
attribute or group of attribute. It is always combined with aggregation function
which is computed on group. e.g.;
SELECT ADDRESS, SUM(AGE) FROM STUDENT
GROUP BY (ADDRESS);
In this query, SUM(AGE) will be computed but not for entire table but for
each address. i.e.; sum of AGE for address DELHI(18+18=36) and similarly
for other address as well. The output is:
ADDRESS SUM(AGE)
DELHI 36
GURGAON 18
ROHTAK 20
If we try to execute the query given below, it will result in error because
although we have computed SUM(AGE) for each address, there are more
than 1 ROLL_NO for each address we have grouped. So it can’t be
displayed in result set. We need to use aggregate functions on columns after
SELECT statement to make sense of the resulting set whenever we are
using GROUP BY.
SELECT ROLL_NO, ADDRESS, SUM(AGE) FROM STUDENT
GROUP BY (ADDRESS);
NOTE: An attribute which is not a part of GROUP BY clause can’t be used
for selection. Any attribute which is part of GROUP BY CLAUSE can be used
for selection but it is not mandatory. But we could use attributes which are
not a part of the GROUP BY clause in an aggregrate function.
Basic Syntax:
2 RAMESH 18
3 SUJIT 20
4 SURESH 18
SELECT *
FROM students;
OR
SELECT *
FROM students
where due_fees <=20000;
2. INSERT Command –
This command is used to enter the information or values into a row.
We can connect one or more records to a single table within a
repository using this instruction. This is often used to connect an
unused tag to the documents.
Syntax :
INSERT INTO <table_name> ('column_name1' <datatype>,
'column_name2' <datatype>)
WHERE condition;
Example :
UPDATE students
WHERE <condition>;
Example :
DELETE FROM students
2. Revoke :
Revoke command withdraw user privileges on database objects if any
granted. It does operations opposite to the Grant command. When a
privilege is revoked from a particular user U, then the privileges granted to all
other users by user U will be revoked.
Syntax:
revoke privilege_name on object_name
from {user_name | public | role_name}
Example:
grant insert,
select on accounts to Ram
By the above command user ram has granted permissions on accounts
database object like he can query or insert into accounts.
revoke insert,
select on accounts from Ram
By the above command user ram’s permissions like query or insert on
accounts database object has been removed.
To know the exact syntax and how are they used click here.
Differences between Grant and Revoke commands:
• Syntax:
• COMMIT;
• Example: Sample table 1
•
•
• Following is an example which would delete those records from the
table which have age = 20 and then COMMIT the changes in the
database.
Queries:
• DELETE FROM Student WHERE AGE = 20;
• COMMIT;
•
• Output:
Thus, two rows from the table would be deleted and the SELECT
statement would look like,
•
•
• 4. ROLLBACK: If any error occurs with any of the SQL grouped
statements, all changes need to be aborted. The process of reversing
changes is called rollback. This command can only be used to undo
transactions since the last COMMIT or ROLLBACK command was
issued.
Syntax:
• ROLLBACK;
•
• Example:
From the above example Sample table1,
Delete those records from the table which have age = 20 and then
ROLLBACK the changes in the database.
Queries:
•
• 5. SAVEPOINT: creates points within the groups of transactions in
which to ROLLBACK.
A SAVEPOINT is a point in a transaction in which you can roll the
transaction back to a certain point without rolling back the entire
transaction.
• SAVEPOINT SAVEPOINT_NAME;
• This command is used only in the creation of SAVEPOINT among all
the transactions.
In general ROLLBACK is used to undo a group of transactions.
Syntax for rolling back to Savepoint command:
• ROLLBACK TO SAVEPOINT_NAME;
•
• you can ROLLBACK to any SAVEPOINT at any time to return the
appropriate data to its original state.
Example:
From the above example Sample table1,
Delete those records from the table which have age = 20 and then
ROLLBACK the changes in the database by keeping Savepoints.
Queries:
• SAVEPOINT SP1;
• //Savepoint created.
• DELETE FROM Student WHERE AGE = 20;
• //deleted
• SAVEPOINT SP2;
• //Savepoint created.
•
• Here SP1 is first SAVEPOINT created before deletion. In this example
one deletion have taken place.
After deletion again SAVEPOINT SP2 is created.
Output:
•
•
• Deletion have been taken place, let us assume that you have changed
your mind and decided to ROLLBACK to the SAVEPOINT that you
identified as SP1 which is before deletion.
deletion is undone by this statement,
• ROLLBACK TO SP1;
• //Rollback completed.
•
•
• 6. RELEASE SAVEPOINT:- This command is used to remove a
SAVEPOINT that you have created.
Syntax:
Syntax
Example:
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
4 Stephan
5 David
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.
Syntax
Example:
ID NAME
3 Jackson
4. Minus
o It combines the result of two SELECT statements. Minus operator is used to display the
rows which are present in the first query but absent in the second query.
o It has no duplicates and data arranged in ascending order by default.
Syntax:
Example
ID NAME
1 Jack
2 Harry
1. COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table. It can work
on both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) considers duplicate and Null.
Syntax
1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )
Sample table:
PRODUCT_MAST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Example: COUNT()
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
Output:
10
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;
Output:
Output:
Output:
Com1 5
Com2 3
Com3 2
Output:
Com1 5
Com2 3
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric
fields only.
Syntax
1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )
Example: SUM()
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;
Output:
670
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;
Output:
320
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;
Output:
Com1 150
Com2 170
Output:
Com1 335
Com3 170
3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG
function returns the average of all non-Null values.
Syntax
1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )
Example:
1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;
Output:
67.00
4. MAX Function
MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.
Syntax
1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )
Example:
1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30
5. MIN Function
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.
Syntax
1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )
Example:
1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;
Output:
10
Domain Constraints are user-defined columns that help the user to enter the
value according to the data type. And if it encounters a wrong input it gives
the message to the user that the column is not fulfilled properly. Or in other
words, it is an attribute that specifies all the possible values that the attribute
can hold like integer, character, date, time, string, etc. It defines the domain
or the set of values for an attribute and ensures that the value taken by the
attribute must be an atomic value(Can’t be divided) from its domain.
Domain Constraint = data type(integer / character/date / time /
string / etc.) +
Constraints(NOT NULL / UNIQUE / PRIMARY KEY /
FOREIGN KEY / CHECK / DEFAULT)
Type of domain constraints:
There are two types of constraints that come under domain constraint and
they are:
1. Domain Constraints – Not Null: Null values are the values that are
unassigned or we can also say that which are unknown or the missing
attribute values and by default, a column can hold the null values. Now as
we know that the Not Null constraint restricts a column to not accept the null
values which means it only restricts a field to always contain a value which
means you cannot insert a new record or update a record without adding a
value into the field.
Example: In the ’employee’ database, every employee must have a name
associated with them.
Create table employee
(employee_id varchar(30),
employee_name varchar(30) not null,
salary NUMBER);
2. Domain Constraints – Check: It defines a condition that each row must
satisfy which means it restricts the value of a column between ranges or we
can say that it is just like a condition or filter checking before saving data into
a column. It ensures that when a tuple is inserted inside the relation must
satisfy the predicate given in the check clause.
Example: We need to check whether the entered id number is greater than 0
or not for the employee table.
Create table employee
(employee_id varchar(30) not null check(employee_id > 0),
employee_name varchar(30),
salary NUMBER);
The above example creates CHECK constraints on the employee_id column
and specifies that the column employee_id must only include integers
greater than 0.
Table:
The above example will only accept the roll no. which is greater than 0.
Example 2:
Creating a table “Employee” with the “AGE” field having a value greater than
18.
Domain:
Table:
The above example will only accept the Employee with an age greater than
18.
The table from which the values are derived is known as Master or Referenced Table
and the Table in which values are inserted accordingly is known as Child or
Referencing Table, In other words, we can say that the table containing the foreign
key is called the child table, and the table containing the Primary key/candidate
key is called the referenced or parent table. When we talk about the database
relational model, the candidate key can be defined as a set of attribute which can have
zero or more attributes.
1. CREATE TABLE Student (Roll int PRIMARY KEY, Name varchar(25) , Course varc
har(10) );
Here column Roll is acting as Primary Key, which will help in deriving the value of
foreign key in the child table.
In the above table, column Roll is acting as Foreign Key, whose values are derived
using the Roll value of Primary key from Master table.
Insert Constraint: Value cannot be inserted in CHILD Table if the value is not lying in
MASTER Table
Delete Constraint: Value cannot be deleted from MASTER Table if the value is lying
in CHILD Table
Suppose you wanted to insert Roll = 05 with other values of columns in SUBJECT Table,
then you will immediately see an error "Foreign key Constraint Violated" i.e. on
running an insertion command as:
Insert into SUBJECT values(5, 786, OS); will not be entertained by SQL due to
Insertion Constraint ( As you cannot insert value in a child table if the value is not
lying in the master table, since Roll = 5 is not present in the master table, hence it will
not be allowed to enter Roll = 5 in child table )
Similarly, if you want to delete Roll = 4 from STUDENT Table, then you will immediately
see an error "Foreign key Constraint Violated" i.e. on running a deletion command
as:
Delete from STUDENT where Roll = 4; will not be entertained by SQL due to
Deletion Constraint. ( As you cannot delete the value from the master table if the
value is lying in the child table, since Roll = 5 is present in the child table, hence it will
not be allowed to delete Roll = 5 from the master table, lets if somehow we managed
to delete Roll = 5, then Roll = 5 will be available in child table which will ultimately
violate insertion constraint. )
ON DELETE CASCADE.
As per deletion constraint: Value cannot be deleted from the MASTER Table if the value
is lying in CHILD Table. The next question comes can we delete the value from the
master table if the value is lying in the child table without violating the deletion
constraint? i.e. The moment we delete the value from the master table the value
corresponding to it should also get deleted from the child table.
The answer to the above question is YES, we can delete the value from the master table
if the value is lying in the child table without violating the deletion constraint, we have
to do slight modification while creating the child table, i.e. by adding on delete
cascade.
TABLE SYNTAX
1. CREATE TABLE Subject (Roll int references Student on delete cascade, SubCod
e int, SubName varchar(10) );
In the above syntax, just after references keyword( used for creating foreign key), we
have added on delete cascade, by adding such now, we can delete the value from the
master table if the value is lying in the child table without violating deletion constraint.
Now if you wanted to delete Roll = 5 from the master table even though Roll = 5 is
lying in the child table, it is possible because the moment you give the command to
delete Roll = 5 from the master table, the row having Roll = 5 from child table will also
get deleted.
The above two tables STUDENT and SUBJECT having four values each are shown, now
suppose you are looking to delete Roll = 4 from STUDENT( Master ) Table by writing
a SQL command: delete from STUDENT where Roll = 4;
The moment SQL execute the above command the row having Roll = 4 from SUBJECT(
Child ) Table will also get deleted, The resultant STUDENT and SUBJECT table will
look like:
From the above two tables STUDENT and SUBJECT, you can see that in both the table
Roll = 4 gets deleted at one go without violating deletion constraint.
Sometimes a very important question is asked in interviews that: Can Foreign Key have
NULL values?
The answer to the above question is YES, it may have NULL values, whereas the Primary
key cannot be NULL at any cost. To understand the above question practically let's
understand below the concept of delete null.
ON DELETE NULL.
As per deletion constraint: Value cannot be deleted from the MASTER Table if the value
is lying in CHILD Table. The next question comes can we delete the value from the
master table if the value is lying in the child table without violating the deletion
constraint? i.e. The moment we delete the value from the master table the value
corresponding to it should also get deleted from the child table or can be replaced
with the NULL value.
The answer to the above question is YES, we can delete the value from the master table
if the value is lying in child table without violating deletion constraint by inserting NULL
in the foreign key, we have to do slight modification while creating child table, i.e. by
adding on delete null.
TABLE SYNTAX:
1. CREATE TABLE Subject (Roll int references Student on delete null, SubCode in
t, SubName varchar(10) );
In the above syntax, just after references keyword( used for creating foreign key), we
have added on delete null, by adding such now, we can delete the value from the
master table if the value is lying in the child table without violating deletion constraint.
Now if you wanted to delete Roll = 4 from the master table even though Roll =4 is
lying in the child table, it is possible because the moment you give the command to
delete Roll = 4 from the master table, the row having Roll = 4 from child table will get
replaced by a NULL value.
The above two tables STUDENT and SUBJECT having four values each are shown, now
suppose you are looking to delete Roll = 4 from STUDENT( Master ) Table by writing
a SQL command: delete from STUDENT where Roll = 4;
The moment SQL execute the above command the row having Roll = 4 from SUBJECT(
Child ) Table will get replaced by a NULL value, The resultant STUDENT and
SUBJECT table will look like:
From the above two tables STUDENT and SUBJECT, you can see that in table STUDENT
Roll = 4 get deleted while the value of Roll = 4 in the SUBJECT table is replaced by
NULL. This proves that the Foreign key can have null values. If in the case in SUBJECT
Table, column Roll is Primary Key along with Foreign Key then in that case we could
not make a foreign key to have NULL values.
Assertions have small syntax They have large Syntax to indicate each
5. compared to Triggers. and every specific of the created trigger.
Modern databases do not use Triggers are very well used in modern
6. Assertions. databases.
Assertions can’t modify the data and they are not linked to any specific
tables or events in the database but Triggers are more powerful because
they can check conditions and also modify the data within the tables inside a
database, unlike assertions.
SQL | Views
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.
In this article we will learn about creating , deleting and updating Views.
Sample Tables:
StudentDetails
StudentMarks
CREATING VIEWS
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;
DELETING VIEWS
We have learned about creating a View, but what if a created View is not needed
any more? Obviously we will want to delete it. SQL allows us to delete an existing
View. We can delete or drop a View using the DROP statement.
Syntax:
DROP VIEW view_name;
STUDENT
S_ID S_NAME S_ADDRESS S_PHONE S_AGE
S1 RAM DELHI 9455123451 18
COURSE
C_ID C_NAME
C1 DSA
C2 Programming
C3 DBMS
STUDENT_COURSE
S_ID C_ID
S1 C1
S1 C3
S2 C1
S3 C2
S4 C2
S4 C3
IN: If we want to find out S_ID who are enrolled in C_NAME ‘DSA’ or
‘DBMS’, we can write it with the help of independent nested query and
IN operator. From COURSE table, we can find
out C_ID for C_NAME ‘DSA’ or DBMS’ and we can use these C_IDs for
finding S_IDs from STUDENT_COURSE TABLE.
The inner query will return a set with members C1 and C3 and outer
query will return those S_IDs for which C_ID is equal to any member of
set (C1 and C3 in this case). So, it will return S1, S2 and S4.
Note: If we want to find out names of STUDENTs who have either
enrolled in ‘DSA’ or ‘DBMS’, it can be done as:
Select S_NAME from STUDENT where S_ID IN
(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’
or C_NAME=’DBMS’));
NOT IN: If we want to find out S_IDs of STUDENTs who have neither
enrolled in ‘DSA’ nor in ‘DBMS’, it can be done as:
Select S_ID from STUDENT where S_ID NOT IN
(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’
or C_NAME=’DBMS’));
The innermost query will return a set with members C1 and C3. Second
inner query will return those S_IDs for which C_ID is equal to any
member of set (C1 and C3 in this case) which are S1, S2 and S4. The
outermost query will return those S_IDs where S_ID is not a member of
set (S1, S2 and S4). So it will return S3.
1. Authentication :
Authentication is the process of confirmation that whether the user
log in only according to the rights provided to him to perform the
activities of data base. A particular user can login only up to his
privilege but he can’t access the other sensitive data. The privilege
of accessing sensitive data is restricted by using Authentication .
By using these authentication tools for biometrics such as retina
and figure prints can prevent the data base from
unauthorized/malicious users.
2. Access Control :
The security mechanism of DBMS must include some provisions for
restricting access to the data base by unauthorized users. Access
control is done by creating user accounts and to control login
process by the DBMS. So, that database access of sensitive data is
possible only to those people (database users) who are allowed to
access such data and to restrict access to unauthorized persons.
The database system must also keep the track of all operations
performed by certain user throughout the entire login time.
3. Inference Control :
This method is known as the countermeasures to statistical
database security problem.It is used to prevent the user from
completing any inference channel. This method protect the
sensitive information from indirect disclosure.
Inferences are of two types, identity disclosure or attribute
disclosure.
4. Flow Control :
This prevents information from flowing in a way that it reaches
unauthorized users. Channels are the pathways for information to
flow implicitly in ways that violate the privacy policy of a company
are called covert channels.
5. Database Security applying Statistical Method :
Statistical database security focuses on the protection of
confidential individual values stored in and used for statistical
purposes and used to retrieve the summaries of values based on
categories. They do not permit to retrieve the individual information.
This allows to access the database to get statistical information
about the number of employees in the company but not to access
the detailed confidential/personal information about specific
individual employee.
6. Encryption :
This method is mainly used to protect sensitive data (such as credit
card numbers, OTP numbers) and other sensitive numbers. The
data is encoded using some encoding algorithms.
An unauthorized user who tries to access this encoded data will
face difficulty in decoding it, but authorized users are given
decoding keys to decode data.
VARIABLE v NUMBER;
•
• Execution of the Procedure:
PRINT :v
•
Difference between Trigger and
Procedure in DBMS
1. Procedures :
A procedure is a combination of SQL statements written to perform a
specified tasks. It helps in code re-usability and saves time and lines of code.
2. Triggers :
A trigger is a special kind of procedure which executes only when some
triggering event such as INSERT, UPDATE, DELETE operations occurs in a
table.
Difference between Triggers and Procedures :
Triggers Procedures