Unit III
Unit III
SQL
Topics Covered
• SQL commands,
• Constraints,
• Joins,
• set operations,
• Sub queries,
• Views,
• PL – SQL,
• Triggers, and Cursors.
Basics of SQL-DDL,DML,DCL,TCL Nested Queries, Views and its
Structure Creation, alternation Types
Defining Constraints-Primary Key, Foreign Key, Transaction Control Commands
Unique, not null, check, IN operator Commit, Rollback, Savepoint
Tables in SQL
Product
Tuples or rows
Tables Explained
• The schema of a table is the table name and its
attributes:
Product(PName, Price, Category, Manfacturer)
• Used to create a table by defining its structure, the data type and name of the various
columns, the relationships with columns of other tables etc.
• E.g.:
CREATE TABLE Employee(Name varchar2(20), DOB date, Salary number(6));
ALTER - Add a new attribute or Modify the characteristics of some existing attribute.
• ALTER TABLE table_name ADD (column_name1 data_type (size), column_name2 data_type (size),
….., column_nameN data_type (size));
E.g.:
ALTER TABLE Employee ADD (Address varchar2(20));
ALTER TABLE Employee ADD (Designation varchar2(20), Dept varchar2(3));
ALTER TABLE table_name MODIFY (column_name data_type(new_size));
E.g.:
E.g.:
E.g.:
TRUNCATE TABLE Employee_details;
Data Manipulation Language
E.g.:
• INSERT INTO Employee VALUES (‘ashok’, ‘16-mar-1998’, 30000);
E.g.
• CREATE TABLE Student ( ID int(6) NOT NULL, NAME varchar(10)
NOT NULL, ADDRESS varchar(20) );
UNIQUE
• This constraint helps to uniquely identify each row in the table. i.e. for a
particular column, all the rows should have unique values. We can have
more than one UNIQUE columns in a table.
E.g.
• CREATE TABLE Student ( ID int(6) NOT NULL UNIQUE, NAME
varchar(10), ADDRESS varchar(20) );
PRIMARY KEY
• Primary Key is a field which uniquely identifies each row in the table.
• If a field in a table as primary key, then the field will not be able to
contain NULL values as well as all the rows should have unique values
for this field.
• In other words we can say that this is combination of NOT NULL and
UNIQUE constraints.
• A table can have only one field as primary key.
E.g.
• CREATE TABLE Student ( ID int(6) NOT NULL UNIQUE, NAME
varchar(10), ADDRESS varchar(20), PRIMARY KEY(ID) );
FOREIGN KEY
• Foreign Key is a field in a table which uniquely identifies each row of a
another table.
• That is, this field points to primary key of another table. This usually
creates a kind of link between the tables.
• Foreign Key is used to relate two tables. The relationship between the
two tables matches the Primary Key in one of the tables with a Foreign
Key in the second table.
• This is also called a referencing key.
• We use ALTER statement and ADD statement to specify this constraint.
• In Customer_Detail table, c_id is the primary key which is set as foreign key
in Order_Detail table.
• The value that is entered in c_id which is set as foreign key in Order_Detail table
must be present in Customer_Detail table where it is set as primary key.
• This prevents invalid data to be inserted into c_id column of Order_Detail table.
• E.g.
• CREATE TABLE Student ( ID int(6) NOT NULL, NAME varchar(10)
NOT NULL, AGE int DEFAULT 18 );
Primary Key Vs Foreign Key
Primary Key Vs Unique Key
Aggregate functions in SQL
• In database management an aggregate function is a function where the
values of multiple rows are grouped together as input on certain
criteria to form a single value of more significant meaning.
Various Aggregate Functions are
• Count()
• Sum()
• Avg()
• Min()
• Max()
Count()
• Count(*): Returns total number of records .i.e 6.[select count(*) from emp;]
•
Count(salary): Return number of Non Null values over the column salary. i.e 5.
[select
Table: count(salary)
emp from emp]
• Count(Distinct Salary): Return number of distinct Non Null values over the column
salary.i.e 4 [SELECT COUNT(DISTINCT salary) FROM emp;]
• Sum()
• sum(salary): Sum all Non Null values of
Column salary i.e., 310
• sum(Distinct salary): Sum of all distinct
Non-Null values i.e., 250.
• Avg()
• Avg(salary) = Sum(salary) / count(salary) = 310/5
• Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4
• Min(), Max()
• Min(salary): Minimum value in the salary column except NULL i.e., 40.
• Max(salary): Maximum value in the salary i.e., 80.
Built in Functions - Numeric Functions in
SQL
• ABS(): It returns the absolute value of a number.
Syntax: SELECT ABS(-243.5);
Output: 243.5
• ACOS(): It returns the cosine of a number.
Syntax: SELECT ACOS(0.25);
Output: 1.318116071652818
• ASIN(): It returns the arc sine of a number.
Syntax: SELECT ASIN(0.25);
Output: 0.25268025514207865
• ATAN(): It returns the arc tangent of a number.
Syntax: SELECT ATAN(2.5);
Output: 1.1902899496825317
• CEIL(): It returns the smallest integer value that is greater than or equal to a number.
Syntax: SELECT CEIL(25.75);
Output: 26
• CEILING(): It returns the smallest integer value that is greater than or equal to a number.
Syntax: SELECT CEILING(25.75);
Output: 26
• COS(): It returns the cosine of a number.
Syntax: SELECT COS(30);
Built in Functions - Numeric Functions in SQL
• COT(): It returns the cotangent of a number.
Syntax: SELECT COT(6);
Output: -3.436353004180128
• DEGREES(): It converts a radian value into degrees.
Syntax: SELECT DEGREES(1.5);
Output: 85.94366926962348
• DIV(): It is used for integer division.
Syntax: SELECT 10 DIV 5;
Output: 2
• EXP(): It returns e raised to the power of number.
Syntax: SELECT EXP(1);
Output: 2.718281828459045
• FLOOR(): It returns the largest integer value that is less than or equal to a number.
Syntax: SELECT FLOOR(25.75);
Output: 25
• GREATEST(): It returns the greatest value in a list of expressions.
Syntax: SELECT GREATEST(30, 2, 36, 81, 125);
Output: 125
• LEAST(): It returns the smallest value in a list of expressions.
Syntax: SELECT LEAST(30, 2, 36, 81, 125);
Output: 2
• LN(): It returns the natural logarithm of a number.
Syntax: SELECT LN(2);
Output: 0.6931471805599453
• LOG10(): It returns the base-10 logarithm of a number.
Syntax: SELECT LOG(2);
Output: 0.6931471805599453
Built in Functions - Numeric Functions in
•
SQL
LOG2(): It returns the base-2 logarithm of a number.
Syntax: SELECT LOG2(6);
Output: 2.584962500721156
• MOD(): It returns the remainder of n divided by m.
Syntax: SELECT MOD(18, 4);
Output: 2
• PI(): It returns the value of PI displayed with 6 decimal places.
Syntax: SELECT PI();
Output: 3.141593
• POW(): It returns m raised to the nth power.
Syntax: SELECT POW(4, 2);
Output: 16
• RADIANS(): It converts a value in degrees to radians.
Syntax: SELECT RADIANS(180);
• RAND(): It returns a random number.
Syntax: SELECT RAND();
Output: 0.33623238684258644
• ROUND(): It returns a number rounded to a certain number of decimal places.
Syntax: SELECT ROUND(5.553);
Output: 6
• SIGN(): It returns a value indicating the sign of a number.
Syntax: SELECT SIGN(255.5);
Output: 1
• SIN(): It returns the sine of a number.
Syntax: SELECT SIN(2);
Output: 0.9092974268256817
Built in Functions - Numeric Functions in
SQL
• SQRT(): It returns the square root of a number.
Syntax: SELECT SQRT(25);
Output: 5
• ATAN2(): It returns the arctangent of the x and y coordinates, as an angle and expressed in radians.
Syntax: SELECT ATAN2(7);
Output: 1.42889927219073
• TRUNCATE(): This doesn’t work for SQL Server. It returns 7.53635 truncated to 2 places right of the
decimal point.
Syntax: SELECT TRUNCATE(7.53635, 2);
Output: 7.53
Built in Functions - String functions in SQL
• ASCII(): This function is used to find the ASCII value of a character.
Syntax: SELECT ascii('t’);
Output: 116
• CHAR_LENGTH(): Doesn’t work for SQL Server. Use LEN() for SQL Server. This function is used to find the length of a
word. Syntax: SELECT char_length('Hello!’);
Output: 6
• CHARACTER_LENGTH(): Doesn’t work for SQL Server. Use LEN() for SQL Server. This function is used to find the
length of a line.
Syntax: SELECT CHARACTER_LENGTH('geeks for geeks’);
Output: 15
• CONCAT(): This function is used to add two words or strings.
Syntax: SELECT 'Geeks' || ' ' || 'forGeeks';
Output: ‘GeeksforGeeks’
• CONCAT_WS(): This function is used to add two words or strings with a symbol as concatenating symbol.
Syntax: SELECT CONCAT_WS('_', 'geeks', 'for', 'geeks’);
Output: geeks_for_geeks
• FIND_IN_SET(): This function is used to find a symbol from a set of symbols.
Syntax: SELECT FIND_IN_SET('b', 'a, b, c, d, e, f’);
Output: 2
• FORMAT(): This function is used to display a number in the given format.
Syntax: Format("0.981", "Percent");
Output: ‘98.10%’
Built in Functions - String functions in SQL
• INSTR(): This function is used to find the occurrence of an alphabet.
Syntax: INSTR('geeks for geeks', 'e’);
Output: 2 (the first occurrence of ‘e’)
Syntax: INSTR('geeks for geeks', 'e', 1, 2 );
Output: 3 (the second occurrence of ‘e’)
• LCASE(): This function is used to convert the given string into lower case.
Syntax: LCASE ("GeeksFor Geeks To Learn");
Output: geeksforgeeks to learn
• LEFT(): This function is used to SELECT a sub string from the left of given size or characters.
Syntax: SELECT LEFT('geeksforgeeks.org', 5);
Output: geeks
• LENGTH(): This function is used to find the length of a word.
Syntax: LENGTH('GeeksForGeeks’);
Output: 13
• LOCATE(): This function is used to find the nth position of the given word in a string.
Syntax: SELECT LOCATE('for', 'geeksforgeeks', 1);
Output: 6
• LOWER(): This function is used to convert the upper case string into lower case.
Syntax: SELECT LOWER('GEEKSFORGEEKS.ORG’);
Output: geeksforgeeks.org
• LPAD(): This function is used to make the given string of the given size by adding the given symbol.
Syntax: LPAD('geeks', 8, '0’);
Output: 000geeks
Built in Functions - String functions in SQL
• LTRIM(): This function is used to cut the given sub string from the original string.
Syntax: LTRIM('123123geeks', '123’);
Output: geeks
• MID(): This function is to find a word from the given position and of the given size.
Syntax: Mid ("geeksforgeeks", 6, 2);
Output: for
• POSITION(): This function is used to find position of the first occurrence of the given alphabet.
Syntax: SELECT POSITION('e' IN 'geeksforgeeks’);
Output: 2
• REPEAT(): This function is used to write the given string again and again till the number of times mentioned.
Syntax: SELECT REPEAT('geeks', 2);
Output: geeksgeeks
• REPLACE(): This function is used to cut the given string by removing the given sub string.
Syntax: REPLACE('123geeks123', '123’);
Output: geeks
• REVERSE(): This function is used to reverse a string.
Syntax: SELECT REVERSE('geeksforgeeks.org’);
Output: ‘gro.skeegrofskeeg’
• RIGHT(): This function is used to SELECT a sub string from the right end of the given size.
Syntax: SELECT RIGHT('geeksforgeeks.org', 4);
Output: ‘.org’
• RPAD(): This function is used to make the given string as long as the given size by adding the given symbol on the right.
Syntax: RPAD('geeks', 8, '0’);
Output: ‘geeks000’
• RTRIM(): This function is used to cut the given sub string from the original string.
Syntax: RTRIM('geeksxyxzyyy', 'xyz’);
Output: ‘geeks’
• SPACE(): This function is used to write the given number of spaces.
Syntax: SELECT SPACE(7);
Output: ‘ ‘
Built in Functions - String functions in SQL
• STRCMP(): This function is used to compare 2 strings.
• If string1 and string2 are the same, the STRCMP function will return 0.
• If string1 is smaller than string2, the STRCMP function will return -1.
• If string1 is larger than string2, the STRCMP function will return 1.
Syntax: SELECT STRCMP('google.com', 'geeksforgeeks.com’);
Output: -1
• SUBSTR(): This function is used to find a sub string from the a string from the given position.
Syntax:SUBSTR('geeksforgeeks', 1, 5);
Output: ‘geeks’
• SUBSTRING(): This function is used to find an alphabet from the mentioned size and the given string.
Syntax: SELECT SUBSTRING('GeeksForGeeks.org', 9, 1);
Output: ‘G’
• SUBSTRING_INDEX(): This function is used to find a sub string before the given symbol.
Syntax: SELECT SUBSTRING_INDEX('www.geeksforgeeks.org', '.', 1);
Output: ‘www’
• TRIM(): This function is used to cut the given symbol from the string.
Syntax: TRIM(LEADING '0' FROM '000123’);
Output: 123
• UCASE(): This function is used to make the string in upper case.
Syntax: UCASE ("GeeksForGeeks");
Output: GEEKSFORGEEKS
Built in Functions - Date functions in SQL
• NOW(): Returns the current date and time.
Example: SELECT NOW();
Output:2017-01-13 08:03:52
• CURDATE(): Returns the current date.
Example: SELECT CURDATE();
Output: 2017-01-13
• CURTIME(): Returns the current time.
Example: SELECT CURTIME();
Output: 08:05:15
• DATE(): Extracts the date part of a date or date/time expression.
• EXTRACT(): Returns a single part of a date/time.
Syntax: EXTRACT(unit FORM date);
SELECT Name, Extract(DAY FROM BirthTime) AS BirthDay FROM
Test;
Built in Functions - Date functions in SQL
• DATE_ADD() : Adds a specified time interval to a date
Syntax: DATE_ADD(date, INTERVAL expr type);
SELECT Name, DATE_ADD(BirthTime, INTERVAL 1 YEAR) AS
BirthTimeModified FROM Test;
• In the query, the GROUP BY clause is placed after the WHERE clause.
• In the query, the Group BY clause is placed before the Having clause.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
GROUP BY column1, column2
Key Terms
1. function_name: Name of the function used for example, SUM() ,
AVG().
SELECT salesperson,
SUM(amount) AS total_sales
FROM Sales
GROUP BY salesperson
HAVING SUM(amount) > 13000
ORDER BY total_sales DESC;
Set Operation functions in SQL
• The SQL Set operation is used to combine the two or more SQL
SELECT statements.
• Types of Set Operation
UNION Operation
• UNION is used to combine the results of two or
more SELECT statements.
• However it will eliminate duplicate rows from its resultset.
• In case of union, number of columns and datatype must be same in both
the tables, on which UNION operation is being applied.
Union All
• Union All operation is equal to the Union operation. It returns the set
without removing duplication and sorting the data.
Intersect
• It is used to combine two SELECT statements. The Intersect operation returns the common
rows from both the SELECT statements.
• In the Intersect operation, the number of datatype and columns must be the same.
• It has no duplicates and it arranges the data in ascending order by default.
Minus
• It combines the result of two SELECT statements. Minus operator is used
to display the rows which are present in the first table but absent in the
second table.
• It has no duplicates and data arranged in ascending order by default.
Basics of SQL-DDL,DML,DCL,TCL Views and its Types
Structure Creation, alternation
Following are the important rules which must be followed by the SQL Subquery:
1. The SQL subqueries can be used with the following statements along with the SQL expression operators:
SELECT statement,
UPDATE statement,
INSERT statement, and
DELETE statement.
2. The subqueries in SQL are always enclosed in the parenthesis and placed on the right side of the SQL operators.
3. We cannot use the ORDER BY clause in the subquery. But, we can use the GROUP BY clause, which performs the same function
as the ORDER BY clause.
4. If the subquery returns more than one record, we have to use the multiple value operators before the Subquery.
5. We can use the BETWEEN operator within the subquery but not with the subquery.
Subquery with SELECT statement
In SQL, inner queries or nested queries are used most frequently with the SELECT
statement. The syntax of Subquery with the SELECT statement is described in the
following block:
Syntax:
SELECT * FROM Student_Details WHERE Stu_Marks > ( SELECT AVG(Stu_Marks ) FROM Student_Details);
Example 2
Let's take the following two tables named Faculty_Details and Department tables. The Faculty_Details table
contains ID, Name, Dept_ID, and address of faculties. And, the Department table contains the Dept_ID, Faculty_ID,
and Dept_Name.
We can insert the results of the subquery into the table of the outer
query. The syntax of Subquery with the INSERT statement is described
in the following block:
Syntax
The subqueries and nested queries can be used with the UPDATE statement in Structured
Query Language for updating the columns of the existing table. We can easily update one
or more columns using a subquery with the UPDATE statement.
Query 4: Update the emp salary by adding 5000 for the employee id
whose working in the department grade A
UPDATE Employee_Details SET Emp_Salary = Emp_Salary + 5000 WHERE
Emp_ID IN ( SELECT Emp_ID FROM Department WHERE Dept_Grade = 'A' ) ;
• DELETE FROM Student2 WHERE ROLL_NO IN ( SELECT ROLL_NO FROM Student1 WHERE LOCATION = ’chennai’);
SQL Correlated Subqueries
• Correlated subqueries are used for row-by-row processing. Each
subquery is executed once for every row of the outer query.
• A correlated subquery is evaluated once for each row processed by the
parent statement. The parent statement can be a SELECT, UPDATE,
or DELETE statement.
• A correlated subquery is one way of reading every row in a table and
comparing values in each row against related data.
• It is used whenever a subquery must return a different result or set of
results for each candidate row considered by the main query.
Nested Subqueries Versus Correlated Subqueries
• With a normal nested subquery, the inner SELECT query runs first and
executes once, returning values to be used by the main query.
• A correlated subquery, however, executes once for each candidate row
considered by the outer query. In other words, the inner query is driven by
the outer query.
NOTE : You can also use the ANY and ALL operator in a correlated
subquery.
Key Features of Corelated Queries
✅ The subquery runs for each row in the outer query.
✅ The subquery depends on values from the outer query.
✅ Often used for comparisons within the same table.
✅ Slower than normal subqueries because it runs multiple times.
When to Use Correlated Queries?
✔ Filtering based on grouped values (e.g., "higher than department
average").
✔ Checking existence conditions (e.g., "employees who earn more than
their manager").
✔ Row-by-row comparisons within the same table.
Example
• CORRELATED DELETE
• DELETE FROM table1 alias1 WHERE column1 operator (SELECT expression FROM table2 alias2 WHERE alias1.column =
alias2.column);
• Use a correlated subquery to delete rows in one table based on the rows from another table.
Processing a correlated subquery Using the Exists Operator - E.g.
• The result of the inner query can be used by the outer query
for comparison or as input data.
Syntax
Student Details CREATE VIEW view_name AS SELECT column1, column2..... FROM table_name
WHERE condition;
To see the data in the View, we can query the view in the same manner as we query a
table.
SELECT * FROM DetailsView;
Student Details 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.
Student Marks CREATE VIEW MarksView AS SELECT StudentDetails.NAME,
StudentDetails.ADDRESS,StudentMarks.MARKS FROM
StudentDetails, StudentMarks WHERE StudentDetails.NAME =
StudentMarks.NAME;
Syntax
1.The SELECT statement which is used to create the view should not include
GROUP BY clause or ORDER BY clause.
2.The SELECT statement should not have the DISTINCT keyword.
3.The View should have all NOT NULL values.
4.The view should not be created using nested queries or complex queries.
5.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.
CREATE OR REPLACE VIEW
We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a view.
Syntax
CREATE OR REPLACE VIEW view_name AS SELECT column1,coulmn2,.. FROM table_name WHERE condition;
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:
Output
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.
Syntax:
INSERT INTO view_name(column1, column2 , column3,..) VALUES(value1, value2, value3..); view_name: Name
of the View
Example:
In the below example we will insert a new row in the View DetailsView which we have created above in the
example of “creating views from a single table”.
In this example we will delete the last row from the view DetailsView which we just added in the above
example of inserting rows.
DELETE FROM DetailsView WHERE NAME="Suresh";
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView; Output
Uses of a View
1.Restricting data access
Views provide an additional level of table security by restricting access to a predetermined
set of rows and columns of a table.
2.Hiding data complexity
A view can hide the complexity that exists in a multiple table join.
3.Simplify commands for the user
Views allows the user to select information from multiple tables without requiring the users
to actually know how to perform a join.
4.Store complex queries
Views can be used to store complex queries.
5.Rename Columns
Views can also be used to rename the columns without affecting the base tables provided
the number of columns in view must match the number of columns specified in select
statement. Thus, renaming helps to to hide the names of the columns of the base tables.
6.Multiple view facility
Different views can be created on the same table for different users.
Basics of SQL-DDL,DML,DCL,TCL Nested Queries, Views and its
Structure Creation, alternation Types
Defining Constraints-Primary Key, Foreign Key, Transaction Control Commands
Unique, not null, check, IN operator Commit, Rollback, Savepoint
Atomicity − ensures that all operations within the work unit are completed
successfully. Otherwise, the transaction is aborted at the point of failure
and all the previous operations are rolled back to their former state.
Consistency − ensures that the database properly changes states
upon a successfully committed transaction.
Isolation − enables transactions to operate independently of and
transparent to each other.
Durability − ensures that the result or effect of a committed transaction
persists in case of a system failure.
Transaction Control language is a language that manages transactions within the database. It
is used to execute the changes made by the DML statements.
TCL Commands
Transaction Control Language (TCL) Commands are:
Rollback − It is used to restore the database to that state which was last committed.
Savepoint − The changes done till savpoint will be unchanged and all the transactions after
savepoint will be rolled back.
COMMIT
Transactional control commands are only used with the DML
Commands such as - INSERT, UPDATE and DELETE only.
Thus, two rows from the table would be deleted and the SELECT statement would
produce the following result.
ROLLBACK Command
Following is an example, which would delete those records from the table which
have the age = 25 and then ROLLBACK the changes in the database.
Thus, the delete operation would not impact the table and the
SELECT statement would produce the following result.
select * from customers;
Example
• Given below is an example of the usage of the TCL commands
in the database management system (DBMS)
@@ROWCOUNT returns the number of rows affected
by the last SQL statement only, which in this case is the
second UPDATE (the one with city = 'hyderabad’).
It does not return the total rows affected by both
UPDATEs.
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 −
Notice that only the first deletion took place since you rolled back to
SP2.
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:
Once a SAVEPOINT has been released, you can no longer use the
ROLLBACK command to undo transactions performed since the last
SAVEPOINT.
Difference between Commit, rollback and savepoint of
TCL commands
Basics of SQL-DDL,DML,DCL,TCL Nested Queries, Views and its
Structure Creation, alternation Types
Defining Constraints-Primary Key, Foreign Key, Transaction Control Commands
Unique, not null, check, IN operator Commit, Rollback, Savepoint
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
PL/SQL - Variables
The syntax for declaring a variable is −
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT
initial_value]
Where, variable_name is a valid identifier in PL/SQL, datatype must be a
valid PL/SQL data type
PL/SQL Control Structure
PL/SQL has a number of control structures which includes:
• Conditional controls
• Iterative or loop controls.
• Exception or error controls
• These control structure, can be used singly or together, that allow the
PL/SQL developer to direct the flow of execution through the
program.
PL/SQL Control Structure
• Conditional Controls
IF....THEN....END IF;
IF....THEN...ELSE....END IF;
IF....THEN...ELSIF....THEN....ELSE....END IF;
PL/SQL Control Structure
• LOOP
...SQL Statements...
EXIT;
END LOOP;
• WHILE loops
WHILE condition LOOP
...SQL Statements...
END LOOP;
• FOR loops
FOR <variable(numeric)> IN [REVERSE]
Assigning SQL Query Results to PL/SQL Variables
The following program assigns values from the above table to PL/SQL
variables using the SELECT INTO clause of SQL −
DECLARE
c_id customers.id%type := 1;
c_name customers.name%type;
c_addr customers.address%type;
c_sal customers.salary%type;
BEGIN
SELECT name, address, salary INTO c_name, c_addr, c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line ('Customer ' ||c_name || ' from ' || c_addr || '
earns ' || c_sal);
END;
/
It declares four PL/SQL variables:c_id is initialized to 1 and uses the data
type of customers.id.c_name, c_addr, and c_sal are declared to hold the
values from columns name, address, and salary of the customers table.
They inherit their data types using %TYPE.
Cursor
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.
• There are two types of cursors −
Implicit cursors
Explicit cursors
Implicit Cursors
%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE
statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it
2 returns FALSE.
%ISOPEN
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
3 automatically after executing its associated SQL statement.
%ROWCOUNT
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
4 returned by a SELECT INTO statement.
Example
The following program will update the employee table and increase the salary of each customer by 500
and use the SQL%ROWCOUNT attribute to determine the number of rows affected −
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 ');
END IF;
END;
Output:
6 customers selected
Example - %Found
CREATE TABLE tempory_employee AS SELECT * FROM
employees;
DECLARE
employeeNo NUMBER(4) := 2;
BEGIN
DELETE FROM tempory_employee WHERE employeeId =
employeeNo ;
IF SQL%FOUND THEN
INSERT INTO tempory_employee
(employeeId,employeeName,employeeCity) VALUES (2, 'ZZZ',
'Delhi');
END IF;
END;
/
Example for %NOTFOUND with Implicit Cursor
You want to update the salary of an employee, and then check whether any row was affected
using SQL%NOTFOUND.
BEGIN
UPDATE employees
SET salary = salary + 1000
WHERE employee_id = 105;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee found with employee_id = 105');
ELSE
DBMS_OUTPUT.PUT_LINE('Salary updated successfully.');
END IF;
END;
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.
LANGUAGE value of SQL and the BEGIN...END block, which forms the procedure body, are particular to an SQL procedure
1)The stored procedure name is UPDATE_SALARY_1.
2)The two parameters have data types of CHAR(6) and INTEGER. Both are input parameters.
3)LANGUAGE SQL indicates that this is an SQL procedure, so a procedure body follows the other parameters.
4)The procedure body consists of a single SQL UPDATE statement, which updates rows in the employee table.
Some Valid SQL Procedure Body Statements
∙ CASE statement
∙ FOR statement
∙ GOTO statement
∙ IF statement
∙ ITERATE statement
∙ RETURN statement
∙ WHILE statement
CONDITIONAL STATEMENTS:
IF <condition> THEN
<statement(s)>
ELSE
<statement(s)>
END IF;
Loops
LOOP
……
EXIT WHEN <condition>
……
END LOOP;
Example
The procedure takes two numbers using the IN mode and returns their minimum using the OUT
parameters.
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
Example 2
Write a procedure computes the square of value of a
passed value.
CREATE PROCEDURE UPDATE_SALARY_IF
(IN employee_number CHAR(6), IN rating SMALLINT)
Question
Write a stored procedure to update an LANGUAGE SQL
employee’s salary and bonus based on BEGIN
their performance rating. If the
employee’s rating is 1, increase the SET counter = 10;
salary by 10% and set a bonus of 1000. WHILE (counter > 0) DO
If the rating is 2, increase the salary by IF (rating = 1)
5% and set a bonus of 500. For any THEN UPDATE employee
other rating, increase the salary by 3%
SET salary = salary * 1.10, bonus = 1000
and set the bonus to 0. Additionally, the
update process should be repeated 10 WHERE empno = employee_number;
times using a loop." ELSEIF (rating = 2)
THEN UPDATE employee
SET salary = salary * 1.05, bonus = 500
WHERE empno = employee_number;
ELSE UPDATE employee
SET salary = salary * 1.03, bonus = 0
WHERE empno = employee_number;
END IF;
SET counter = counter – 1;
END WHILE;
END
Creating a Function
A standalone function is created using the CREATE
FUNCTION statement. The simplified syntax for the CREATE OR
REPLACE PROCEDURE statement is as follows −
• function-name specifies the name of the
function.
• [OR REPLACE] option allows the modification of
an existing function.
• The optional parameter list contains name, mode
and types of the parameters. IN represents the
value that will be passed from outside and OUT
represents the parameter that will be used to
return a value outside of the procedure.
• The function must contain a return statement.
• The RETURN clause specifies the data type you
are going to return from the function.
• function-body contains the executable part.
• The AS keyword is used instead of the IS keyword
for creating a standalone function.
Example
Write PL/SQL Function that computes and returns the
maximum of two values.
Triggers
• 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.
∙
A database definition (DDL) statement (CREATE, ALTER, or DROP).
∙
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers - Syntax
Key Terms
trigger_name: The name of the trigger to be created.
BEFORE | AFTER: Specifies whether the trigger is fired before or after the triggering event (INSERT, UPDATE,
DELETE).
{INSERT | UPDATE | DELETE}: Specifies the operation that will activate the trigger.
table_name: The name of the table the trigger is associated with.
FOR EACH ROW: Indicates that the trigger is row-level, meaning it executes once for each affected row.
trigger_body: The SQL statements to be executed when the trigger is fired.
DDL Triggers
The Data Definition Language (DDL) command events such
as Create_table, Create_view, drop_table, Drop_view, and Alter_table cause the DDL triggers to be
activated. They allow us to track changes in the structure of the database. The trigger will prevent any
table creation, alteration, or deletion in the database.
DML Triggers
• The Data manipulation Language (DML) command events
that begin with Insert, Update, and Delete set off the
DML triggers. DML triggers are used for data validation,
ensuring that modifications to a table are done under
controlled conditions.
Using SQL Triggers: Practical Use Cases
Automatically Updating Related Tables (DML Trigger
Example)
Output
This trigger ensures that no grade less than 0 or greater than 100 is
inserted into the student_grades table.
EXAMPLE
The following program creates a row-level trigger for the customers table
that would fire for INSERT or UPDATE or DELETE operations
performed on the CUSTOMERS table. This trigger will display the salary
difference between the old values and new values
•Auditing
2. Optimization
3. Evaluation
Query Processing
Query Processing (Cont.)
• Alternative ways of evaluating a given query
• Equivalent expressions
• Different algorithms for each operation
• Cost difference between a good and a bad way of evaluating a query can be enormous
• Need to estimate the cost of operations
• Depends critically on statistical information about relations which the database must
maintain
• Need to estimate statistics for intermediate results to compute cost of complex
expressions
Transaction Management
• What if the system fails?
• What if more than one user is concurrently updating the same data?
• A transaction is a collection of operations that performs a single logical function in a database
application
• Transaction-management component ensures that the database remains in a consistent
(correct) state despite system failures (e.g., power failures and operating system crashes) and
transaction failures.
• Concurrency-control manager controls the interaction among the concurrent transactions, to
ensure the consistency of the database.
Step-1
• Parser: During parse call, the database performs the following checks-
Syntax check, Semantic check and Shared pool check, after converting the
query into relational algebra.
• Parser performs the following
• Syntax check – concludes SQL syntactic validity.
• SELECT * FROM employee;
1.Semantic check – determines whether the statement is meaningful or not.
Example: query contains a tablename which does not exist is checked by this
check.
2.Shared Pool check – Every query possess a hash code during its execution.
So, this check determines existence of written hash code in shared pool if
code exists in shared pool then database will not take additional steps for
optimization and execution.
Hard Parse and Soft Parse
• If there is a fresh query and its hash code does not exist in shared pool then that query has to pass through from the additional steps
known as hard parsing
• If hash code exists then query does not passes through additional steps. It just passes directly to execution engine. This is known as
soft parsing.
Step-2
Optimizer
• During optimization stage, database must perform a hard parse at least for one unique DML statement and perform optimization during
this parse. This database never optimizes DDL unless it includes a DML component such as subquery that require optimization.
• It is a process in which multiple query execution plan for satisfying a query are examined and most efficient query plan is satisfied for
execution.
•
Database catalog stores the execution plans and then optimizer passes the lowest cost plan for execution.
• Row Source Generation
• The Row Source Generation is a software that receives a optimal execution
plan from the optimizer and produces an iterative execution plan that is
usable by the rest of the database.
• The iterative plan is the binary program that when executes by the sql
engine produces the result set.
• Step-3
Execution Engine
• Finally runs the query and display the required result.