0% found this document useful (0 votes)
10 views

DBMS Unit 3

The document discusses different types of constraints in SQL including NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT. It also covers creating indexes and different types of joins in SQL including INNER, LEFT, RIGHT, and FULL OUTER joins.

Uploaded by

siddhunkl33
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

DBMS Unit 3

The document discusses different types of constraints in SQL including NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT. It also covers creating indexes and different types of joins in SQL including INNER, LEFT, RIGHT, and FULL OUTER joins.

Uploaded by

siddhunkl33
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

UNIT-3

SQL | Constraints
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.
The available 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.
Syntax:
Below is the syntax to create constraints using CREATE TABLE statement at the time of creating the table.

CREATE TABLE sample_table


(
column1 data_type(size) constraint_name,
column2 data_type(size) constraint_name,
column3 data_type(size) constraint_name,
....
);

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
//Unique
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

//Primary Key
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
• The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

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

• The table with the foreign key is called the child table, and the table with the primary key is called the referenced
or parent table.
Persons PersonID LastName FirstName Age
Table 1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20

derID OrderNumb PersonID


Orders Table er
1 77895 3
2 44678 3
3 22456 2
4 24562 1
• The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

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

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

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

CREATE TABLE Orders (


OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);
• The CHECK constraint is used to limit the value range that can be placed in a column.

• If you define a CHECK constraint on a column it will allow only certain values for this column.

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

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);
• The DEFAULT constraint is used to set a default value for a column.

• The default value will be added to all new records, if no other value is specified.

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);

CREATE TABLE Orders (


ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT GETDATE()
);
CREATE INDEX Statement

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

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

CREATE INDEX index_name


ON table_name (column1, column2, ...);
SQL JOIN
• A JOIN clause is used to combine rows from two or more tables, based on a related column between them.
• Let's look at a selection from the "Orders" table: "Customers" table:
Custo CustomerNam ContactName Country
OrderID CustomerI OrderDate merID e
D
1 Alfreds Maria Anders Germany
10308 2 1996-09-18 Futterkiste
2 Ana Trujillo Ana Trujillo Mexico
10309 37 1996-09-19
Emparedados
y helados
10310 77 1996-09-20
3 Antonio Antonio Mexico
Moreno Moreno
Taquería
SELECT Orders.OrderID, Customers.CustomerName,
Orders.OrderDate
FROM Orders
INNER JOIN Customers ON
Orders.CustomerID=Customers.CustomerID;
OrderID CustomerName OrderDat
e
10308 Ana Trujillo Emparedados y helados 9/18/1996
10365 Antonio Moreno Taquería 11/27/199
6
10383 Around the Horn 12/16/199
6
10355 Around the Horn 11/15/199
6
10278 Berglunds snabbköp 8/12/1996
Different Types of SQL JOINs

Here are the different types of the JOINs in SQL:


• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table
• FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table
A. INNER JOIN
• The INNER JOIN keyword selects all rows from both the tables as long as the condition is satisfied. 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 the same.

Syntax:
Example Queries(INNER JOIN)
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 This query will show the names and age of students enrolled
INNER JOIN table2 in different courses.
ON table1.matching_column = table2.matching_column;
SELECT StudentCourse.COURSE_ID, Student.NAME,
Student.AGE FROM Student
table1: First table. INNER JOIN StudentCourse
table2: Second table ON Student.ROLL_NO = StudentCourse.ROLL_NO;
matching_column: Column common to both the tables.
Consider the two tables below as follows:
StudentCourse
Student

Output:
B. LEFT JOIN
• This join returns all the rows of the table on the left side of the join and matches rows for the table on the right
side of the join. For the rows for which there is no matching row on the right side, the result-set will contain null.
LEFT JOIN is also known as LEFT OUTER JOIN.
SELECT Student.NAME,StudentCourse.COURSE_ID
Syntax: FROM Student
LEFT JOIN StudentCourse
SELECT table1.column1,table1.column2,table2.column1,.... ON StudentCourse.ROLL_NO = Student.ROLL_NO;
FROM table1
LEFT JOIN table2 Output:
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
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 the join. For the rows for which there is no matching row on the left side, the
result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.

Syntax: SELECT Student.NAME,StudentCourse.COURSE_ID


FROM Student
SELECT table1.column1,table1.column2,table2.column1,.... RIGHT JOIN StudentCourse
FROM table1 ON StudentCourse.ROLL_NO = Student.ROLL_NO;
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Output:

table1: First table.


table2: Second table
matching_column: Column common to both the tables
D. FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT JOIN. The result-set will contain all the
rows from both tables. For the rows for which there is no matching, the result-set will contain NULL values.

Syntax:
Example Queries(FULL JOIN):
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 SELECT Student.NAME,StudentCourse.COURSE_ID
FULL JOIN table2 FROM Student
ON table1.matching_column = table2.matching_column; FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Output:
NAME COURSE_ID

HARSH 1

PRATIK 2

RIYANKA 2

DEEP 3

SAPTARHI 1

DHANRAJ NULL

ROHIT NULL

NIRAJ NULL

NULL 4

NULL 5

NULL 4
SET Operators in SQL
SET operators are special type of operators which are used to combine the result of two queries.
Operators covered under SET operators are:
1.UNION
2.UNION ALL
3.INTERSECT
4.MINUS

There are certain rules which must be followed to perform


operations using SET operators in SQL. Rules are as follows:

• The number and order of columns must be the same.


• Data types must be compatible.
All the examples will be written using the MySQL database.
Consider we have the following tables with the given data.
Table 1: t_employees Table 2: t2_employees

ID Name Department Salary Year_of_Ex ID Name Department Salary Year_of_Ex


perience perience

1 Aakash Developmen 72000 2 1 Prashant R&D 49000 1


Singh t Wagh
2 Abhishek Production 45000 1 2 Abhishek Production 45000 1
Pawar Pawar
3 Pranav HR 59900 3 3 Gautam Jain Development 56000 4
Deshmukh
4 Shubham Accounts 57000 2 4 Shubham Accounts 57000 2
Mahale Mahale
5 Sunil Developmen 87000 3 5 Rahul Production 76000 4
Kulkarni t Thakur
6 Bhushan R&D 75000 2 6 Bhushan R&D 75000 2
Wagh Wagh
7 Paras Jaiswal Marketing 32000 1 7 Anand Singh Marketing 28000 1
Table 3: t_students Table 4: t2_students

ID Name Hometown Percentage Favourite_Su ID Name Hometown Percentage Favourite_


bject Subject
1 Soniya Jain Udaipur 89 Physics
1 Soniya Jain Udaipur 89 Physics
2 Harshada Kanpur 92 Chemistry
Sharma
2 Ishwari Delhi 86 Hindi
3 Anuja Rajput Jaipur 78 History Dixit
3 Anuja Jaipur 78 History
4 Pranali Singh Nashik 88 Geography Rajput
4 Pakhi Surat 70 Sanskrit
5 Renuka Panipat 90 Biology
Deshmukh Arora

6 Swati Kumari Faridabad 93 English 5 Renuka Panipat 90 Biology


Deshmukh
7 Prachi Gurugram 96 Hindi
Jaiswal 6 Jayshree Pune 91 Maths
Patel
7 Prachi Gurugram 96 Hindi
Jaiswal
1. UNION:

• UNION will be used to combine the result of two select statements.


• Duplicate rows will be eliminated from the results obtained after performing the UNION operation.

Example 1:
Write a query to perform union between the table t_employees and the table t2_employees.
Query:
1.mysql> SELECT *FROM t_employees UNION SELECT *FROM t2_employees;
Here, in a single query, we have written two SELECT queries. The first SELECT query will fetch the records from the
t_employees table and perform a UNION operation with the records fetched by the second SELECT query from the
t2_employees table.
ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

1 Prashant Wagh R&D 49000 1

3 Gautam Jain Development 56000 4

5 Rahul Thakur Production 76000 4

7 Anand Singh Marketing 28000 1


UNION ALL
• This operator combines all the records from both the queries.
• Duplicate rows will be not be eliminated from the results obtained after performing the UNION ALL operation.
Example 1:
Write a query to perform union all operation between the table t_employees and the table t2_employees.
SELECT *FROM t_employees UNION ALL SELECT *FROM t2_employees;
ID Name Department Salary Year_of_Experien
ce
1 Aakash Singh Development 72000 2
2 Abhishek Pawar Production 45000 1
3 Pranav Deshmukh HR 59900 3
4 Shubham Mahale Accounts 57000 2
5 Sunil Kulkarni Development 87000 3
6 Bhushan Wagh R&D 75000 2
7 Paras Jaiswal Marketing 32000 1
1 Prashant Wagh R&D 49000 1
2 Abhishek Pawar Production 45000 1
3 Gautam Jain Development 56000 4
4 Shubham Mahale Accounts 57000 2
5 Rahul Thakur Production 76000 4
6 Bhushan Wagh R&D 75000 2
7 Anand Singh Marketing 28000 1
INTERSECT:
• It is used to combine two SELECT statements, but it only returns the records which are common from both SELECT
statements.

SELECT *FROM t_employees INTERSECT SELECT *FROM t2_employees;

ID Name Hometown Percentage Favourite_S


ubject

2 Abhishek Production 45000 1


Pawar
4 Shubham Accounts 57000 2
Mahale
6 Bhushan R&D 75000 2
Wagh
4.MINUS
• It displays the rows which are present in the first query but absent in the second query with no duplicates.

SELECT *FROM t_employees MINUS SELECT *FROM t2_employees;

ID Name Department Salary Year_of_Ex


perience

1 Aakash Development 72000 2


Singh
3 Pranav HR 59900 3
Deshmukh
5 Sunil Development 87000 3
Kulkarni
7 Paras Jaiswal Marketing 32000 1
SQL Subqueries
• An SQL Subquery, is a SELECT query within another query. It is also known as Inner
query or Nested query and the query containing it is the outer query.
• The outer query can contain the SELECT, INSERT, UPDATE, and DELETE statements. We can
use the subquery as a column expression, as a condition in SQL clauses, and with operators
like =, >, <, >=, <=, IN, BETWEEN, etc.
Rules to be followed
Following are the rules to be followed while writing subqueries −
• Subqueries must be enclosed within parentheses.
• Subqueries can be nested within another subquery.
• A subquery must contain the SELECT query and the FROM clause always.
• A subquery consists of all the clauses an ordinary SELECT clause can contain: GROUP BY,
WHERE, HAVING, DISTINCT, TOP/LIMIT, etc. However, an ORDER BY clause is only used
when a TOP clause is specified. It can't include COMPUTE or FOR BROWSE clause.
• A subquery can return a single value, a single row, a single column, or a whole table. They
are called scalar subqueries.
Subqueries with the SELECT Statement

SELECT column_name [, column_name ]


FROM table1 [, table2 ]
WHERE column_name
OPERATOR (SELECT column_name [,column_name ] FROM table1 [, table2 ] [WHERE]);
//Example
CREATE TABLE CUSTOMERS ( ID NAME AGE ADDRESS SALARY
ID INT NOT NULL,
1 Ramesh 32 Ahmedabad 2000.00
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL, 2 Khilan 25 Delhi 1500.00
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2), 3 kaushik 23 Kota 2000.00
PRIMARY KEY (ID) 4 Chaitali 25 Mumbai 6500.00
);
INSERT INTO CUSTOMERS VALUES 5 Hardik 27 Bhopal 8500.00
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00),
6 Komal 22 Hyderabad 4500.00
(2, 'Khilan', 25, 'Delhi', 1500.00),
(3, 'Kaushik', 23, 'Kota', 2000.00), 10000.0
7 Muffy 24 Indore
(4, 'Chaitali', 25, 'Mumbai', 6500.00), 0
(5, 'Hardik', 27, 'Bhopal', 8500.00),
(6, 'Komal', 22, 'Hyderabad', 4500.00),
(7, 'Muffy', 24, 'Indore', 10000.00);
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500);

ID NAME AGE ADDRESS SALARY

4 Chaitali 25 Mumbai 6500.00


5 Hardik 27 Bhopal 8500.00

7 Muffy 24 Indore 10000.00


Subqueries with the INSERT Statement

INSERT INTO table_name [ (column1 [, column2 ]) ]


SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ] SELECT * FROM CUSTOMERS_BKP;
[ WHERE VALUE OPERATOR ]
ID NAME AGE ADDRESS SALARY
CREATE TABLE CUSTOMERS_BKP ( 1 Ramesh 32 Ahmedabad 2000.00
ID INT NOT NULL,
2 Khilan 25 Delhi 1500.00
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL, 3 kaushik 23 Kota 2000.00
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2), 4 Chaitali 25 Mumbai 6500.00
PRIMARY KEY (ID) 5 Hardik 27 Bhopal 8500.00
);
6 Komal 22 Hyderabad 4500.00
INSERT INTO CUSTOMERS_BKP 10000.0
7 Muffy 24 Indore
SELECT * FROM CUSTOMERS 0
WHERE ID IN (SELECT ID FROM CUSTOMERS);
Subqueries with the UPDATE Statement

UPDATE table
SET column_name = new_value
[WHERE OPERATOR [VALUE](SELECT COLUMN_NAME FROM TABLE_NAME [WHERE]);

UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25 ID NAME AGE ADDRESS SALARY
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
1 Ramesh 32 Ahmedabad 500.00
WHERE AGE >= 27 );
2 Khilan 25 Delhi 1500.00
SELECT * FROM CUSTOMERS;
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 2125.00
6 Komal 22 Hyderabad 4500.00
10000.0
7 Muffy 24 Indore
0
Subqueries with the DELETE Statement

DELETE FROM TABLE_NAME


[WHERE OPERATOR [ VALUE ](SELECT COLUMN_NAME FROM TABLE_NAME)[WHERE)];
DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 );
SELECT * FROM CUSTOMERS;

ID NAME AGE ADDRESS SALARY

2 Khilan 25 Delhi 1500.00


3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00


SQL Views
• SQL CREATE VIEW Statement
• In SQL, a view is a virtual table based on the result-set of an SQL statement.
• A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real
tables in the database.
• You can add SQL statements and functions to a view and present the data as if the data were coming from one
single table.
• A view is created with the CREATE VIEW statement.

CREATE VIEW [Products Above Average Price] AS


CREATE VIEW view_name AS SELECT ProductName, Price
SELECT column1, column2, ... FROM Products
FROM table_name WHERE Price > (SELECT AVG(Price) FROM Products);
WHERE condition; SELECT * FROM [Products Above Average Price];
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';

SELECT * FROM [Brazil Customers];


SQL Updating a View SQL Dropping a View

DROP VIEW view_name;


CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ... DROP VIEW [Brazil Customers];
FROM table_name
WHERE condition;

CREATE OR REPLACE VIEW [Brazil Customers] AS


SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';
PL/SQL Introduction
• PL/SQL is a block structured language that enables developers to combine the power of SQL with procedural
statements.All the statements of a block are passed to oracle engine all at once which increases processing speed
and decreases the traffic.

Basics of PL/SQL
• PL/SQL stands for Procedural Language extensions to the Structured Query Language (SQL).
• PL/SQL is a combination of SQL along with the procedural features of programming languages.
• Oracle uses a PL/SQL engine to processes the PL/SQL statements.
• PL/SQL includes procedural language elements like conditions and loops. It allows declaration of constants
and variables, procedures and functions, types and variable of those types and triggers.
Disadvantages of SQL:
• SQL doesn’t provide the programmers with a technique of condition checking, looping and branching.
• SQL statements are passed to Oracle engine one at a time which increases traffic and decreases speed.
• SQL has no facility of error checking during manipulation of data.
Features of PL/SQL:
• PL/SQL is basically a procedural language, which provides the functionality of decision making, iteration and many
more features of procedural programming languages.
• PL/SQL can execute a number of queries in one block using single command.
• One can create a PL/SQL unit such as procedures, functions, packages, triggers, and types, which are stored in the
database for reuse by applications.
• PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known as exception handling
block.
• Applications written in PL/SQL are portable to computer hardware or operating system where Oracle is
operational.
• PL/SQL Offers extensive error checking.
Differences between SQL and PL/SQL:

SQL PL/SQL

SQL is a single query that is used to perform DML and PL/SQL is a block of codes that used to write the
DDL operations. entire program blocks/ procedure/ function, etc.

It is declarative, that defines what needs to be done, PL/SQL is procedural that defines how the things
rather than how things need to be done. needs to be done.

Execute as a single statement. Execute as a whole block.

Mainly used to manipulate data. Mainly used to create an application.

It is an extension of SQL, so it can contain SQL inside


Cannot contain PL/SQL code in it.
it.
Structure of PL/SQL Block:
• PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural language that is
more powerful than SQL. The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which
can be nested within each other.

Typically, each block performs a logical action in the


program. A block has the following structure:

DECLARE
declaration statements;

BEGIN
executable statements

EXCEPTIONS
exception handling statements

END;
• Declare section starts with DECLARE keyword in which variables, constants, records as cursors can be declared
which stores data temporarily. It basically consists definition of PL/SQL identifiers. This part of the code is
optional.
• Execution section starts with BEGIN and ends with END keyword. This is a mandatory section and here the
program logic is written to perform any task like loops and conditional statements. It supports all DML
commands, DDL commands and SQL*PLUS built-in functions as well.
• Exception section starts with EXCEPTION keyword. This section is optional which contains statements that are
executed when a run-time error occurs. Any exceptions can be handled in this section.

SQL> SET SERVEROUTPUT ON;


SQL> DECLARE
SQL> SET SERVEROUTPUT ON; -- taking input for variable a
SQL> DECLARE a integer := &a ;
var varchar2(40) := 'I love GeeksForGeeks' ; -- taking input for variable b
b integer := &b ;
BEGIN c integer ;
dbms_output.put_line(var); BEGIN
c := a + b ;
END; dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c);
/ END;
/
SQL PL/SQL

SQL is a single query that is used to perform DML and DDL PL/SQL is a block of codes that used to write the entire
operations. program blocks/ procedure/ function, etc.

It is declarative, that defines what needs to be done, rather PL/SQL is procedural that defines how the things needs to be
than how things need to be done. done.

Execute as a single statement. Execute as a whole block.

Mainly used to manipulate data. Mainly used to create an application.

Cannot contain PL/SQL code in it. It is an extension of SQL, so it can contain SQL inside it.
SELECT TOP 1 ConsultationFees
FROM(
SELECT TOP N ConsultationFees
FROM PatientsCheckup
ORDER BY ConsultationFees DESC) AS FEES
ORDER BY ConsultationFees ASC;

SELECT ConsultationFees
FROM PatientsCheckup F1
WHERE N-1 = (
SELECT COUNT( DISTINCT ( F2.ConsultationFees ) )
FROM PatientsCheckup F2
WHERE F2.ConsultationFees > F1.ConsultationFees );
PL/SQL - Triggers
Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in
fact, written to be executed in response to any of the following events −
• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
• A database definition (DDL) statement (CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).

Benefits of Triggers
Triggers can be written for the following purposes −
• Generating some derived column values automatically
• Enforcing referential integrity
• Event logging and storing information on table access
• Auditing
• Synchronous replication of tables
• Imposing security authorizations
• Preventing invalid transactions
Creating Triggers
• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or
The syntax for creating a trigger is − replaces an existing trigger with the trigger_name.
• {BEFORE | AFTER | INSTEAD OF} − This specifies when the
CREATE [OR REPLACE ] TRIGGER trigger_name trigger will be executed. The INSTEAD OF clause is used for
{BEFORE | AFTER | INSTEAD OF } creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} • {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the
[OF col_name] DML operation.
ON table_name • [OF col_name] − This specifies the column name that will be
[REFERENCING OLD AS o NEW AS n] updated.
[FOR EACH ROW] • [ON table_name] − This specifies the name of the table
WHEN (condition) associated with the trigger.
DECLARE • [REFERENCING OLD AS o NEW AS n] − This allows you to
Declaration-statements refer new and old values for various DML statements, such
BEGIN as INSERT, UPDATE, and DELETE.
Executable-statements • [FOR EACH ROW] − This specifies a row-level trigger, i.e., the
EXCEPTION trigger will be executed for each row being affected.
Exception-handling-statements Otherwise the trigger will execute just once when the SQL
END; statement is executed, which is called a table level trigger.
• WHEN (condition) − This provides a condition for rows for
which the trigger would fire. This clause is valid only for
row-level triggers.
Example
To start with, we will be using the CUSTOMERS table we had created and used in the previous
chapters −
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
Select * from customers; FOR EACH ROW
WHEN (NEW.ID > 0)
+----+----------+-----+-----------+----------+ DECLARE
| ID | NAME | AGE | ADDRESS | SALARY | sal_diff number;
+----+----------+-----+-----------+----------+ BEGIN
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | sal_diff := :NEW.salary - :OLD.salary;
| 2 | Khilan | 25 | Delhi | 1500.00 | dbms_output.put_line('Old salary: ' || :OLD.salary);
| 3 | kaushik | 23 | Kota | 2000.00 | dbms_output.put_line('New salary: ' || :NEW.salary);
| 4 | Chaitali | 25 | Mumbai | 6500.00 | dbms_output.put_line('Salary difference: ' || sal_diff);
| 5 | Hardik | 27 | Bhopal | 8500.00 | END;
| 6 | Komal | 22 | MP | 4500.00 | /
+----+----------+-----+-----------+----------+

Old salary: 1500


New salary: 2000
Salary difference: 500
PL/SQL cursors
• Cursors in PL/SQL. Oracle creates a memory area, known as the context area, for processing an SQL
statement, which contains all the information needed for processing the statement; for example, the
number of rows processed, etc.
• A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor
holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred
to as the active set.
• User can name a cursor so that it could be referred to in a program to fetch and process the rows
returned by the SQL statement, one at a time. There are two types of cursors −
• Implicit cursors
• Explicit cursors
Implicit Cursors
• Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no
explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it.
• Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated with this
statement. For INSERT operations, the cursor holds the data that needs to be inserted. For UPDATE and DELETE
operations, the cursor identifies the rows that would be affected.
• In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has attributes such
as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The SQL cursor has additional attributes,
%BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use with the FORALL statement. The following
table provides the description of the most used attributes −
S.No Attribute & Description

%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or
a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.

%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE
2
statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise,
it returns FALSE.

%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
returned by a SELECT INTO statement.
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected
Select * from customers;
');
END IF;
+----+----------+-----+-----------+----------+
END;
| ID | NAME | AGE | ADDRESS | SALARY |
/
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
Explicit Cursors
• Explicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit cursor
should be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns
more than one row.
• The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −

• Declaring the cursor for initializing the memory


• Opening the cursor for allocating the memory
• Fetching the cursor for retrieving the data
• Closing the cursor to release the allocated memory
Declaring the Cursor
• Declaring the cursor defines the cursor with a name and the associated SELECT statement. For example −
CURSOR c_customers IS
SELECT id, name, address FROM customers;

Opening the Cursor


• Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows returned by the SQL
statement into it. For example, we will open the above defined cursor as follows −
• OPEN c_customers;

Fetching the Cursor


• Fetching the cursor involves accessing one row at a time. For example, we will fetch rows from the above-opened
cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;
Closing the Cursor
Example
• Closing the cursor means releasing the Following is a complete example to illustrate the concepts of
allocated memory. For example, we will close explicit cursors &minua;

the above-opened cursor as follows DECLARE


• CLOSE c_customers; c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
When the above code is executed at the SQL
SELECT id, name, address FROM customers;
prompt, it produces the following result −
BEGIN
OPEN c_customers;
1 Ramesh Ahmedabad
LOOP
2 Khilan Delhi
FETCH c_customers into c_id, c_name, c_addr;
3 kaushik Kota
EXIT WHEN c_customers%notfound;
4 Chaitali Mumbai
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
5 Hardik Bhopal
END LOOP;
6 Komal MP
CLOSE c_customers;
END;
PL/SQL procedure successfully completed.
/

You might also like