Professional Documents
Culture Documents
LANGUAGE (SQL)
TAIYE AHMED
Trainer
analytics solutions, leveraging expertise in, database
management, data warehousing technologies, data
modeling, data visualization, ETL, Big Data, and
Cloud analytics technologies.
Musefiu Adekunle
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
Queries
SQL Examples I
Analytic Function
Database Objects
SQL Joins
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?
12
Introduction to Database
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
13
Introduction to Datawarehouse
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
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
20
Introduction to SQL – Database Objects
(contd.)
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.
• 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
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:
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:
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:
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:
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:
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, ...);
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
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
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
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
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 :
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:
67
Common Table Expressions – Temporary Table
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
70
Introduction to
Advance SQL
Advance SQL
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.
75
PL/SQL program block types
There are three different PL/SQL program block types.
• 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
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
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
sequence_of_statements
END LOOP;
resumes at the top of the loop. If the condition is false or null, the loop is
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
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
procedure.
87
Procedure
IS
-- SQL statements
-- PL/SQL statements
88
Procedure
Parameter
in to the procedure.
89
Procedure
Create procedure example:
is
v_error varchar2(250);
begin
Loop
end loop;
exception
DBMS_OUTPUT.PUT_LINE(v_error);
end; 90
Function
FUNCTION
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