0% found this document useful (0 votes)
28 views35 pages

Ch.2.advanced SQL

Uploaded by

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

Ch.2.advanced SQL

Uploaded by

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

SQL | SEQUENCES

• SQL sequences specifies the properties of a sequence object while


creating it.
• An object bound to a user-defined schema called a sequence
produces a series of numerical values in accordance with the
specification used to create it.
• The series of numerical values can be configured to restart (cycle)
when it runs out and is generated in either ascending or descending
order at a predetermined interval.
Different Features of Sequences
• A sequence is a database object that generates and produces integer values in
sequential order.
• It automatically generates the primary key and unique key values.
• It may be in ascending or descending order.
• It can be used for multiple tables.
• Sequence numbers are stored and generated independently of tables.
• It saves time by reducing application code.
• It is used to generate unique integers.
• It is used to create an auto number field.
• Useful when you need to create a unique number to act as a primary key.
• Oracle provides an object called a Sequence that can generate numeric values.
The value generated can have maximum of 38 digits.
Creating a Sequence
Syntax to create a sequence is,
Syntax:- CREATE SEQUENCE sequence-name
START WITH initial-value
INCREMENT BY increment-value
MAXVALUE maximum-value
CYCLE | NOCYCLE;
•The initial-value specifies the starting value for the Sequence.
•The increment-value is the value by which sequence will be
incremented.
•The maximum-value specifies the upper limit or the maximum value
upto which sequence will increment itself.
•The keyword CYCLE specifies that if the maximum value exceeds the set
limit, sequence will restart its cycle from the begining.
•And, NO CYCLE specifies that if sequence exceeds MAXVALUE value, an
error will be thrown.
Using Sequence in SQL Query
which will start from 1, increment by 1 with a maximum value of 999.

CREATE SEQUENCE seq_1


START WITH 1
INCREMENT BY 1
MAXVALUE 999
CYCLE;
• Now let's use the sequence that we just created above.
• Below we have a class table,

ID NAME
1 abhi
2 adam
4 alex
The SQL query will be,
• INSERT INTO class VALUE(seq_1.nextval, 'anu');
• Result set table will look like,
ID NAME
1 abhi
2 adam
4 alex
1 anu

• Once you use nextval the sequence will increment even


if you don't Insert any record into the table.
SQL VIEW
• A VIEW in SQL is a logical subset of data from one or more tables. View is used to
restrict data access.
• Syntax for creating a View,
CREATE or REPLACE VIEW view_name
AS
SELECT column_name(s)
FROM table_name
WHERE condition
As you may have understood by seeing the above SQL query, a view is created using
data fetched from some other table(s).
It's more like a temporary table created with data.
Creating a VIEW
Consider following Sale table,
oid order_name previous_balance Customer
11 ord1 2000 Alex
12 ord2 1000 Adam
13 ord3 2000 Abhi
14 ord4 1000 Adam
15 ord5 2000 Alex

SQL Query to Create a View from the above table will be,
CREATE or REPLACE VIEW sale_view
AS
SELECT * FROM Sale WHERE customer = 'Alex';

The data fetched from SELECT statement will be stored in another


object called sale_view.
We can use CREATE and REPLACE seperately too, but using both
together works better, as if any view with the specified name exists,
this query will replace it with fresh data.
Displaying a VIEW

The syntax for displaying the data in a view is similar to fetching data from a table using
a SELECT statement.
SELECT * FROM sale_view;
SYSNONYM

• The SYSNONYM is the alternative name or the alias name for the database
objects so the same database object can be referred by different names without
using the complex names that are defined before. The SYNONYM can be created
for the tables, stored procedures, user-defined functions, or any database
objects.
• The SYNONYMS becomes invalid when:
• The base table is dropped.
• The name of the base table is changed.
• Creating a synonym for a synonym is not possible.
PL/SQL Introduction

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 DDL operations. PL/SQL is a block of codes that used to write the entire program blocks/
procedure/ function, etc.

It is declarative, that defines what needs to be done, rather than how things PL/SQL is procedural that defines how the things needs to be done.
need to be 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.
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.
A block has the following structure:
A block has the following structure: • It supports all DML commands, DDL commands and
DECLARE SQL*PLUS built-in functions as well.
declaration statements; • Exception section starts with EXCEPTION keyword.
BEGIN • This section is optional which contains statements that
executable statements EXCEPTIONS are executed when a run-time error occurs.
exception handling statements • Any exceptions can be handled in this section.
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.
SQL> SET SERVEROUTPUT ON;

SQL> DECLARE
var1 INTEGER;
var2 REAL;
var3 varchar2(20) ;

BEGIN
null;
END;
/

OUTPUT:-
PL/SQL procedure successfully completed.
PL/SQL code to print sum of two numbers taken from the user.
--SQL> SET SERVEROUTPUT ON;

SQL> DECLARE

-- taking input for variable a


a integer := &a ;

-- taking input for variable b


b integer := &b ;
c integer ;

BEGIN
c := a + b ;
dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c);

END;
/

OUTPUT:-
Enter value for a: 2
Enter value for b: 3
Sum of 2 and 3 is = 5

PL/SQL procedure successfully completed.


SQL Stored Procedures

• A stored procedure in SQL is a group of SQL queries that can be saved and reused multiple times. It is very useful as it
reduces the need for rewriting SQL queries. It enhances efficiency, reusability, and security in database management.
• Users can also pass parameters to stored procedures so that the stored procedure can act on the passed parameter values.
• Stored Procedures are created to perform one or more DML operations on the Database. It is nothing but a group of SQL
statements that accepts some input in the form of parameters, performs some task, and may or may not return a value.

• Syntax
Syntax to Create a Stored Procedure
CREATE PROCEDURE procedure_name
(parameter1 data_type, parameter2 data_type, …)
AS
BEGIN
— SQL statements to be executed
END

• OUTPUT:-
• EXEC procedure_name parameter1_value, parameter2_value, ..
-- Create a new database named "SampleDB" (5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain');
CREATE DATABASE SampleDB; Output:
-- Create a stored procedure named
-- Switch to the new database "GetCustomersByCountry"
USE SampleDB; CREATE PROCEDURE GetCustomersByCountry
@Country VARCHAR(50)
-- Create a new table named "Customers" AS CustomerName Contact Name
CREATE TABLE Customers ( BEGIN
CustomerID INT PRIMARY KEY, SELECT CustomerName, ContactName
CustomerName VARCHAR(50), FROM Customers
ContactName VARCHAR(50), WHERE Country = @Country;
Country VARCHAR(50) END; Naveen Tulasi
);
-- Execute the stored procedure with parameter "Sri lanka"
-- Insert some sample data into the Customers table EXEC GetCustomersByCountry @Country = 'Sri lanka';
INSERT INTO Customers (CustomerID, CustomerName,
ContactName, Country)
VALUES (1, 'Shubham', 'Thakur', 'India'),
(2, 'Aman ', 'Chopra', 'Australia'),
(3, 'Naveen', 'Tulasi', 'Sri lanka'),
(4, 'Aditya', 'Arpan', 'Austria'),
SQL Trigger

• trigger is a stored procedure in a database that 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 specific table columns are updated. In simple words, a trigger is a
collection of SQL statements with particular names that are stored in system
memory.
• It belongs to a specific class of stored procedures that are automatically invoked
in response to database server events. Every trigger has a table attached to it.
• Because a trigger cannot be called directly, unlike a stored procedure, it is
referred to as a special procedure.
• A trigger is automatically called whenever a data modification event against a
table takes place, which is the main distinction between a trigger and a
procedure.
• On the other hand, a stored procedure must be called directly.
The following are the key differences between triggers and
stored procedures:
• Triggers cannot be manually invoked or executed.
• There is no chance that triggers will receive parameters.
• A transaction cannot be committed or rolled back inside a trigger.

We can classify this trigger further into three types:


• AFTER INSERT Trigger
• AFTER UPDATE Trigger
• AFTER DELETE Trigger
Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
CREATE [OR REPLACE ] TRIGGER
trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE Declaration-statements
BEGIN Executable-statements
EXCEPTION Exception-handling-
statements
END;
• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an
existing trigger with the trigger_name.
• {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The INSTEAD OF clause is used for creating trigger on a view.
• {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
• [OF col_name] − This specifies the column name that will be updated.
• [ON table_name] − This specifies the name of the table associated with the trigger.
• [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old
values for various DML statements, such as INSERT, UPDATE, and DELETE.
• [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL 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.
• Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
Example
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );
When a record is created in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following
result −
Old salary: New salary: 7500
Salary difference:
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
Old salary: 1500
New salary: 2000
Salary difference: 500
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 are automatically created by Oracle whenever an SQL
statement is executed, when there is no explicit cursor for the
statement.
• S.No Attribute & Description
1 %FOUND 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.

2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or


%NOTFOUND DELETE statement affected no rows, or a SELECT INTO statement returned no
rows. Otherwise, it returns FALSE.

3 %ISOPEN Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.

4 %ROWCOUNT Returns the number of rows affected by an INSERT, UPDATE, or DELETE


statement, or returned by a SELECT INTO statement.
• Let’s consider a table named student, as given below.
• CursorinSQL_1.
• Now, using the below program, we’ll update the table
by decreasing the salary of each below by 1000.
SQL %ROWCOUNT attribute
• 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
PL/SQL procedure successfully completed.
Now, if we see our table, the rows have been updated and the salary of each

employee has been reduced by 1000 .


Explicit Cursor
n explicit cursor is a programmer-defined cursor that is created
hen we are executing a SELECT statement returning more than one r
ven though the cursor stores several records simultaneously, only on
ontext area.
he syntax for defining an explicit cursor-

CURSOR cursor_name IS select_statement;


In the above code, we declare the cursor as
s_student, and it is used to fetch the id, name and
address of each student in the database.

Output:-

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy