Lab 7 (SQL DML-tutorial) Using Database Script
Lab 7 (SQL DML-tutorial) Using Database Script
Use company schema came along this lab for this tutorial. Upload the SQL script to create and
populate database using APEX.
This document has many examples of each SQL construct to understand how each SQL
construct just for your learning. Use separate lab tasks to submit your week 6 assignment.
Table of Content
s
Lab 7 –Introduction to Basic SQL................................................................................................................2
Loading the Tables and Data...................................................................................................................2
Anatomy of a SQL Statement..................................................................................................................5
SELECT Statement with a Condition........................................................................................................5
Practice:..................................................................................................................................................8
For each of the task below, use APEX to create query. Copy a screenshot of query and its results using
APEX......................................................................................................................................................8
WHERE and ORDER BY.................................................................................................................................9
Syntax with Examples..............................................................................................................................9
Lab Task 2:.............................................................................................................................................11
GROUP Functions......................................................................................................................................12
SELECT Statement with Group Functions..............................................................................................12
SELECT Statement with Group By Clause...............................................................................................14
SELECT Statement with Group By and Having Clauses..........................................................................16
SELECT Statement with Set Operators...................................................................................................18
Fundamentals of Subqueries.....................................................................................................................19
Subquery Overview...............................................................................................................................19
Single Row Subquery.........................................................................................................................20
Multiple Row Subquery.....................................................................................................................22
Practice.....................................................................................................................................................25
Subqueries: use nested queries only.....................................................................................................25
Aggregate function................................................................................................................................25
Ordering of query results.......................................................................................................................26
Grouping function.................................................................................................................................26
Introduction to Joins.................................................................................................................................26
SELECT Statement with NATURAL JOIN.............................................................................................27
SELECT Statement with CROSS JOIN..................................................................................................29
SELECT Statement with JOIN and USING Clause................................................................................29
SELECT Statement with JOIN and ON Clause.........................................................................................30
SELECT Statement to Join 3 Tables....................................................................................................31
SELECT Statement with LEFT and RIGHT OUTER JOIN........................................................................31
SELECT Statement with FULL OUTER JOIN.........................................................................................32
SELECT Statement with SELF JOIN.....................................................................................................33
Practice.....................................................................................................................................................34
2. Click Upload
2
4. Navigate to the working directory where you extracted apex-course-labs.zip. Locate
the Project_Tables.sql file, and double-click the file or click the file and then click
Open. Click Upload.
3
5. Review the uploaded script to see what tables will be created. In the SQL Scripts list,
click the Edit icon (pencil), to the left of the script you just uploaded.
6. Click the Run icon to the right of the script you uploaded.
4
Anatomy of a SQL Statement
SELECT <attribute list>
FROM <table list>
WHERE <condition>;
where
■ <attribute list> is a list of attribute names whose values are to be retrieved by the query.
■ <table list> is a list of the relation names required to process the query.
■ <condition> is a conditional (Boolean) expression that identifies the tuples to be retrieved by the
query.
Example Explanation
Using Comparison Operators
SELECT DISTINCT country_id It displays unique country_id from table
FROM locations locations for all rows that have location_id
WHERE location_id<2000 less than 2000.
5
Example Explanation
Concatenation and Literal Values You can also include numbers as literal
values. In the following example, the
number 1 is concatenated to the strings, 'has
a 'and 'year salary of '
6
Example Explanation
SELECT last_name ||' has a '|| 1 ||' year salary
of '||
salary*12 || ' dollars.' AS Pay
FROM employees;
Using IS NULL
SELECT * It displays all columns and all rows of
FROM departments departments table whose manager_id is
WHERE manager_id is null; null (empty).
7
Practice:
For each of the task below, use APEX to create query. Copy a screenshot of query and its results
using APEX.
1. Create a SQL statement that displays only the first_name and salary of an employee
whose salary is greater than 10,000.
2. Create a SQL statement that displays only the first_name and salary of an employee
whose salary is between 10000 and 15000.
3. Create a SQL statement that displays the first_name and last_name of employees whose
last_name is ‘Smith’.
4. Create a SQL statement that displays the first_name and last_name of employees whose
last_name is either ‘Smith’, ‘King’, or ‘Rogers’.
5. Create a SQL statement that displays the first_name and last_name of employees whose
last_name starts with ’S’.
8
WHERE and ORDER BY
create SELECT Statements using logical operators
create SELECT Statements using ORDER BY
create SELECT Statements using column aliases
create SELECT Statements using sorting with other columns
create SELECT Statements using sorting with multiple columns
Logical conditions combine the result of two or more conditions to produce a single result. In
SQL, the basic logical comparison operators for comparing attribute values with one another and
with literal constants are =, <, <=, >, >=, and, or, <>.
These correspond to the relational algebra operators =, <, ≤, >, ≥, and ≠, respectively, and to the
C/C++ programming language operators =, <, <=, >, >=, and !=. The main syntactic
difference is the not equal operator. SQL has additional comparison operators that we will
present gradually.
Example Explanation
Using Logical Operators
SELECT last_name, department_id, salary In the query shown, the results returned
FROM employees will be rows that satisfy BOTH
WHERE department_id > 50 AND salary > 12000; conditions specified in the WHERE
clause.
9
Example Explanation
FROM departments to 124
WHERE location_id = 2500 OR manager_id=124;
SELECT department_name, location_id The NOT operator will return rows that
FROM departments do NOT satisfy the condition in the
WHERE location_id NOT IN (1700,1800); WHERE clause.
Using Order By
SELECT last_name, hire_date uses the ORDER BY clause to order
FROM employees hire_date in ascending (default) order
ORDER BY hire_date;
10
Example Explanation
SELECTing. In the real world, you
would run your query selecting the
last_name column until you were sure
you were getting the right data. Then
you could remove that column from
your SELECT statement.
Lab Task 2:
Use the company database to perform the following operations. Use order by and column aliases
to make the results meaningful.
To perform this lab activity, you first need to upload companySchema.SQl by following the data
upload steps, you already learned.
1. Retrieve the name and address of all employees who work for the ‘Research’ department.
Sort results by the first name.
2. For every project located in ‘Stafford’, list the project number, the controlling department
number, and the department manager’s last name, address, and birth date.
3. For each employee, retrieve the employee’s first and last name and the first and last name of
his or her immediate supervisor.
11
GROUP Functions
In SQL, the following group functions can operate on a whole table or on a specific grouping of rows.
Each function returns one result.
Group Functions include AVG, COUNT, MIN, MAX, SUM, VARIANCE, and STDDEV.
Example Output
Using MIN
SELECT MIN(life_expect_at_birth) 32.62
AS "Lowest Life Exp"
FROM wf_countries;
Using MAX
SELECT MAX(life_expect_at_birth) 83.51
AS "Highest Life Exp"
FROM wf_countries;
Using SUM
SELECT SUM(area) 241424
FROM wf_countries
WHERE region_id = 29;
Using AVG
12
Example Output
SELECT AVG(area) 9656.96
FROM wf_countries
WHERE region_id = 29;
Using VARIANCE
SELECT 143.2394
ROUND(VARIANCE(life_expect_at_birth),4)
FROM wf_countries;
Using STDDEV
SELECT ROUND(STDDEV(life_expect_at_birth), 11.9683
4)
FROM wf_countries;
Using COUNT
SELECT COUNT(job_id) FROM employees; 20
Using NVL
13
Example Output
SELECT AVG(commission_pct) FROM .2125
employees;
You use the GROUP BY clause to divide the rows in a table into smaller groups.
You can then use the group functions to return summary information for each group.
Group functions require that any column listed in the SELECT clause that is not part of a
group function must be listed in a GROUP BY clause.
If you include a group function (AVG, SUM, COUNT, MAX, MIN, STDDEV,
VARIANCE) in a SELECT clause along with any other individual columns, each
individual column must also appear in the GROUP BY clause.
You cannot use a column alias in the GROUP BY clause.
The WHERE clause excludes rows before they are divided into groups.
Example Explanation
SELECT department_id, The rows are being grouped by department_id. The AVG
AVG(salary) function is then applied to each group.
FROM employees
GROUP BY department_id
ORDER BY department_id;
14
Example Explanation
Column department_id is added to tell which maximum
salary belongs to which department
SELECT department_id,
MAX(salary)
FROM employees
GROUP BY department_id;
SELECT COUNT(country_name), This example shows how many countries are in each
region_id FROM wf_countries region.
GROUP BY region_id ORDER Remember that group functions ignore null values, so if
BY region_id; any country does not have a country name, it will not be
included in the COUNT.
SELECT COUNT(*), region_id Unlike the previous example, this one will count all of
FROM wf_countries GROUP BY the rows in each region group, without the need to check
region_id ORDER BY region_id; which columns contained NULL values.
15
Example Explanation
SELECT department_id, WHERE Clause: We can also use a WHERE clause to
MAX(salary) exclude rows before the remaining rows are formed into
FROM employees groups
WHERE last_name != 'King'
GROUP BY department_id;
16
.
Example Explanation
Suppose we want to find the maximum salary in A WHERE clause can be used only to
each department, but only for those departments include/exclude individual rows, not
which have more than one employee? groups of rows. Therefore we cannot
What is wrong with this example? use group functions in a WHERE
SELECT department_id, MAX(salary) clause.
FROM employees In the same way, you used the WHERE
WHERE COUNT(*) > 1 clause to restrict the rows that you
GROUP BY department_id; selected, you can use the HAVING
clause to restrict groups.
In a query using a GROUP BY and
HAVING clause, the rows are first
grouped, group functions are applied,
and then only those groups matching the
HAVING clause are displayed.
The HAVING and GROUP BY clauses can use This query finds the average population
different columns. The example on GROUPs BY of the countries in each region.
region_id, but the HAVING clause restricts groups It then only returns the region groups
based on population. with a lowest population greater than
SELECT region_id, three hundred thousand.
ROUND(AVG(population)) You place each clause in the following
FROM wf_countries order:
GROUP BY region_id SELECT column, group_function
HAVING MIN(population)>300000 FROM table
ORDER BY region_id; WHERE
GROUP BY
HAVING
17
Example Explanation
Suppose we want to find the maximum salary in A WHERE clause can be used only to
each department, but only for those departments include/exclude individual rows, not
which have more than one employee? groups of rows. Therefore we cannot
What is wrong with this example? use group functions in a WHERE
SELECT department_id, MAX(salary) clause.
FROM employees In the same way, you used the WHERE
WHERE COUNT(*) > 1 clause to restrict the rows that you
GROUP BY department_id; selected, you can use the HAVING
clause to restrict groups.
In a query using a GROUP BY and
HAVING clause, the rows are first
grouped, group functions are applied,
and then only those groups matching the
HAVING clause are displayed.
ORDER BY
18
Example Explanation
SELECT hire_date, employee_id, job_id
FROM employees
UNION
SELECT TO_DATE(NULL),employee_id,
job_id
FROM job_history;
Fundamentals of Subqueries
Throughout this course, you have written queries to extract data from a database
What if you wanted to write a query, only to find out you didn't have all the information you
needed to construct it?
You can solve this problem by nesting queries—placing one query inside the other query
The inner query is called a "subquery."
19
Subquery Overview
A subquery is a SELECT statement that is embedded in a clause of another SELECT
statement
A subquery executes once before the main query
The result of the subquery is used by the main or outer query
Subqueries can be placed in a number of SQL clauses, including the WHERE clause, the
HAVING clause, and the FROM clause
The subquery syntax is:
SELECT select_list
FROM table
WHERE expression operator
(SELECT select_list The SELECT statement in parentheses is the
FROM table);
inner query or 'subquery'. It executes first,
before the outer query
Example Explanation
SELECT first_name, last_name, hire_date What if you wanted to find out the
FROM employees names of the employees that were hired
WHERE hire_date > after Peter Vargas?
(SELECT hire_date The first thing you need to know is the
FROM employees answer to the question, "When was Peter
WHERE last_name = 'Vargas'); Vargas hired?"
Once you know his hire date, then you
can select those employees whose hire
dates are after his.
20
Single Row Subquery
They return only one row
They use single-row comparison operators (=, >,>=, <, <=, <>)
Always enclose the subquery in parentheses.
Always place the subquery on the right hand side of the comparison condition.
The outer and inner queries can get data from different tables.
Only one ORDER BY clause can be used for a SELECT statement, and if specified, it
must be the last clause in the main SELECT statement.
The only limit on the number of subqueries is the buffer size that the query uses.
Example Explanation
SELECT last_name, job_id, department_id The outer and inner queries can get data from
FROM employees different tables.
WHERE department_id = The subquery finds the department_id for
(SELECT department_id 'Marketing', the outer query uses the returned
FROM departments department_id to display rows from the
WHERE department_name = 'Marketing') employees table.
ORDER BY job_id;
SELECT last_name, job_id, salary, More than one subquery can return information
department_id to the outer query.
FROM employees The first subquery returns the job_id of
WHERE job_id = employee 141 (ST_CLERK). The second
(SELECT job_id subquery uses the departments table to find the
FROM employees department_id at location_id 1500 (50). The
WHERE employee_id = 141) outer query then returns rows from the
AND department_id = employees table that match both these values.
(SELECT department_id
FROM departments
21
Example Explanation
WHERE location_id = 1500);
"Which employees earn less than the Group function (AVG) in subquery. The
average salary?" subquery first finds the average salary for all
SELECT last_name, salary employees, the outer query then returns
FROM employees employees with a salary of less than the average.
WHERE salary <
(SELECT AVG(salary)
FROM employees);
Which departments have a lowest salary In this example, the subquery selects and returns
that is greater than the lowest salary in the lowest salary in department 50. The outer
department 50? query uses this value to select the department ID
SELECT department_id, MIN(salary) and lowest salaries of all the departments whose
FROM employees lowest salary is greater than that number. The
GROUP BY department_id HAVING clause eliminated those departments
HAVING MIN(salary) > whose MIN salary was less than department 50's
(SELECT MIN(salary) MIN salary.
FROM employees
WHERE department_id = 50);
Example Explanation
Query Comparison
Whose salary is equal to the salary of an This example returns an error because
employee in department 20 ? more than one employee exists in
department 20, the subquery returns
SELECT first_name, last_name multiple rows
FROM employees
22
Example Explanation
WHERE salary =
(SELECT salary
FROM employees
WHERE department_id = 20);
23
Example Explanation
which match the criteria ( <, >, =, etc.) of all of As no employee was hired before 1987, no
the values in the subquery result set. rows are returned.
SELECT last_name, hire_date FROM employees =ALL: How can one value equal every
WHERE EXTRACT(YEAR FROM hire_date) < one of a set of values? For this reason,
ALL =ALL is rarely used.
(SELECT EXTRACT(YEAR FROM hire_date)
FROM employees
WHERE department_id=90);
Dealing with Null Values
Suppose that one of the values returned by
SELECT last_name, a multiple-row subquery is null, but other
employee_id values are not.
FROM employees If IN or ANY are used, the outer query
WHERE employee_id IN will return rows which match the non-null
(SELECT manager_id values.
FROM employees);
If ALL is used, the outer query returns no
SELECT last_name, employee_id rows because ALL compares the outer
FROM employees query row with every value returned by
WHERE employee_id <= ALL the subquery, including the null.
(SELECT manager_id And comparing anything with null results
FROM employees); in null.
24
Example Explanation
Multiple-Column Subqueries
Subqueries can use one or more columns.
If they use more than one column, they are called multiple-column subqueries.
A multiple-column subquery can be either pair-wise comparisons or non-pair-wise
comparisons.
The example below shows a multiple-column The query lists the employees whose
pair-wise subquery manager and departments are the same as
the manager and department of employees
SELECT employee_id, manager_id, 149 or 174.
department_id First, the subquery to retrieve the
FROM employees MANAGER_ID and DEPARTMENT_ID
WHERE(manager_id,department_id) IN values for the employees with
(SELECT manager_id,department_id EMPLOYEE_ID 149 or 174 is executed.
FROM employees These values are compared with the
WHERE employee_id IN (149,174)) MANAGER_ID column and the
AND employee_id NOT IN (149,174); DEPARTMENT_ID column of each row
in the EMPLOYEES table. If the values
match, the row is displayed. In the output,
the records of the employees with the
EMPLOYEE_ID 149 or 174 will not be
displayed.
Practice
Apply the SQL concepts learn in this lab on the company database for performing the following retrieval
operations.
Aggregate function
1. Find the sum of the salaries of all employees, the maximum salary, the minimum salary, and the
average salary.
2. Find the sum of the salaries of all employees of the ‘Research’ department, as well as the
maximum salary, the minimum salary, and the average salary in this department.
3. Retrieve the total number of employees in the company (Q1) and the number of employees in
the ‘Research’ department (Q2)
4. Count the number of distinct salary values in the database.
26
Grouping function
1. For each department, retrieve the department number, the number of employees in the
department, and their average salary.
2. For each project, retrieve the project number, the project name, and the number of employees
who work on that project.
3. For each project on which more than two employees work, retrieve the project number, the
project name, and the number of employees who work on the project.
4. For each department that has more than five employees, retrieve the department number and
the number of its employees who are making more than $40,000.
Introduction to Joins
Up to now, your experience using SQL has been limited to querying and returning information
from one database table at a time
This would not be a problem if all data in the database were stored in only one table
But you know from data modeling that separating data into individual tables and being able to
associate the tables with one another is the heart of relational database design
Fortunately, SQL provides join conditions that enable information to be queried from separate
tables and combined in one report
27
A SQL join clause combines fields from 2 (or more) tables in a relational database as shown in
the below figure. The top table is combining departments and employee DEPT_ID as common
attribute in both table.
28
As shown in the sample code below, when using a natural join, it is possible to join the
tables without having to explicitly specify the columns in the corresponding table. However, the
names and data types of both columns must be the same
Example Explanation
SELECT first_name, last_name, job_id, job_title This join will return columns from the
FROM employees NATURAL JOIN jobs employees table and their related
WHERE department_id > 80; job_title from the jobs table based on
the common column job_id.
The WHERE clause was added to apply
an additional restriction to one of the
tables, to limit the rows of output. The
output is shown below
29
Example Explanation
have to appear in the SELECT clause.
Example Explanation
SELECT last_name, department_name The employees table contains 20 rows
FROM employees CROSS JOIN departments; and the departments table has 8 rows.
Performing a CROSS JOIN will return
160 rows.
Example Explanation
SELECT first_name, last_name, department_id, The columns referenced in the USING
department_name FROM employees JOIN clause should not have a qualifier (table
departments USING (department_id); name or alias) anywhere in the SQL
statement.
If the column in the USING clause has a
qualifier, the following error is returned
ORA-25154: column part of USING
clause cannot have qualifier.
30
Example Explanation
WHERE last_name = 'Higgins';
Example Explanation
SELECT last_name, job_title In this example, the ON clause is used to
FROM employees e JOIN jobs j join the employees table with the jobs
ON (e.job_id = j.job_id); table.
A join ON clause is required when the
The example above uses table aliases as a qualifier common columns have different names
e.job_id = j.job_id, but could also have been written in the two tables
using the table names (employees.job_id =
jobs.job_id
Sometimes you may need to retrieve data from a table that has no corresponding column in
another table
Suppose we want to know the grade_level for each employees salary
31
Example Explanation
The job_grades table (shown below) does not have a common column with the employees
table . Using an ON clause allows us to join the two tables
SELECT last_name, salary, grade_level, This is to know the grade_level for each
lowest_sal, highest_sal employees salary. Even if the
FROM employees JOIN job_grades job_grades table does not have a
ON(salary BETWEEN lowest_sal AND common column with the employees
highest_sal); table.
Example Explanation
SELECT last_name, department_name AS To produce a report of employees, their
"Department", city department, and the city where the
FROM employees JOIN departments USING department is located, we need to join
(department_id) three tables: employees, departments
JOIN locations USING (location_id); and locations.
32
Example Explanation
SELECT e.last_name, d.department_id, note that the table name listed to the left of
d.department_name the words "left outer join" is referred to as
FROM employees e the "left table."
LEFT OUTER JOIN departments d ON This query will return all employee last
(e.department_id = d.department_id); names, both those that are assigned to a
department and those that are not
SELECT e.last_name, d.department_id, This right outer join would return all
d.department_name department IDs and department names, both
FROM employees e those that have employees assigned to them
RIGHT OUTER JOIN departments d ON and those that do not.
(e.department_id = d.department_id);
33
Example Explanation
SELECT e.last_name, d.department_id, Employees and departments tables are
d.department_name fully joined on their department_id using
FROM employees e FULL OUTER JOIN.
FULL OUTER JOIN departments d ON
(e.department_id = d.department_id);
Example Explanation
SELECT worker.last_name, “Manager name” is alias names that relate to
worker.manager_id, manager.last_name the data's association with that table.
AS "Manager name" Manager_id in the worker table is equal to
FROM employees worker JOIN employees employee_id in the manager table.
manager
ON (worker.manager_id =
manager.employee_id);
34
Example Explanation
To join a table to itself, the table is given two
names or aliases. This will make the database
"think" that there are two tables shown below
Practice
Apply the concepts learn in this lab on company database for retrieving following information.
1. Retrieve the name and address of all employees who work for the ‘Research’ department
without using join
2. Modify query 1 and observe results by using join
3. Modify query 1 and use subquery instead of join
4. Retrieve the last name of employees and their supervisors (natural join)
5. Modify query 4 to display all employees with supervisor and also that employee where a
supervisor is not assigned (left outer join)
6. Modify query 4 to display all the supervisors with and without employees assigned to
them (Right outer join)
7. Modify query 4 to display all employees with and without supervisors and all supervisors
with and without employees (Full outer join)
35