You are on page 1of 145

SQL DML Queries

SQL Select Statement


• The SELECT statement is used to select data from
a database.
• The data returned is stored in a result table, called
the result-set.

– SELECT Syntax

– SELECT column1, column2, ...


FROM table_name;
• The SQL SELECT DISTINCT Statement

• The SELECT DISTINCT statement is used to


return only distinct (different) values.

• SELECT DISTINCT Syntax


• SELECT DISTINCT column1, column2, ...
FROM table_name;
• The SQL WHERE Clause
• The WHERE clause is used to filter records.
• It is used to extract only those records that
fulfill a specified condition.

• WHERE Syntax

• SELECT column1, column2, ...


FROM table_name
WHERE condition;
• The SQL AND, OR and NOT Operators
• The WHERE clause can be combined with AND, OR,
and NOT operators.
• The AND and OR operators are used to filter records based
on more than one condition

• The AND operator displays a record if all the conditions


separated by AND are TRUE.

• The OR operator displays a record if any of the conditions


separated by OR is TRUE.

• The NOT operator displays a record if the condition(s) is NOT


TRUE.
• AND Syntax

• SELECT column1, column2, ...


FROM table_name
WHERE condition1 AND condition2 AND condition3 ;
• OR Syntax

• SELECT column1, column2, ...


FROM table_name
WHERE condition1 OR condition2 OR condi
tion3 ...;
• NOT Syntax

• SELECT column1, column2, ...


FROM table_name
WHERE NOT condition;
• The SQL ORDER BY Keyword
• The ORDER BY keyword is used to sort the result-
set in ascending or descending order.
• The ORDER BY keyword sorts the records in
ascending order by default. To sort the records in
descending order, use the DESC keyword.
• ORDER BY Syntax
• SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Comparison Operators
Logical Operators
• The SQL BETWEEN Operator
• The BETWEEN operator selects values within a
given range. The values can be numbers, text, or
dates.
• The BETWEEN operator is inclusive: begin and
end values are included.

• BETWEEN Syntax
• SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
• Example

• SELECT * FROM Products


WHERE Price BETWEEN 10 AND 20;
The SQL LIKE Operator
• The LIKE operator is used in a WHERE clause
to search for a specified pattern in a column.
• There are two wildcards often used in
conjunction with the LIKE operator:
• The percent sign (%) represents zero, one, or
multiple characters
• The underscore sign (_) represents one,
single character
• LIKE Syntax
• SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
• Example
• The following SQL statement selects all
customers with a CustomerName starting with
"a":
• SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
• The following SQL statement selects all
customers with a CustomerName that have
"or" in any position:

• Example

• SELECT * FROM Customers


WHERE CustomerName LIKE '%or%';
• The following SQL statement selects all
customers with a CustomerName that have
"r" in the second position:

• Example
• SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
• The following SQL statement selects all
customers with a CustomerName that starts
with "a" and are at least 3 characters in
length:

• Example
• SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
• The following SQL statement selects all
customers with a ContactName that starts
with "a" and ends with "o":
• Example

• SELECT * FROM Customers


WHERE ContactName LIKE 'a%o';
• The following SQL statement selects all
customers with a CustomerName that does
NOT start with "a":
• Example

• SELECT * FROM Customers


WHERE CustomerName NOT LIKE 'a%';
• The SQL UNION Operator

• The UNION operator is used to combine the


result-set of two or more SELECT statements.

• Every SELECT statement within UNION must


have the same number of columns

• The columns must also have similar data types


• The columns in every SELECT statement must
also be in the same order

• UNION Syntax

• SELECT column_name(s) FROM table1


UNION
SELECT column_name(s) FROM table2;
• UNION ALL Syntax
• The UNION operator selects only distinct
values by default. To allow duplicate values,
use UNION ALL

• SELECT column_name(s) FROM table1


UNION ALL
SELECT column_name(s) FROM table2;
• SQL UNION Example
• The following SQL statement returns the cities
(only distinct values) from both the
"Customers" and the "Suppliers" table:
• Example
• SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
• SQL UNION ALL Example
• The following SQL statement returns the cities
(duplicate values also) from both the
"Customers" and the "Suppliers" table:
• Example
• SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
• SQL UNION With WHERE
• The following SQL statement returns the
German cities (only distinct values) from both
the "Customers" and the "Suppliers" table:
• Example
• SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
• The SQL INTERSECT clause/operator is used to
combine two SELECT statements, but returns
rows only from the first SELECT statement that
are identical to a row in the second SELECT
statement. This means INTERSECT returns only
common rows returned by the two SELECT
statements.

• Duplicate rows are eliminated unless ALL is


specified
• Syntax
• The basic syntax of INTERSECT is as follows.
• SELECT column1 [, column2 ]
• FROM table1 [, table2 ]
• [WHERE condition]
• INTERSECT
• SELECT column1 [, column2 ]
• FROM table1 [, table2 ]
• [WHERE condition]
EXCEPT Clause in SQL
• Returns all rows that are in the result of
Query1 but not in the result of Query2

• Returns only Distinct Rows.

• Duplicate rows are eliminated unless ALL is


specified
• The SQL GROUP BY Statement
• The GROUP BY statement groups rows that
have the same values into summary rows,
like "find the number of customers in each
country".
• The GROUP BY statement is often used with
aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to
group the result-set by one or more columns.
• GROUP BY Syntax
• SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
• SQL GROUP BY Examples
• The following SQL statement lists the number
of customers in each country:
• Example

• SELECT COUNT(CustomerID), Country


FROM Customers
GROUP BY Country;
Having Clause
• The HAVING clause was added to SQL because
the WHERE keyword cannot be used with
aggregate functions.
• HAVING Syntax
• SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
• The following SQL statement lists the number
of customers in each country. Only include
countries with more than 5 customers:

• SELECT COUNT(CustomerID), Country


FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
• The following SQL statement lists the number
of customers in each country, sorted high to
low:
• Example
• SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
• The SQL COUNT(), AVG() and SUM() Functions

• The COUNT() function returns the number of


rows that matches a specified criterion.

• COUNT() Syntax
• SELECT COUNT(column_name)
FROM table_name
WHERE condition;
• The AVG() function returns the average value
of a numeric column.

• AVG() Syntax
• SELECT AVG(column_name)
FROM table_name
WHERE condition;
• The SUM() function returns the total sum of a
numeric column.

• SUM() Syntax

• SELECT SUM(column_name)
FROM table_name
WHERE condition;
SQL JOIN
• A JOIN clause is used to combine rows from
two or more tables, based on a related
common column between them.

• 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 SQL JOINs
• (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
SQL INNER JOIN
• The INNER JOIN selects records that have
matching values in both tables.

• INNER JOIN Syntax


• SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
• SQL INNER JOIN Example
• The following SQL statement selects all orders
with customer information:
• Example
• SELECT Orders.OrderID,
Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID =
Customers.CustomerID;
• JOIN Three Tables
• The following SQL statement selects all orders
with customer and shipper information:
• Example
• SELECT Orders.OrderID,
Customers.CustomerName,
Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerI
D = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID =
Shippers.ShipperID);
• SQL LEFT JOIN Keyword
• The LEFT JOIN keyword returns all records from
the left table (table1), and the matching records
from the right table (table2). The result is 0
records from the right side, if there is no match.
• LEFT JOIN Syntax
• SELECT column name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
• SQL LEFT JOIN Example
• The following SQL statement will select all
customers, and any orders they might have:
• Example
• SELECT Customers.CustomerName,
Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID =
Orders.CustomerID
ORDER BY Customers.CustomerName;
• The LEFT JOIN keyword returns all records from the left table
(Customers), even if there are no matches in the right table
(Orders).
• SQL RIGHT JOIN Keyword
• The RIGHT JOIN keyword returns all records from
the right table (table2), and the matching records
from the left table (table1). The result is 0
records from the left side, if there is no match.
• RIGHT JOIN Syntax
• SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
• SQL RIGHT JOIN Example
• The following SQL statement will return all
employees, and any orders they might have
placed:
• Example
• SELECT Orders.OrderID,
Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.Employee
ID = Employees.EmployeeID
ORDER BY Orders.OrderID;
• SQL FULL OUTER JOIN Keyword
• The FULL OUTER JOIN keyword returns all records
when there is a match in left (table1) or right
(table2) table records.
• FULL OUTER JOIN Syntax
• SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
• SQL FULL OUTER JOIN Example
• The following SQL statement selects all
customers, and all orders:
• SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.Customer ID=
Orders.CustomerID
ORDER BY Customers.CustomerName;
• Note: The FULL OUTER JOIN keyword returns
all matching records from both tables whether
the other table matches or not. So, if there
are rows in "Customers" that do not have
matches in "Orders", or if there are rows in
"Orders" that do not have matches in
"Customers", those rows will be listed as well.
• SQL Self Join
• A self join is a regular join, but the table is
joined with itself.

• Self Join Syntax


• SELECT column_name(s) FROM table1 T1,
table1 T2 WHERE condition;
• SQL Self Join Example
• The following SQL statement matches customers
that are from the same city:
• Example
• SELECT A.CustomerName AS CustomerName1,
B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
Overview of Predicates (SQL)
• Use of Predicates
• A predicate is a condition expression that
evaluates to a Boolean value, either true or
false.
• Predicates can be used as follows:
• In a SELECT statement's WHERE clause
or HAVING clause to determine which rows
are relevant to a particular query. Note that
not all predicates can be used in
a HAVING clause.
• In a JOIN operation’s ON clause to determine
which rows are relevant to the join operation.

• In UPDATE or DELETE statement's WHERE clause


, to determine which rows are to be modified.

• In a DROP statement, such as DROP TABLE, to


suppress errors occurring if the target does not
exist.
• List of Predicates
• Every predicate contains one or more
comparison operators, either symbols or
keyword clauses. InterSystems SQL supports
the following comparison operators:
• Comparison OperatorDescription
• = (equals)
• <> (does not equal)
• != (does not equal)
• > (is greater than)
• >= (is greater than or equal to)
Nested Sub Queries
• In nested queries, a query is written inside a
query. The result of inner query is used in
execution of outer query.
• A subquery is a query within a query.
• Appears within where or Having clause of
other query.
• There are mainly two types of nested queries:
• Independent Nested Queries
• Co-related Nested Queries
• Independent Nested Queries: In independent
nested queries, query execution starts from
innermost query to outermost queries. The
execution of inner query is independent of
outer query, but the result of inner query is
used in execution of outer query.
• Various operators like IN, NOT IN, ANY, ALL etc
are used in writing independent nested
queries.

• Co-related Nested Queries: In co-related


nested queries, the output of inner query
depends on the row which is being currently
executed in outer query.
Select -------------------------

From --------------------------

WHERE ---------------(<,>,<=,>=,<>)
Sub=Query

HAVING ----------------(IN/ANY/ALL)
Syntax

SELECT select_list

FROM table

WHERE expr_operator(SELECT select_list FROM


table)
Independent Subquery
• A subquery is one which returns only one row
to main query.

• A subquery which uses single row operators in


above syntax is called as single row subquery

• EX: Find all employees whose salary less than


50000
• EX:List the books whose average sale of books
published by Technical is higher than overall
average sale.
SELECT NAME,AVG(sale)
FROM SALES,BOOKS
WHERE Publication = ‘Technical’
AND SALES.Bid = BOOKS.Bid
GROUP BY book_name
HAVING Avg(Sale) > ( SELECT AVG(Sale)
FROM SALES;
Multiple Row Subquery
• If subquery returns more than one row then
that type of query is known as Multiple row
sub query.

• A subquery which uses multiple row operators


in above syntax is called as multiple row
subqueries
• IN

• This multiple row operator used to check that


a given tuple in main memory satisfy at least
one values.

• NOT IN can be used to check test value is not a


member of result set of inner subquery.
ANY
• This multiple row operator used to check that
a given tuple in main memory satisfy any
value in the range

• ALL
• This multiple row operator used to check that
a given tuple in main memory satifies given
condition for all values in range
EXISTS
• TO check whether a subquery has any tuples
in the result set or not.
Set Membership
IN
-Equal to any member in the list
ANY
-Compare value to at least one value returned by
the subquery in range
ALL
-Compare value to all value returned by the
subquery in range
EXISTS
- Checks whether sub query returns a value or
not
EMP_ID FNAME DESIGNATION SALARY

101 AAA MANAGER 80000

102 DDD CLERK 20000

103 CCC CLERK 18000

104 SSS MANAGER 70000

105 RRR CLERK 16000


• EX: Find out all employees having salary not
equal to any of the manager’s salary he/she
should not be manager.

SELECT emp_id,fname,designation,salary
FROM employees
WHERE salary NOT IN
AND job_id <> ‘Manager’
PL/SQL
(Procedural Language extension to Structured
Query Language)
In Oracle database management, PL/SQL is a
procedural language extension to Structured
Query Language (SQL). The purpose of PL/SQL
is to combine database language and
procedural programming language. The basic
unit in PL/SQL is called a block and is made up
of three parts: a Declarative part, an
Executable part and an Exception-building
part.
• Because PL/SQL enables users to mix SQL
statements with procedural constructs, it is
possible to use PL/SQL blocks and
subprograms to group SQL statements before
sending them to Oracle for execution. Without
PL/SQL, Oracle must process SQL statements
one at a time. In a network environment, this
can affect traffic flow and slow down response
time. PL/SQL blocks can be compiled once
and stored in executable form to improve
response time.
• A PL/SQL program that is stored in a database
in compiled form and can be called by name is
referred to as a stored procedure. A PL/SQL
stored procedure that is implicitly started
when an INSERT, UPDATE or DELETE statement
is issued against an associated table is called
a trigger.
How PL/SQL works
• PL/SQL blocks are defined by the keywords
DECLARE, BEGIN, EXCEPTION and END, which
divide the block into a declarative part, an
executable part and an exception-building
part, respectively. The declaration section of
the block is used to define and initialize
constants and variables; if a variable is not
initialized, it will default to NULL value. Blocks
can be nested and submitted to interactive
tools, like SQL*Plus.
• PL/SQL is designed to compute and return a
single scalar value or a single collection, such
as a nested table or VARRAY. Users can create
their own functions to supplement those
provided by Oracle. While functions can be
used in an SQL statement, procedures cannot.
PL/SQL - Basic Syntax
The PL/SQL programs are divided and written in
logical blocks of code. Each block consists of
three sub-parts
Declarations
This section starts with the keyword DECLARE. It
is an optional section and defines all variables,
cursors, subprograms, and other elements to
be used in the program.
• Executable Commands
• This section is enclosed between the
keywords BEGIN and END and it is a
mandatory section. It consists of the
executable PL/SQL statements of the program.
It should have at least one executable line of
code, which may be just a NULL command to
indicate that nothing should be executed.
• Exception Handling
• This section starts with the
keyword EXCEPTION. This optional section
contains exception(s) that handle errors in the
program.
• Every PL/SQL statement ends with a
semicolon (;).
• PL/SQL blocks can be nested within other
PL/SQL blocks using BEGIN and END.
Following is the basic structure of a PL/SQL block −

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
• The PL/SQL Delimiters
• A delimiter is a symbol with a special meaning.
Following is the list of delimiters in PL/SQL
Delimiter Description

+, -, *, / Addition,
subtraction/negation,
multiplication, division
% Attribute indicator

' Character string delimiter

. Component selector

(,) Expression or list delimiter

: Host variable indicator

, Item separator
Delimiter Description

" Quoted identifier delimiter

= Relational operator

@ Remote access indicator

; Statement terminator

:= Assignment operator
Delimiter Description

=> Association operator

|| Concatenation operator

** Exponentiation operator

<<, >> Label delimiter (begin and end)

/*, */ Multi-line comment delimiter (begin and


end)
-- Single-line comment indicator

.. Range operator

<, >, <=, >= Relational operators

<>, '=, ~=, ^= Different versions of NOT EQUAL


The PL/SQL Comments

• The PL/SQL supports single-line and multi-line


comments. All characters available inside any
comment are ignored by the PL/SQL compiler.
The PL/SQL single-line comments start with
the delimiter -- (double hyphen) and multi-line
comments are enclosed by /* and */.
• PL/SQL Program Units
• A PL/SQL unit is any one of the following −
• PL/SQL block
• Function
• Package
• Package body
• Procedure
• Trigger
• Type
• Type body
PL/SQL - Data Types
• The PL/SQL variables, constants and
parameters must have a valid data type, which
specifies a storage format, constraints, and a
valid range of values.
• Scalar
• Single values with no internal components, such as
a NUMBER, DATE, or BOOLEAN.
• Large Object (LOB)
• Pointers to large objects that are stored separately
from other data items, such as text, graphic images,
video clips, and sound waveforms.
• Composite
• Data items that have internal components that can
be accessed individually. For example, collections
and records.
• Reference
• Pointers to other data items.
PL/SQL Data Types
• Number:Zero.Positive & Negative nos
• Number(P,S)
• Binary Integer
• Boolean
• Char
• Varchar
• Date
• Rowid (Returns a specific row number)
Variables
• Syntax
<var_name> <data_type> [NOT NULL] [:=<Value>];
EX: DECLARE l_total_sales NUMBER(15,2);
l_contact_name VARCHAR2(255);
• Start with an alphabet
• Combination of (A-Z),(a-z) (0-9)
• Maximum 30 characters
• No spaces in names
• No reserved words are allowed
• Constant
• <const_name> CONSTANT <data_type> :=<value>;
• EX: co_pi CONSTANT REAL := 3.14159;
Control Structures
• If else statement

– IF <condition> THEN
<Statements>
ELSE
<Statements>
END IF;
DECLARE
sales NUMBER := 300000;
commission NUMBER( 10, 2 ) := 0;
BEGIN
IF sales > 200000 THEN
commission := sales * 0.1;
ELSE
commission := sales * 0.05;
END IF;
END;
IF condition_1 THEN
statements_1
ELSIF condition_2 THEN
statements_2
[ ELSIF condition_3 THEN
statements_3
]
...
[ ELSE
else statements
]
END IF;
DECLARE
sales NUMBER := 300000;
commission NUMBER( 10, 2 ) := 0;
BEGIN
IF sales > 200000 THEN
commission := _sales * 0.1;
ELSIF sales <= 200000 AND sales > 100000 THEN
n_commission := n_sales * 0.05;
ELSIF n_sales <= 100000 AND n_sales > 50000 THEN
n_commission := n_sales * 0.03;
ELSE
n_commission := n_sales * 0.02;
END IF;
END;
• Iterative Constructs Loops

• LOOP

• WHILE-LOOP

• FOR-LOOP
LOOP Constructs

LOOP
<Sequence of statements>

END LOOP;
LOOP with EXIT
LOOP
<statements>

IF <condition> THEN

Exit;

END IF;

END LOOP;
LOOP
counter =counter + 1;

IF counter >=50 THEN

Exit;

END IF;

END LOOP;
LOOP using EXIT WHEN
LOOP
<Sequence of statements>

EXIT WHEN <Condition>;

END LOOP;
WHILE-LOOP
WHILE <Condition> LOOP

<Sequence of statements>

END LOOP;
FOR -LOOP
Stored Procedure
• A stored procedure in SQL is a group of SQL
statements that are stored together in
a database. Based on the statements in the
procedure and the parameters you pass, it can
perform one or multiple DML operations on
the database, and return value, if any. Thus, it
allows you to pass the same statements
multiple times, thereby, enabling reusability.
Benefits of using a Stored Procedure in SQL?

• Reusable: As mentioned, multiple users and


applications can easily use and reuse stored
procedures by merely calling it.

• Easy to modify: You can quickly change the


statements in a stored procedure as and when
you want to, with the help of the ALTER TABLE
command.
• Security: Stored procedures allow you to
enhance the security of an application or a
database by restricting the users from direct
access to the table.
• Low network traffic: The server only passes
the procedure name instead of the whole
query, reducing network traffic.
• Increases performance: Upon the first use, a
plan for the stored procedure is created and
stored in the buffer pool for quick execution
for the next time.
The syntax of SQL stored procedure
CREATE or REPLACE PROCEDURE
name(parameters)
AS
variables;
BEGIN;
//statements;
END;
• In the syntax mentioned above, the only thing
to note here are the parameters, which can be
the following three types:
• IN: It is the default parameter that will receive
input value from the program

• OUT: It will send output value to the program

• IN OUT: It is the combination of both IN and


OUT. Thus, it receives from, as well as sends a
value to the program
Stored Functions
• A stored function in MySQL is a set of SQL
statements that perform some task/operation
and return a single value. It is one of the types
of stored programs in MySQL. When you will
create a stored function, make sure that you
have a CREATE ROUTINE database privilege.
Generally, we used this function to
encapsulate the common business rules or
formulas reusable in stored programs or SQL
• statements.
• The stored function is almost similar to the
procedure in MySQL
• , but it has some differences that are as
follows:
• The function parameter may contain only
the IN parameter but can't allow specifying
this parameter, while the procedure can
allow IN, OUT, INOUT parameters.
• The stored function can return only a single
value defined in the function header.
• The stored function may also be called within
SQL statements.
• It may not produce a result set.
• The syntax of creating a stored function in
MySQL is as follows:

DELIMITER $$
CREATE FUNCTION fun_name(fun_parameter(s))
RETURNS datatype
[NOT] {Characteristics}
fun_body;
CURSOR
• Cursor is a Temporary Memory or Temporary
Work Station. It is Allocated by Database
Server at the Time of Performing DML(Data
Manipulation Language) operations on Table
by User. Cursors are used to store Database
Tables.
• An area of memory(Context) allocated for the
processing of SQL statements.
• Cursor is a handle or pointer to the context
area.
• Cursor in SQL
To execute SQL statements, a work area is used
by the Oracle engine for its internal processing
and storing the information. This work area is
private to SQL’s operations. The ‘Cursor’ is the
PL/SQL construct that allows the user to name
the work area and access the stored
information in it.
• Use of cursor
The major function of a cursor is to retrieve
data, one row at a time, from a result set,
unlike the SQL commands which operate on
all the rows in the result set at one time.
Cursors are used when the user needs to
update records in a singleton fashion or in a
row by row manner, in a database table.
• The Data that is stored in the Cursor is called
the Active Data Set. Oracle DBMS has another
predefined area in the main memory Set,
within which the cursors are opened. Hence
the size of the cursor is limited by the size of
this pre-defined area.
• Cursor Actions
• Declare Cursor: A cursor is declared by
defining the SQL statement that returns a
result set.
• Open: A Cursor is opened and populated by
executing the SQL statement defined by the
cursor.
• Fetch: When the cursor is opened, rows can
be fetched from the cursor one by one or in a
block to perform data manipulation.
• Cursor Actions
• Declare Cursor: A cursor is declared by
defining the SQL statement that returns a
result set.
• Open: A Cursor is opened and populated by
executing the SQL statement defined by the
cursor.
• Fetch: When the cursor is opened, rows can
be fetched from the cursor one by one or in a
block to perform data manipulation.
• Close: After data manipulation, close the
cursor explicitly.
• Deallocate: Finally, delete the cursor
definition and release all the system resources
associated with the cursor.
• Types of Cursors
Cursors are classified depending on the
circumstances in which they are opened.
• Implicit Cursor: If the Oracle engine opened a
cursor for its internal processing it is known as
an Implicit Cursor. It is created “automatically”
for the user by Oracle when a query is
executed and is simpler to code.
• Explicit Cursor: A Cursor can also be opened
for processing data through a PL/SQL block, on
demand. Such a user-defined cursor is known
as an Explicit Cursor.
• Explicit cursor
An explicit cursor is defined in the declaration
section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than
one row. A suitable name for the cursor.
• General syntax for creating a cursor:
• CURSOR cursor_name IS select_statement;
• cursor_name – A suitable name for the cursor.
select_statement – A select query which
returns multiple rows
• How to use Explicit Cursor?
• There are four steps in using an Explicit Cursor.
• DECLARE the cursor in the Declaration section.
• OPEN the cursor in the Execution Section.
• FETCH the data from the cursor into PL/SQL
variables or records in the Execution Section.
• CLOSE the cursor in the Execution Section
before you end the PL/SQL Block.
• Syntax:
DECLARE variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;
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).
• Triggers can be defined on the table, view, schema,
or database with which the event is associated.
Benefits of Triggers
• 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
• 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.
Assertions

• When a constraint involves 2 (or) more tables,


the table constraint mechanism is sometimes
hard and results may not come as expected.
To cover such situation SQL supports the
creation of assertions that are constraints not
associated with only one table.
• An assertion statement should ensure a
certain condition will always exist in the
database. DBMS always checks the assertion
whenever modifications are done in the
corresponding table.
• Syntax –
• CREATE ASSERTION [ assertion_name ]
• CHECK ( [ condition ] );
Ex: There should not any customer in bank
having balance less than 1000.

Create Assertion c1 Check

( NOT EXISTS (

Select * From customer Where balance<1000));


Difference between Assertions and
Triggers :
Assertions Triggers
1. Assertions can be used 1. Triggers even particular
when we know that the condition may or may not
given particular condition be true.
is always true.
2. When the SQL condition is 2. Triggers can catch errors if
not met then there are the condition of the query
chances to an entire table is not true.
or even Database to get
locked up.
3. Assertions are not linked 3. It helps in maintaining the
to specific table or event. It integrity constraints in the
performs task specified or database tables, especially
defined by the user. when the primary key and
foreign key constraint are
not defined.

4. Assertions do not maintain 4. Triggers maintain track of


any track of changes made all changes occurred in
in table. table.
5. Modern databases do not 5. Triggers are very well used
use Assertions. in modern databases.
Roles and Privileges
• A role is created to ease setup and
maintenance of the security model. It is a
named group of related privileges that can be
granted to the user.
• Privileges: It defines the access rights to
database users on database objects
(Functions,Procedures or Tables)
• You can grant or revoke privileges to users,
thereby automatically granting or revoking
privileges.
• You can either create Roles or use the system
roles pre-defined.
• Creating and Assigning a Role –
• First, the (Database Administrator)DBA must
create the role. Then the DBA can assign
privileges to the role and users to the role
• Syntax –
– CREATE ROLE manager;
– Role created.
• Now that the role is created, the DBA can use
the GRANT statement to assign users to the
role as well as assign privileges to the role.
• It’s easier to GRANT or REVOKE privileges to
the users through a role rather than assigning
a privilege directly to every user.
• If a role is identified by a password, then
GRANT or REVOKE privileges have to be
identified by the password.
• Grant privileges to a role –
• GRANT create table, create view TO manager;
• Grant a role to users
• GRANT manager TO SAM, STARK; Grant
succeeded. Grant a role to users
• GRANT manager TO SAM, STARK; Grant
succeeded.
• Revoke privilege from a Role :
• REVOKE create table FROM manager;
• Drop a Role :
• DROP ROLE manager;
Privileges
Database security:
• System security
• Data security
System privileges: Gaining access to the
database .
Object privileges: Manipulating the content of
the database objects
Schemas: Collection of objects such as tables,
views, and sequences
System Privileges
More than 100 privileges are available.
The database administrator has highlevel
system privileges for tasks such as:
Creating new users
Removing users
Removing tables
Backing up tables
Object Privileges
Object privileges vary from object to object.

An owner has all the privileges on the object.

An owner can give specific privileges on that


owner’s object.

GRANT object_priv [(columns)] ON object TO


{user|role|PUBLIC} [WITH GRANT OPTION];
Embedded SQL

• Embedded SQL is a method of combining the


computing power of a programming language
and the database manipulation capabilities
of SQL. Embedded SQL statements are SQL
statements written inline with the program
source code, of the host language.
Types of Embedded SQL
• There are two types of embedded SQL
statements: executable and declarative.
Executable statements result in calls to Oracle
and return codes and data from Oracle. You
use them to connect to Oracle, to define,
query, manipulate, and control access to
Oracle data, and to process transactions
Advantages of Embedded SQL
• Helps to access databases from anywhere.
• Allows integrating authentication service for
large scale applications.
• Provides extra security to database
transactions.
• Avoids logical errors while performing
transactions on our database.
• Makes it easy to integrate the frontend and
the backend of our application.
Dynamic SQL
• Dynamic SQL is a programming technique
that enables you to build SQL statements
dynamically at runtime. You can create more
general purpose, flexible applications by using
dynamic SQL because the full text of a SQL
statement may be unknown at compilation.

You might also like