0% found this document useful (0 votes)
31 views105 pages

DBS Unit II

The document discusses SQL and its components like DDL, DML, aggregate functions and more. SQL is used for relational databases and allows defining schemas, inserting, updating, deleting and querying data. Common SQL commands like CREATE, SELECT, WHERE, ORDER BY, JOIN and aggregate functions like COUNT, SUM, AVG are covered.

Uploaded by

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

DBS Unit II

The document discusses SQL and its components like DDL, DML, aggregate functions and more. SQL is used for relational databases and allows defining schemas, inserting, updating, deleting and querying data. Common SQL commands like CREATE, SELECT, WHERE, ORDER BY, JOIN and aggregate functions like COUNT, SUM, AVG are covered.

Uploaded by

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

Database Systems

Unit – II

SQL

Dr. S. Manikandan
HOD-IT

1
SQL

• 1970 – Sequel
• 1986 – SQL (Structured Query Language)
• It is not case sensitive
• It is a programming language for relational databases
like MySQL, Oracle, Sybase
• Non relational databases like MongoDB, DynamoDB do
not use SQL

2
Parts of SQL

• DDL
• Interactive DML
• Integrity Constraints – Commands
• View definition
• Transaction control – commands for
specifying beginning and ending of
transaction
• Embedded SQL and Dynamic SQL –
how SQL statements can be
embedded with C, C++,Java
3
Data Definition

• DDL allows information about


• The schema for each relation
• The domain values associated with
each attribute
• The integrity constraints
• Security & authorization information
for each relation
• The physical storage structure of each
relation on disk
4
Basic Domain Types

• char(n)
• varchar(n)
• int
• numeric(p,d)
numeric (3,1) allows 78.2
• Float(n)

5
Basic Schema Definition in SQL
What is Relational Database?
Relational database means the data is stored as well as retrieved in the form of
relations (tables).
Table 1 shows the relational database with only one relation
called STUDENT which
stores ROLL_NO, NAME, ADDRESS, PHONE and AGE of students.
STUDENT

ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 9156768971 18

6
Terminologies

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:
Degree: The number of attributes in the relation is known as degree of the
relation. The STUDENT relation defined above has degree 5.
Cardinality: The number of tuples in a relation is known as cardinality.
The STUDENT relation defined above has cardinality 4.
Column: Column represents the set of values for a particular attribute.
The column ROLL_NO is extracted from relation STUDENT.

7
SQL Commands

8
DDL

Here are some commands that come under


DDL:
• CREATE
• ALTER
• DROP
• TRUNCATE

9
• CREATE It is used to create a new table in
the database.
• Syntax:
• CREATE TABLE TABLE_NAME (COLUM
N_NAME DATATYPES[,....]);
• Example:
• CREATE TABLE EMPLOYEE(Name VAR
CHAR2(20), Email VARCHAR2(100), DOB
DATE);
10
• DROP: It is used to delete both the
structure and record stored in the table.
• Syntax
• DROP TABLE table_name;
• Example
• DROP TABLE EMPLOYEE;

11
• ALTER: It is used to alter the structure of the
database. This change could be either to modify the
characteristics of an existing attribute or probably to
add a new attribute.
• Syntax:
• To add a new column in the table
• ALTER TABLE table_name ADD column_name COLU
MN-definition;
• To modify existing column in the table:
• ALTER TABLE table_name MODIFY(column_definitio
ns....);
• EXAMPLE
• ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
• ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20)); 12
• TRUNCATE: It is used to delete all the
rows from the table and free the space
containing the table.
• Syntax:
• TRUNCATE TABLE table_name;
• Example:
• TRUNCATE TABLE EMPLOYEE;

13
DML Commands

Here are some commands that come under


DML:
• INSERT
• UPDATE
• DELETE

14
• INSERT: The INSERT statement is a SQL query. It is
used to insert data into the row of a table.
Syntax:
• INSERT INTO TABLE_NAME
(col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN); Or
• INSERT INTO TABLE_NAME
VALUES (value1, value2, value3, .... valueN);
Example
• INSERT INTO book (Author, Subject) VALU
ES (“Abraham", "DBMS"); 15
• UPDATE: This command is used to update or
modify the value of a column in the table.
Syntax:
• UPDATE table_name SET [column_name1= v
alue1,...column_nameN = valueN] [WHERE C
ONDITION]
For example:
UPDATE students
SET User_Name = 'Sonoo'
WHERE Student_Id = '3'

16
DELETE: It is used to remove one or more
row from a table.
Syntax:
• DELETE FROM table_name [WHERE co
ndition];
For example:
DELETE FROM book
WHERE Author=“Abraham";

17
Banking Database

Relational Schema
• branch(branch_name, branch_city,assets)
• customer(cus_name,cus_street,cus_city)
• loan(loan_num,branch_name,amount)
• borrower(cus_name,loan_num)
• account(account_num,branch_name,balance)
• depositor(cus_name,account_num)

Write create statements for the above

18
Basic Structure of SQL Queries

• It consists of three clauses: select, from,


where
select A1, A2, ….. An
from r1, r2,……rn
where P
A – attribute r – relation P- Predicate

19
select branch_name
from loan

select distinct branch_name


from loan

select all branch_name


from loan

20
Book Table

ISBN NO TITLE PUB_YEAR UNIT_PRICE AUTHOR_NAME PUBLISHER_NA


ME

1001 ORACLE 2004 399 Arora PHI

1002 DBMS 2004 400 Basu Technical

1003 DOS 2003 250 Sinha Nirali

1004 ADBMS 2004 450 Basu Technical

1005 UNIX 2000 300 Kapoor SciTech

21
Author table

Author_name Country

Arora U.S.

Kapoor Canada

Basu India

Sinha India

22
Select clause

• Use of select for displaying all fields


select * from book
• Select clause with arithmetic expression
select title, unit_price *10 from book;
• Find the titles of books published in 2004
Select title from book where
pub_year=2004

23
SQL uses logical connectives and,or,not

• Find the titles of book having price


between 300 to 400
Select title from book where unit_price
between 300 and 400;
Or
Select title from book where unit_price
>=300 and unit_price <=400;

24
Rename Operation

• Old-name as new-name
Select title, Unit_price*1.15 as New_price from book;
Tuple variables
Tuple variables are defined in the from clause by the
way of as clause
Find the titles of books with author name and author
country
select title, B.author_name, country
From book as B, author as A
Where B.author_name = A.author_name
25
String operations

• The most commonly used operation on strings is pattern


matching using the operator like
• We describe patterns by using two special characters
(Percent) % : The % character matches any substring
(Underscore) _ : The _ character matches any character
• Find the name of authors from author table where the first
two characters of name are “Ba’.
Select Author_name from Author
Where Author_name like ‘Ba%’;
• Find author name from author where the second character
of name is ‘r’ or ‘a’.
Select Author_name from Author
Where Author_name like ‘_r%’ or Author_name like ‘_a%’
26
Ordering the display of tuples
• SQL uses order by clause to display the tuples in the
result of the query to appear in sorted order.
• By default the order by clause lists item in ascending
order. To specify the sort order, we may specify desc
for descending order or asc for ascending order.
• Display the titles of books with price in ascending order
of title.
select title, unit_price from book order by title;
• Display the titles of books with price and year in
descending order of year
select title, unit_price, pub_year from book
order by pub_year desc;

27
Aggregate Functions
Aggregate functions are functions that take a
collection of values as input and return a single
value. SQL offers five built-in aggregate
functions.
SQL offers five built in aggregate function:
• Average: avg
• Minimum: min
• Maximum: max
• Total: sum
• Count: count

28
Aggregate Functions

select avg(unit_price) “Average price” from book;


Output:
Average price
359.8

select min(unit_price) “Minimum price” from book;


Output:
Minimum price
250

29
Aggregate Functions

select max(unit_price) “Maximum price” from book;


Output:
Maximum price
450
select sum(unit_price) “Total” from book;
Output:
Total
1799
select count(title) “No. of books” from book;
Output:
No. of books
5
30
Group by

• It is used to group the rows based on certain criteria.


Ex: Display the total price of all books (Publisher wise)
Select Publisher_name, sum(Unit_price) “Total book
amount” from book
group by Publisher_name;

Publisher_name Total book amount


Nirali 250
PHI 399
SciTech 300
Technical 850

31
Ex: On every book author receives 10 %
royalty. Display total royalty amount
received by each author till date.

32
• Select Author_name, sum(Unit_price * .10)
“Royalty Amount” from book
group by Author_name;

Author_name Royalty amount


Arora 39.99
Basu 85
Kapoor 30
Sinha 25

33
Having

• The having clause tells SQL to include


only certain groups produced by the
group by clause in the query result set.
• Having is equivalent to the where clause
and is used to specify search condition
when group by clause is specified

34
• Display publisher wise total price of books
published, except for publisher “PHI”.
select Publisher_name, sum(Unit_price) “Total
Book Amount” from book group by
Publisher_name
having Publisher_name < > ‘PHI’;
Publisher_name Total book amount
Nirali 250
SciTech 300
Technical 850

35
• Display royalty amount received by
those authors whose second
character of name contains ‘a’.

36
• Select Author_name, sum(Unit_price *
0.10) “Royalty Amount” from book
group by Author_name
having Author_name like ‘_a%’;
Author_name Royalty amount
Basu 85
Kapoor 30
Sinha 25

37
Set Operations

• The SQL operations union, intersect


and except operate on relations

38
Example – Set Operations
Depositor Table
Customer_Name Account_no
John 1001
Sita 1002
Vishal 1003
Ram 1004

Borrower Table
Customer_Name Loan_no
John 2001
Tonny 2002
Rohit 2003
Vishal 2004

39
Union

• Find all customers having a loan, an account, or both


at the bank
select Customer_Name from Borrower
union
select Customer_Name from Depositor;
The union operation automatically terminates duplicates.
If we want to retain all duplicates, we must write union
all in place of union
select Customer_Name from Borrower
union all
select Customer_Name from Depositor;

40
Customer_Name Customer_Name
John John
Sita Sita
Vishal Vishal
Ram Ram
Tonny John
Rohit Tonny
Rohit
Vishal

41
Intersect
• Intersect operation returns common records from the
output of both queries.
Find all customers who have a loan and account at the
bank
select Customer_Name from Depositor
intersect
select Customer_Name from Borrower;
The intersect operation automatically terminates
duplicates. If we want to retain all duplicates, we must
write intersect all in place of intersect
select Customer_Name from Borrower
Intersect all
select Customer_Name from Depositor;
42
Cusomer_name
John
Vishal

43
Except

• Except also called Minus outputs rows that are in first


table but not in second table
select Customer_Name from Depositor
except
select Customer_Name from Borrower;

Customer_name
Ram
Sita

44
Null Values

• SQL allows the use of null values to indicate absence of


information about the value of attribute.
• Use keyword null in a predicate to test for null value
Cust_no Cust_name Cust_Phone_no
• Cust Table 1 Balaji 8556556565
2 Ram 9598653248
3 Mahesh

• Select Cust_name from Cust


where Cust_Phone_no is null;
• Select Cust_name from Cust
where Cust_Phone_no is not null;

45
Nested Subquries

• SQL provides a mechanism for nesting subquries. A


subquery is a select from where expression that is nested
within another query.
Set Memberships
SQL uses in and not in constructs for set membership
tests.
IN
The in connective tests for set membership, where the
set is a collection of values produced by a select
clause

46
Set Memberships

• Display the title, author, publisher name and publisher year


of all books published in 2000, 2002 and 2004
select title, author_name, Publisher_name, Pub_year
from book
where Pub_year in(‘2000’,’2002’,’2004’);

47
in

• Get the details of author who have published book in


2004
Select * from author
Where Author_name in (select Author_name

from book
Author_name Country
where Pub_year = ‘2004’);

Arora U.S.
Basu India

48
Not in

• Display title, author, Publisher name and Publisher


year of all books except those which are published
in 2002,2004 abd 2005.
select title, author_name, Publisher_name,
Pub_year from book
where Pub_year not in(‘2002’,’2004’,’2005’);

49
Not in

• Get the titles of all books written by authors not living in


india.
Select Title from book
where Author_name not in (select Author_name
from author
where country = ‘India’);
Title

Oracle
Unix

50
Set Comparison

• SQL uses various comparison operators such as


<,>,<=,>=,=,<>,any, all, some, etc to compare
sets.
Display the name of the author who have received
highest royalty
select Author_name from book
group by Author_name
having sum(Unit_price*.10) >= all (select
sum(Unit_price*0.10) from book group by
Author_name);

51
JOIN

• Join (Inner, Left, Right and Full Joins)


• A SQL Join statement is used to combine data or
rows from two or more tables based on a common
field between them. Different types of Joins are:
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN

52
Student

Student
Course

53
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.

54
• SELECT StudentCourse.COURSE_ID, Student.NAME,
Student.AGE FROM Student INNER JOIN
StudentCourse ON Student.ROLL_NO =
StudentCourse.ROLL_NO;
Output:

55
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.

56
SELECT student.NAME, StudentCourse.COURSE_ID
FROM Student LEFT JOIN StudentCourse ON
StudentCourse.ROLL_NO = Student.ROLL_NO;

57
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

58
SELECT Student.NAME, StudentCourse.COURSE_ID
FROM Student RIGHT JOIN StudentCourse ON
StudentCourse.ROLL_NO = Student.ROLL_NO;

59
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 will
contain NULL values.

60
• SELECT Student.NAME, StudentCourse.COURSE_ID
FROM Student FULL JOIN StudentCourse ON
StudentCourse.ROLL_NO = Student.ROLL_NO;

61
VIEW

• 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.

62
StudentDetails

StudentMarks

63
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;

64
Creating View from a single table

In this example we will create a View named


DetailsView from the table StudentDetails.
Query:
CREATE VIEW DetailsView AS SELECT NAME,
ADDRESS FROM StudentDetails WHERE S_ID < 5;
To see the data in the View, we can query the view in
the same manner as we query a table.
SELECT * FROM DetailsView;

65
• In this example, we will create a view named
StudentNames from the table StudentDetails.
CREATE VIEW StudentNames AS SELECT S_ID,
NAME FROM StudentDetails ORDER BY NAME;
If we now query the view as,
• SELECT * FROM StudentNames;

66
Creating View from multiple tables

In this example we will create a View named MarksView from


two tables StudentDetails and StudentMarks. To create a
View from multiple tables we can simply include multiple
tables in the SELECT statement.
• CREATE VIEW MarksView AS SELECT
StudentDetails.NAME, StudentDetails.ADDRESS,
StudentMarks.MARKS FROM StudentDetails,
StudentMarks WHERE StudentDetails.NAME =
StudentMarks.NAME;
To display data of View MarksView:
• SELECT * FROM MarksView;

67
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
For example, if we want to delete the
View MarksView, we can do this as:
• DROP VIEW MarksView;

68
UPDATING VIEWS
There are certain conditions needed to be satisfied to update a
view. If any one of these conditions is not met, then we will
not be allowed to update the view.
• The SELECT statement which is used to create the view
should not include GROUP BY clause or ORDER BY clause.
• The SELECT statement should not have the DISTINCT
keyword.
• The View should have all NOT NULL values.
• The view should not be created using nested queries or
complex queries.
• The view should be created from a single table. If the view is
created using multiple tables then we will not be allowed to
update the view.

69
• We can use the CREATE OR REPLACE
VIEW statement to add or remove fields
from a view.
• CREATE OR REPLACE VIEW
view_name AS SELECT
column1,coulmn2,.. FROM table_name
WHERE condition;

70
For example, if we want to update the view MarksView and
add the field AGE to this View from StudentMarks Table,
we can do this as:
• CREATE OR REPLACE VIEW MarksView AS SELECT
StudentDetails.NAME, StudentDetails.ADDRESS,
StudentMarks.MARKS, StudentMarks.AGE FROM
StudentDetails, StudentMarks WHERE
StudentDetails.NAME = StudentMarks.NAME;
If we fetch all the data from MarksView now as:
• SELECT * FROM MarksView;

71
Inserting a row in a view
We can insert a row in a View in a same way as we do in
a table. We can use the INSERT INTO statement of
SQL to insert a row in a View
INSERT INTO DetailsView(NAME, ADDRESS)
VALUES("Suresh","Gurgaon");
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;

72
Deleting a row from a View

Deleting rows from a view is also as simple as deleting


rows from a table. We can use the DELETE statement
of SQL to delete rows from a view. Also deleting a row
from a view first delete the row from the actual table
and the change is then reflected in the view.
• DELETE FROM DetailsView WHERE
NAME="Suresh";
If we fetch all the data from DetailsView now as,
• SELECT * FROM DetailsView;

73
Transactions
• A transaction is a unit of work that is performed against a
database. Transactions are units or sequences of work
accomplished in a logical order, whether in a manual
fashion by a user or automatically by some sort of a
database program.
• A transaction is the propagation of one or more changes to
the database. For example, if you are creating a record or
updating a record or deleting a record from the table, then
you are performing a transaction on that table. It is
important to control these transactions to ensure the data
integrity and to handle database errors.
• Practically, you will club many SQL queries into a group
and you will execute all of them together as a part of a
transaction.
74
• The following commands are used to
control transactions.
• COMMIT − to save the changes.
• ROLLBACK − to roll back the changes.
• SAVEPOINT − creates points within the
groups of transactions in which to
ROLLBACK.
• SET TRANSACTION − Places a name
on a transaction.

75
COMMIT
• Transactional control commands are only used with
the DML Commands such as - INSERT, UPDATE
and DELETE only. They cannot be used while creating
tables or dropping them because these operations are
automatically committed in the database.
• The COMMIT Command
• The COMMIT command is the transactional command
used to save changes invoked by a transaction to the
database.
• The COMMIT command is the transactional command
used to save changes invoked by a transaction to the
database. The COMMIT command saves all the
transactions to the database since the last COMMIT or
ROLLBACK command.
76
The syntax for the COMMIT command is as follows.
COMMIT;
Example
SQL> DELETE FROM CUSTOMERS WHERE AGE = 25;
SQL> COMMIT;
Thus, two rows from the table would be deleted and the
SELECT statement would produce the following result.

77
ROLLBACK Command

• The ROLLBACK command is the


transactional command used to undo
transactions that have not already been
saved to the database. This command
can only be used to undo transactions
since the last COMMIT or ROLLBACK
command was issued.
• The syntax for a ROLLBACK command
is as follows −
• ROLLBACK;
78
• SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
• SQL> ROLLBACK;
• Thus, the delete operation would not
impact the table and the SELECT
statement would produce the following
result.

79
SAVEPOINT Command

• A SAVEPOINT is a point in a transaction


when you can roll the transaction back to
a certain point without rolling back the
entire transaction.
• The syntax for a SAVEPOINT command
is as shown below.
• SAVEPOINT SAVEPOINT_NAME;

80
• SQL> SAVEPOINT SP1;
Savepoint created.
• SQL> DELETE FROM CUSTOMERS WHERE ID=1;
1 row deleted.
• SQL> SAVEPOINT SP2;
Savepoint created.
• SQL> DELETE FROM CUSTOMERS WHERE ID=2;
1 row deleted.
• SQL> SAVEPOINT SP3;
Savepoint created.
• SQL> DELETE FROM CUSTOMERS WHERE ID=3;
1 row deleted.
81
• Now that the three deletions have taken place, let us
assume that you have changed your mind and
decided to ROLLBACK to the SAVEPOINT that you
identified as SP2. Because SP2 was created after
the first deletion, the last two deletions are undone −
• SQL> ROLLBACK TO SP2;
• Rollback complete.
• Notice that only the first deletion took place since
you rolled back to SP2.

82
RELEASE SAVEPOINT Command

• The RELEASE SAVEPOINT command is used to


remove a SAVEPOINT that you have created.
• The syntax for a RELEASE SAVEPOINT command
is as follows.
• RELEASE SAVEPOINT SAVEPOINT_NAME;
• Once a SAVEPOINT has been released, you can no
longer use the ROLLBACK command to undo
transactions performed since the last SAVEPOINT.

83
SET TRANSACTION Command

• The SET TRANSACTION command can be used to


initiate a database transaction. This command is used to
specify characteristics for the transaction that follows. For
example, you can specify a transaction to be read only or
read write.
• The syntax for a SET TRANSACTION command is as
follows.
• SET TRANSACTION [ READ WRITE | READ ONLY ];

84
SQL Data Types and Schemas
Date and Time Data Type
Datatype Description

DATE Stores date in the format YYYY-MM-DD

TIME Stores time in the format HH:MI:SS

Stores date and time information in the


DATETIME
format YYYY-MM-DD HH:MI:SS

Stores number of seconds passed since


TIMESTAMP the Unix epoch (‘1970-01-01 00:00:00’
UTC)

Stores year in 2 digits or 4 digit format.


Range 1901 to 2155 in 4-digit format.
YEAR
Range 70 to 69, representing 1970 to
2069.

85
SQL Character and String Data Types

Datatype Description

Fixed length with a


CHAR maximum length of 8,000
characters

Variable-length storage with


VARCHAR a maximum length of 8,000
characters

Variable-length storage with


VARCHAR(max) provided max characters, not
supported in MySQL

Variable-length storage with


TEXT
maximum size of 2GB data

86
Procedure
• A procedure is a subprogram that performs
a specific action.
create or replace procedure <proc_name> [parameter
list] is
<local declaration>
begin
(executable statements)
[exception] (exception handlers)
end;
A Procedure has two parts:
• Specification
• Body
87
• Specification begins with the key word
procedure and ends with the procedure
name or parameter list.
• Procedure body begins with the keyword
is and ends with the keyword end.
• Syntax to execute a procedure is
exec <proc_name> (parameters);

88
Types of parameters passed to subprogram

1. In parameter: IT is used to pass


values to the subprogram when
invoked.
2. Out parameter: It is used to return
values to the caller of a subprogram.
3. Inout parameter: It is used to pass
initial values to subprogram when
invoked and it also returns updated
values to the caller.

89
create or replace procedure "INSERTUSER"
(id IN NUMBER,
name IN VARCHAR2)
is
begin
insert into user values(id,name);
end;
BEGIN
insertuser(101,'Rahul');
dbms_output.put_line('record inserted successfully');
END;
90
Function

• Function is a sub program that computes a value.


create or replace function <function-name>
[argument list] return data type is
(local declaration)
begin
(executable statements)
[exception]
(exception handler)
end:

91
Example

• Create or replace Large_num ( a in number, b in number, c


in number) return number is
begin
if a>b and a>c then
return a;
else if b>a and b>c then
return b;
else
return c:
end if;
end;

92
Integrity Constraints

• Integrity constraints are a set of rules. It is used to


maintain the quality of information.
• Integrity constraints ensure that the data insertion,
updating, and other processes have to be
performed in such a way that data integrity is not
affected.
• Thus, integrity constraint is used to guard against
accidental damage to the database.

93
94
Domain constraints

• Domain constraints can be defined as the definition


of a valid set of values for an attribute.
• The data type of domain includes string, character,
integer, time, date, currency, etc. The value of the
attribute must be available in the corresponding
domain.
Example:

95
Entity integrity constraints

• The entity integrity constraint states that primary key


value can't be null.
• This is because the primary key value is used to
identify individual rows in relation and if the primary key
has a null value, then we can't identify those rows.
• A table can contain a null value other than the primary
key field.
Example:

96
Referential Integrity Constraints

• A referential integrity constraint is


specified between two tables.
• In the Referential integrity constraints, if a
foreign key in Table 1 refers to the
Primary Key of Table 2, then every value
of the Foreign Key in Table 1 must be
null or be available in Table 2.

97
Example

98
Key constraints

• Keys are the entity set that is used to identify an


entity within its entity set uniquely.
• An entity set can have multiple keys, but out of which
one key will be the primary key. A primary key can
contain a unique and null value in the relational table.
Example:

99
Trigger

• Trigger: A trigger is a stored procedure in database


which automatically invokes whenever a special event
in the database occurs. For example, a trigger can be
invoked when a row is inserted into a specified table or
when certain table columns are being updated.
Syntax:
• create trigger [trigger_name]
• [before | after]
• {insert | update | delete}
• on [table_name]
• [for each row]
• [trigger_body]

100
Explanation of syntax
• create trigger [trigger_name]: Creates or replaces an
existing trigger with the trigger_name.
• [before | after]: This specifies when the trigger will be
executed.
• {insert | update | delete}: This specifies the DML
operation.
• on [table_name]: This specifies the name of the
table associated with the trigger.
• [for each row]: This specifies a row-level trigger, i.e.,
the trigger will be executed for each row being
affected.
• [trigger_body]: This provides the operation to be
performed as trigger is fired
101
Example:

Given Student Report Database, in which


student marks assessment is recorded.
In such schema, create a trigger so that
the total and average of specified marks
is automatically inserted whenever a
record is insert.
• Here, as trigger will invoke before record
is inserted so, BEFORE Tag can be
used.

102
Example

create trigger stud_marks


before INSERT
on Student
for each row
set Student.total = Student.subj1 +
Student.subj2 + Student.subj3,
Student.per = Student.total * 60 / 100;

103
insert into Student values(1,"ABCDE", 20, 20, 20, 0, 0);

Query OK, 1 row affected (0.09 sec)


mysql> select * from Student;

| tid | name | subj1 | subj2 | subj3 | total | per |


| 1 | ABCDE | 20 | 20 | 20 | 60 | 36 |

1 row in set (0.00 sec)

104
End

105

You might also like