You are on page 1of 94

STRUCTURED QUERY

LANGUAGE (SQL)
TAIYE AHMED

An Experienced Data Analyst with a robust


background spanning over five years across the
telecommunications, banking, and corporate sectors.
Proficient in delivering comprehensive BI and data

Trainer
analytics solutions, leveraging expertise in, database
management, data warehousing technologies, data
modeling, data visualization, ETL, Big Data, and
Cloud analytics technologies.
Musefiu Adekunle

I am a seasoned Data Engineer and Business Intelligence Specialist, well-


versed in Data Warehousing and Business Intelligence methodologies using
a variety of tools including Oracle, Microsoft, Python, and other cloud-based

Trainer
and on-premise BI platforms. Additionally, I possess a strong proficiency in
ERP Systems such as Oracle, SAP, Odoo, and ERPNext.
Over the span of six years, I have honed my expertise while contributing to
diverse industries including banking, telecommunications, government, and
logistics. My professional journey has equipped me with a solid foundation
and adaptability to thrive in multifaceted environments.
Content

Environment Set-up

Introduction to Data Analytics

Introduction to Database, Data warehouse and SQL SQL

Queries

SQL Examples I

Analytic Function

Database Objects

SQL Joins

Common Table Expressions

SQL Constraints and Loops

SQL ExamplesII

3
Environment Set-up
Environment Set-up
• Please go to:
https://www.dropbox.com/sh/jka
6tzvoh9r1za3/AAD1JuVpa0Ox
W1u8gV3fEOBAa?dl=0
• For Windows users, scroll down
to the end of the page and click
on Download now (see image
attached)
• For Mac user, virtual Machine
will be required to install
window.
• An application file named
OracleXE would be
downloaded

6
Environment Set-up
Install the Oracle Database 10g Express
The installation dialog

Click the Next button to begin to install the Oracle Database 10g Express Edition. Select and click the Accept radio button followed by clicking the
Next button to go to the next page. Click the Next button to open the next dialog.
In the next dialog, you need to enter your password. You must remember this password since you need to use it to access your database installed
in the Oracle server from your client computer later. The username is SYSTEM by default.

7
Environment Set-up
The installation finishing dialog The Database Login page

When this installation is complete, a finish dialog is displayed, which is shown in Figure C-3. Click the Finish button to complete this
installation. The Database Login page is opened to allow you to enter your username and password to access the Oracle server to
create, access and manipulate the database you created in this server.

8
Environment Set-up
The Database home page

Enter the SYSTEM as your username and the password you selected when you installed the server, and then click the
Login button to open the home page. There are four icons on the opened home page

9
Introduction to Data
Analytics
What is Data Analytics?

Data analytics helps you to


Data analytics is the make sense of the past and
process of analyzing raw to predict future trends and
data in order to draw out behaviors; rather than basing
meaningful, actionable your decisions and strategies
insights, which are then on guesswork, you’re
used to inform and drive making informed choices
smart business decisions. based on what the data is
telling you.
Data Analytics
Roadmap

12
Introduction to Database

A database is an organized collection of data

A database-management system (DBMS) is a computer software that interacts with end-users,


other applications, and the database itself to capture and analyze data. A general-purpose DBMS allows
the definition, creation, querying, update, and administration of databases.

Well-known DBMSs
include MySQL, PostgreSQL, EnterpriseDB, MongoDB, MariaDB, Microsoft SQL
Server, Oracle, Sybase, SAP HANA, MemSQL, SQLite and IBM DB2.

Rows/Columns – Records/Fields

Database is a collection of schemas, tables, queries, reports, views, and other


elements

13
Introduction to Datawarehouse

A data warehouse is a relational It is designed for query and analysis


database designed to enable business rather than for transaction processing, and
intelligence activities: it exists to help usually contains historical data derived
users understand and enhance their from transaction data, but can include data
from other sources
organization's performance

Data Warehouse helps in: In addition to a relational database, a data


• Maintaining historical records warehouse environment can include an
• Analyzing the data to gain a better understanding of Extraction, Transformation, and Loading
the business and to improve the business (ETL) solution, statistical analysis, reporting,
data mining capabilities, client analysis tools,
and other applications that manage the
process of gathering data, transforming it into
useful, actionable information, and delivering
it to business users.

14
Key Characteristics of a Datawarehouse

Data is structured
End users are time-
for simplicity of
sensitive and desire
access and high-
speed-of-thought
speed query
response times.
performance.

Queries often
Large amounts of retrieve large
historical data are amounts of data,
used. perhaps many
thousands of rows.

15
Data Warehouse Logical Architecture

16
Introduction to SQL
Introduction to SQL - Definition

SQL is a standard language for


SQL stands for Structured
accessing and manipulating
Query Language
databases

What Can SQL do?


• SQL can execute queries against a database
• SQL can retrieve data from a database
• SQL can insert records in a database
• SQL can update records in a database
• SQL can delete records from a database
• SQL can create new databases
• SQL can create new tables in a database
• SQL can create stored procedures in a
database
• SQL can create views in a database
• SQL can set permissions on tables, procedures,
and views etc

18
Introduction to SQL - Languages

Data definition
Data manipulation
language(DDL) – defines
language (DML) – performs
data types such as creating,
tasks such as inserting,
altering, or dropping and the
updating, or deleting data
relationships among them
occurrences

Data Query language Data Control language


(DQL) – allows searching (DCL) – gives and takes
for information and back roles, privileges from
computing derived user
information
19
Introduction to SQL – Database Objects

A schema is a collection of database


A database object is any defined objects associated with one particular
object in a database that is used to database username. This username is
store or reference data. Some called the schema owner, or the owner
Database objects are the underlying examples of database objects include of the related group of objects.
backbone of the relational database tables, views, functions, You may have one or multiple schemas
procedures, packages, in a database. The user is only
sequences, indexes, and associated with the schema of the same
synonyms name and often the terms will be used
interchangeably

A database view is a searchable


The table is the primary storage object
object in a database that is defined by
for data in a relational database. In its
a query. Though a view doesn't store
simplest form, a table consists of row(s)
data, some refer to a views as “virtual
and column(s), both of which hold the
tables,” you can query
data. A table takes up physical space in a a view like you can a table.
database and can be permanent or
A view can combine data from two or
temporary.
more table, using joins, and also just
contain a subset of information.

20
Introduction to SQL – Database Objects
(contd.)

A stored function (also called a A procedure is a group of PL/SQL or


user function or user- TSQL statements that you can call by name. A package is an encapsulated collection of
defined function) is a set of PL/SQL A call specification (sometimes called call related procedures, functions, and other
spec) declares a Java method or a third- program objects stored together in the
or TSQL statements you can call by generation language (3GL) routine so that it database. The package specification
name. Stored functions are very can be called declares these objects.
similar to procedures, except that from SQL and PL/SQL. The call spec The package body, specified
a function returns a value to the tells Oracle Database which Java subsequently, defines these objects
environment in which it is called. method to invoke when a call is made.

An index is a schema object that contains


A sequence is a database object from
an entry for each value that appears in the
which multiple users may generate unique
indexed column(s) of the table or cluster
integers. You can use sequences to
and provides direct, fast access to rows.
automatically generate primary key values
Oracle Database supports several types of
index

21
Introduction to SQL – RDBMS Concepts
•RDBMS stands for Relational Database Management System. RDBMS is the
basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2,
Oracle, MySQL, and Microsoft Access.

•A Relational database management system (RDBMS) is a database


management system (DBMS) that is based on the relational model as
introduced by E. F. Codd.

• Data Integrity
The following categories of data integrity exist with each RDBMS −
• Entity Integrity − There are no duplicate rows in a table.
• Domain Integrity − Enforces valid entries for a given column by
restricting the type, the format, or the range of values.
• Referential integrity − Rows cannot be deleted, which are used by other
records.
• User-Defined Integrity − Enforces some specific business rules that do
not fall into entity, domain or referential integrity.

22
Introduction to SQL – Data Types

23
SQL Queries – Constraints

SQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures
the accuracy and reliability of the data in the table. If there is any violation
between the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
Not null- Ensures that a column cannot have a NULL value
Unique- Ensures that all values in a column are different
Primary Key- A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
Foreign Key- Uniquely identifies a row/record in another table
Check-Ensures that all values in a column satisfies a specific condition

76
Introduction to SQL – SQL Operators

25
SQL Queries
SQL Queries

These are the statements that are used to perform actions on a


database. Some of these actions include:
• SQL Create
• SQL Alter
• SQL Drop
• SQL Insert
• SQL Update
• SQL Delete
• SQL Select
• SQL Truncate
• SQL And & Or Clause
• SQL Joins
• SQL Like
• SQL Between
• SQL Order By etc.
• SQL Case Statements

27
SQL Queries -
Create
Create
This is used to create an object in a database. Objects
that can be created include tables, views, sequence,
database. The syntax to create a table is:

Create table tablename(column1 datatype,


Column2 datatype,
column3 datatype,
……..,
columnN datatype,
Primary key(one or
more columns));

28
SQL Queries -
Drop
Alter
This is used to edit the structure of an
object( table, index, sequence, database, view,
procedure etc) from a database.
The syntax are:

Alter object objectname


Modify columnname datatype ;

For example, to change the datatype of


customer_name column in table customer,
run the query :
alter table customer
Modify customer_name varchar(300);

29
SQL Queries -
Drop
Drop
This is used to delete and completely remove
an object( table, index, sequence, database,
view, procedure etc) from a database.
This removes the contents of the objects as
well as the structure. The syntax is:

Drop object objectname;

For example, to drop a table named


customer, run the query : drop table
customer;

30
SQL Queries -
Select

Select
This is used to fetch records from a table.
The basic syntax is:
Select * from tablename;
Select col1, col2, coln from tablename;

31
SQL Queries -
Delete

Delete
This is used to delete the records of a table
when a condition is satisfied . The syntax is:

Delete from tablename


Where {condition};

32
SQL Queries -
Truncate

Truncate
This is used to delete all the records of a table
without deleting the table structure . It is used
to empty a table . The syntax is:

Truncate table tablename;

33
SQL Queries – And / Or Clause
And / Or Clause
This is used to perform an action on a table that satisfies more than one
condition.
The OR clause is used when either of one or more condition is to be satisfied. An
example for the AND clause is:
Select column1,column2…,column
From tablename
Where condition1=value
and condition2=value;
This will return records from
the table that meet the two
conditions given.
Select column1,column2…,column
From tablename
Where condition1=value
or condition2=value;
This will return records from the table that meet either of the two conditions given.
34
SQL Queries – Insert Into
Insert Into
This is used to insert new records in a table An
example is:

INSER
T INTO table_name (column1, column2,
column3, ...)
VALUE
S (value1, value2, value3, ...);

If you are adding values for all the columns


of the table, you do not need to specify the column names in the SQL query.
However, make sure the order of the values is in the same order as the columns in
the table. Here, the INSERT INTO syntax would be as follows:

INSERT INTO table_name


VALUES (value1, value2, value3, ...);

35
SQL Queries – Update

Update
This is used to modify the existing records in a
table.
An example is:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

36
SQL Queries – Between

Between
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. An
example is:
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND
value2;

37
SQL Queries – Sum

Sum
The SUM() function returns the total sum of a numeric column. The
syntax is:
Select sum(columnname)
from tablename;
The sum function can also be
shown by a column(s). In this
case, a function
called group by will be added
to the SQL statement.
Select column1,sum(columnname) from
tablename
group by column1;

38
SQL Queries –
Count

Count
The count() function returns the number of rows that matches a specified criteria
. The syntax is:
select count(column_name)
from table_name
where condition;
The count function can also be done and shown by a column(s).The group by
function will also be added to the SQL statement . For example:
select column1,count(columnname)
from tablename
group by column1;

39
SQL Queries – Average

Average
The avg() function returns the average value of a numeric column . The syntax is:
select avg(column_name)
from table_name;

40
SQL Queries –
Merge Merge
The merge statement is used to make changes in one table based on values matched
from anther. It can be used to combine insert, update, and delete
operations into one statement. The merge statement can combine insert, delete, and
update operations into one table. An example is:
merge table1
Using table2
on
(table1.colum
n1=table2.col
umn2)
When matched then
update table1
set table1.column2=table2.column1,
table1.column3=table2.column3
When not matched then
insert into table1(column2,column3) 41

Values value1,value2;
SQL
Queries
Examples I
SQL Queries – Examples

• Display details of jobs where the minimum salary is greater than


10000.
• Display the first name and join date of the employees who joined
between 2002 and 2005.
• Display first name and join date of the employees who is either IT
Programmer or Sales Man.
• Display employees who joined after 1st January 2008.
• Display details of employee with ID 150 or 160.
• Display first name, salary, commission pct, and hire date for
employees with salary less than 10000.
• Display job Title, the difference between minimum and maximum
salaries for jobs with max salary in the range 10000 to 20000.
• Display first name, salary, and round the salary to thousands.
• Display details of jobs in the descending order of the title.
• Display employees where the first name or last name starts with S

43
Database Objects
Database Objects
Database Objects
These are the elements resident in a database. Some of these elements include:
• Schemas
• Constraints
• Database triggers
• Materialized views
• Index
• Sequences
• Stored functions
• Stored procedures
• Tables
• Views

45
Database Objects -
Schema

Schema
A schema is a collection of logical structures of data, or schema objects. A schema is
owned by a database user and has the same name as that user. Each user owns a
single schema. Schema objects can be created and manipulated with SQL and
contain different database objects.

46
Database Objects –
Views

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

47
Database Objects – Sequence

Sequence
It automatically increments the column value by 1 each time a new record is entered
into the table. The syntax is:
CREATE Sequence sequence_name
start with initial-value increment
by increment-value maxvalue
maximum-value

48
Database Objects – Stored Functions
Stored Function
A standalone function is created using the CREATE FUNCTION statement.
CREATE [OR REPLACE] FUNCTION function_name [(parameter_name [IN |
OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body > END
[function_name];

49
Database Objects – Stored Functions (contd.)
Stored Function
Where,
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.

50
Database Objects – Stored Procedures
Stored Procedure
A procedure/subprogram is a program unit/module that performs a particular task. A
procedure does not return a value directly; mainly used to perform an action . The
syntax is:
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;

51
Analytics Functions
Analytic Functions - Rank
These are functions that are used to perform more complex reasoning in SQL . Some of these functions include Rank, Dense Rank ,
Row_number , Lead , Lag and so on.

Rank
The rank function returns the rank of each row of a query with respective to the other
rows . The Rank function returns a numeric value . The syntax is:
Rank() over ( [ query_partition_clause] order by clause ) . For
Example:
select employee_name, salary , rank() over (partition by department order by salary)
from employees where department = 'Marketing';
The SQL statement above would return all employees who work in the Marketing
department and then calculate a rank for each unique salary in the Marketing
department. If two employees had the same salary, the rank function would return the
same rank for both employees.

53
Analytic Functions - Dense Rank
Dense Rank
The dense_rank function returns the rank of a row in a group of rows. It is very similar
to the rank function. However, rank function can cause non- consecutive rankings if
the tested values are the same. Whereas, the dense_rank function will always result
in consecutive rankings.
The syntax is:
Dense_rank() over ( [ query_partition_clause] order by clause )
For example:
select employee_name, salary , dense_rank() over(partition by department order
by salary) from employees where department = 'Marketing';
The SQL statement above would return all employees who work in the Marketing
department and then calculate a rank for each unique salary in the Marketing
department. If two employees had the same salary, the dense_rank function would
return the same rank for both employees.

54
Analytic Functions - Row_number

Row_number
It assigns a unique number to each row to which it is applied (either each row in the
partition or each row returned by the query), in the ordered sequence of rows
specified in the order_by_clause, beginning with 1.The syntax is:
Select column1, row_number() over(order by columnname) from tablename;

55
Analytic Functions - Lag

Lag
The lag function is used to access data from a previous row . The syntax is: lag
(value_expression [,offset] ) over ([query_partition_clause]
order_by_clause).

56
Analytic Functions - Lead

Lead
The lead function is used to return data from the next row . The syntax is : LEAD
(value_expression [,offset]) OVER ([query_partition_clause]
order_by_clause)
value_expression - Can be a column or a built-in function, except for other
analytic functions.
offset - The number of rows preceeding /following the current row, from which the
data is to be retrieved. The default value is 1.

57
SQL Joins
SQl
Joins Joins

A join clause is used to combine rows from two or more tables, based on a related
column between them. The are different types of SQL joins:
• Equi-join / Inner Join
• Left Outer Join
• Right Outer Join
• Full Outer Join
• Self Join

59
SQl Joins – Equi-join / Inner Join
Equi-join / Inner Join

The INNER JOIN keyword selects records that have matching values in both tables.
The syntax is:
Select column_name(s)
from table1 a, table2 b
Where a.column_name =
b.column_name;

60
SQl Joins – Left Outer Join

Left Outer Join

The left outer join keyword returns all records from the left table (table1), and the
matched records from the right table (table2). The result is NULL from the right side,
if there is no match . The syntax is:
SELECT column_name(s)
FROM table1 a left outer join
table2 b on a.column_name = b.column_name;

61
SQl Joins – Right Outer Join

Right Outer Join

The right outer join keyword returns all records from the right table (table2), and the
matched records from the left table (table1). The result is NULL from the left side,
when there is no match . The syntax is:
SELECT column_name(s)
FROM table1 a right outer join
table2 b on a.column_name = b.column_name

62
SQl Joins – Full Outer Join

Full Outer Join

The full outer join keyword return all records when there is a match in either left
(table1) or right (table2) table records.

Select column_name(s)
from table1 a full outer join
table2 b on a.column_name = b.column_name;

63
SQl Joins – Self
Join

Self Join

A self join is a regular join, but the table is joined with itself.

Select column_name(s)
from table1 a,
table1 b
Where
a.column_name =
b.column_name;

64
Common Table
Expressions
Common Table Expressions – CTEs
CTEs

CTE stands for common table expression. A CTE allows you to define a temporary named result set that
available temporarily in the execution scope of a statement such
as SELECT, INSERT, UPDATE, DELETE, or MERGE.
The following shows the common syntax of a CTE :

WITH expression_name[(column_name [,...])] AS (CTE_definition) SQL_statement;

In this syntax:
• First, specify the expression name (expression_name) to which you can refer later in a query.
• Next, specify a list of comma-separated columns after the expression_name. The number of columns
must be the same as the number of columns defined in the CTE_definition.
• Then, use the AS keyword after the expression name or column list if the column list is specified.
• After, define a SELECT statement whose result set populates the common table expression.
• Finally, refer to the common table expression in a query (SQL_statement) such as
SELECT, INSERT, UPDATE, DELETE, or MERGE.

66
Common Table Expressions – Subqueries
SUBQUERIES

A subquery is a SQL query nested inside a larger query. A subquery may occur in :
• A select clause
• A from clause
• A where clause

The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another
subquery. A subquery is usually added within the WHERE Clause of another SQL SELECT statement.
You can use the comparison operators, such as >, <, or =. The comparison operator can also be a
multiple-row operator, such as IN, ANY, or ALL. A subquery is also called an inner query or inner
select, while the statement containing a subquery is also called an outer query or outer select. The
subquery (inner query) executes once before the main query (outer query) executes. For example:

Select select_list from


tablename Where expr
operator
In(select select_list
from tablename);

67
Common Table Expressions – Temporary Table

USE OF TEMP TABLES

A temporary table is a table used in a procedure that stores data from a select list. This table is
truncated every time the procedure is run. It acts as a temporary container that stores data.
The practice of using temporary tables in efficient in writing stored procedures as it makes
the code readable, and it reduces run time.

68
TEST
Test Question

• Display employees who joined in the month of May.


• Display details of the employees where commission percentage is null
and salary in the range 5000 to 10000 and department is 30.
• Display first name and date of first salary of the employees.
• Display first name and experience of the employees.
• Display first name of employees who joined in 2001.
• Display first name and last name after converting the first letter of each
name to upper case and the rest to lower case.
• Display the first word in job title.
• Display the length of first name for employees where last name
contain character ‘b’ after 3rd position.
• Display first name in upper case and email address in lower case
for employees where the first name and email address are same
irrespective of the case.
• Display employees who joined in the current year.

70
Introduction to
Advance SQL
Advance SQL

The PL/SQL language is an extension of SQL language developed by Oracle


Corporation and the full name it is the Procedural Language/Structured Query
Language.
The PL/SQL language is a procedural programming language which allows data
manipulation and sql query to be included in blocks. PL/SQL can be used to group
multiple instructions in a single block and sending the entire block to the server in a
single call.

72
Some of the outstanding benefits of PL/SQ
 PL/SQL, through PLSQL Engine has the ability to integrate with different
Oracle products without dependency on the engine in Oracle server. For
example, Oracle Developer tools like Oracle Forms, Reports and Graphics
have their in-built PL/SQL Engines.
 PL/SQL automates queries, hence, improving the performance of
Applications. For example, SQL statements can be bundled in a block and
sent to the Oracle server at once.
 PL/SQL programs can run anywhere Oracle server runs.
 PL/SQL allows us declare identifiers for use in procedural statements.
Identifiers include variables, cursors, constants, exceptions, etc.
 PL/SQL allows us to program with control structureslike Selection and
Iteration statements.
 PL/SQL also handles errors intelligently.
73
Program Block
DECLARE
Variables, Constants, Records,Cursors,Exceptions (user defined);

BEGIN
-SQL Statements;-
PL/SQL Statements;

EXCEPTION –Optional
Actions to perform when errors occur;

END;

74
PL/SQL program block types
There are three different PL/SQL program block types.

Anonymous Procedure Function

DECLARE PROCEDURE NAME FUNCTION NAME


IS IS
BEGIN BEGIN BEGIN
Statements; Statements; Statements;

[EXCEPTION] [EXCEPTION] [EXCEPTION]

END END END

75
PL/SQL program block types
There are three different PL/SQL program block types.

Anonymous Procedure Function

DECLARE PROCEDURE NAME FUNCTION NAME


IS IS
BEGIN BEGIN BEGIN
Statements; Statements; Statements;

[EXCEPTION] [EXCEPTION] [EXCEPTION]

END END END

• Anonymous blocks are unnamed programs,quickly developed and passed to the PL/SQL engine for execution at
runtime.
• Procedure and Function are named programs that can take parameters and can be invoked. Procedures are used
to perform actions, while functions are used to compute and return a value.

76
Variables
Variables are identifiers of varied types and sizes being introduced into our
programs.PL/SQL variables have a datatype, which specifies a storage format,
constraints, and valid range of values.Variable Types include Scalar (varchar2,
date, number, Boolean, etc.), Composite (Records), LOB (Large objects like
images, large files, videos, etc.).

DECLARING VARIABLES
Syntax
Identifier datatype(length)[Constraint] := expr;

77
SQL Control
Structure
Selective Control Structure
The selection structure tests a condition, then executes one
sequence of statements instead of another, depending on
whether the condition is true or false. A condition is any variable
or expression that returns a Boolean value (TRUE or FALSE). The
iteration structure executes a sequence of statements repeatedly
as long as a condition holds true. The sequence structure simply
executes a sequence of statements in the order in which they
occur.

79
Selective Control Structure - Examples
IF-THEN Statement
If you want to execute a certain section of code only if a
condition is true, you can use an IF-THEN statement
IF condition THEN
-- statements
END IF;

IF-THEN-ELSIF Statement
You can also use an IF-THEN-ELSIF statement to check multiple
conditions.
IF condition_1 THEN
-- statement_1
ELSIF condition_2 THEN
-- statement_2
END IF;

80
Selective Control Structure - Examples
IF-THEN-ELSE Statement
If you want to execute a certain section of code only if a condition
is NOT true, you can use an IF-THEN-ELSE statement.

IF condition_1 THEN
-- statement_1
ELSIF condition_2 THEN
-- statement_2
ELSE
-- statement_3
END IF;

81
Iterative Control Structure

LOOP statements let you execute a sequence of statements

multiple times. There are three forms of LOOP statements:

 Basic LOOP

 WHILE-LOOP

 FOR-LOOP

82
Iterative Control Structure
BASIC LOOP

The simplest form of LOOP statement is the basic (or infinite) loop, which

encloses a sequence of statements between the keywords LOOP and END

LOOP, as follows:
LOOP
... Statement
... Exit;
END LOOP;

With each iteration of the loop, the sequence of statements is executed, then control resumes at

the top of the loop. If further processing is undesirable or impossible, you can use

an EXIT statement to complete the loop. You can place one or more EXIT statements anywhere

inside a loop, but nowhere outside a loop. There are two forms

of EXIT statements: EXIT and EXIT-WHEN. 83


Iterative Control Structure
WHILE-LOOP

The WHILE-LOOP statement associates a condition with a sequence of

statements enclosed by the keywords LOOP and END LOOP, as follows:

WHILE condition LOOP

sequence_of_statements

END LOOP;

Before each iteration of the loop, the condition is evaluated. If the

condition is true, the sequence of statements is executed, then control

resumes at the top of the loop. If the condition is false or null, the loop is

bypassed and control passes to the next statement.

84
Iterative Control Structure
FOR-LOOP

Whereas the number of iterations through a WHILE loop is unknown until the loop

completes, the number of iterations through a FOR loop is known before the loop is

entered. FOR loops iterate over a specified range of integers. The range is part of

an iteration scheme, which is enclosed by the keywords FOR and LOOP. A double

dot (..) serves as the range operator. The syntax follows:

FOR counter IN [REVERSE] lower_bound..higher_bound LOOP

sequence_of_statements

END LOOP;

The range is evaluated when the FOR loop is first entered and is never re-

evaluated.

85
Procedure and
Function
Procedure

A procedure is a named PL/SQL block which is stored in the database and

can be invoked by name.

An Oracle PL/SQL procedure has a header and a body.

The header consists of the keyword PROCEDURE, followed by the

procedure name, followed by a list of parameters in parentheses. The body

of the procedure consists of the PL/SQL code which implements the

procedure.

87
Procedure

Create procedure syntax:

CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter [,parameter]) ]

IS

-- Declarative part (optional)

BEGIN -- Executable part (required)

-- SQL statements

-- PL/SQL statements

EXCEPTION -- Exception-handling part (optional)

-- Exception handlers for exceptions (errors) raised in executable part

END [procedure_name]; -- End of executable part (required)

88
Procedure
Parameter

Parameters are variables which are passed in to a procedure.

They are used to pass data in to the procedure so that it can be

used by the code inside the procedure. Parameters are declared

in the procedure header, after the procedure name.

A procedure can be executed by using the EXECUTE keyword,

followed by the procedure name and a list of parameters to pass

in to the procedure.

89
Procedure
Create procedure example:

create or replace procedure get_lastname (p_dep_id number)

is

v_error varchar2(250);

begin

for rec in (select * from employee where departmentid = p_dep_id)

Loop

DBMS_OUTPUT.PUT_LINE('The name is: '||rec.lastname);

end loop;

exception

when others then

v_error := 'Database error!';

DBMS_OUTPUT.PUT_LINE(v_error);

end; 90
Function

FUNCTION

A function is a named PL/SQL statement that returns a value. A function can

be stored in the database as a schema object, for repeated execution. A

function can be called as part of an expression.

Syntax
CREATE [OR REPLACE] FUNCTION function_name[(parameter1 datatype1,
Parameter2 datatype2, . . .)
]
RETURN datatype
IS/AS
PL/SQL Block;

91
Thank you
Test
Test Question

• Create a function that will return the cube of any number you used as a
parameter.
• Using the employ table create a function to return the salary of an employee
using employee_id as the parameter.
• Using the student score table add a column called status and create a
procedure to determine the status of the student if they pass or not.
Note: When the student’s score is less than 45 the status will failed
but if is 45 and above the status will be passed.
• Create a new table called student_score2, then create a procedure to load the
score of the student that pass to a the new table.

94

You might also like