Workshop 2 SQL Functions Review

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

Oracle SQL Review

Workshop 2 – Functions

Copyright © 2020, Oracle and/or its affiliates. All rights reserved.


Getting Started with SQL Review
• The purpose of these workshops is to give students a
strong foundation in SQL before diving into the
complexities of PL/SQL or other SQL related technology
• The following workshops are available:
− Workshop 1 : SELECT Statements
− Workshop 2 : Functions
− Workshop 3 : Joins
− Workshop 4 : Subqueries

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 3


Workshop 2 : Functions
• In this workshop, you will review how to select and
apply functions in an SQL query to:
−Change the case of character data
−Concatenate character data
−Determine the length of character data
−Select a substring of character data
−Round or truncate numerical data
−Convert data stored as one data type to another data type

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 4


Workshop 2 : Functions
• In this workshop, you will review how to select and
apply functions in an SQL query to:
−Perform month-level arithmetic
−Enhance query results containing null values
−Use group functions to determine a sum total, an average
amount, and a maximum value
−Group data based on specified criteria

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 5


Table Layouts
• Click link below to see table schemas used in this
review:
−SQL Table Design document

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 6


Case Manipulation Functions
• Case manipulation functions temporarily convert
character data to a specified case
• LOWER(column | expression) converts alpha characters
to lowercase

SELECT country_id, country_name, area


FROM wf_countries
WHERE LOWER(country_name) = 'kingdom of tonga';

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 7


Case Manipulation Functions
• UPPER(column | expression) converts alpha characters
to uppercase
−Example:
SELECT country_id, country_name, area
FROM wf_countries
WHERE LOWER(country_name) = 'kingdom of tonga';

• INITCAP( column | expression) converts alpha


character values to uppercase for the first letter of
each word
−Example:
SELECT country_id, country_name, area
FROM wf_countries
WHERE INITCAP(country_name) = 'Kingdom Of Tonga';

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 8


Character Manipulation Functions
• Character manipulation functions temporarily convert
character data to different values
• CONCAT joins two values together

SELECT CONCAT (country_name,internet_extension)


"Country and extension"
FROM wf_countries WHERE country_id = 229;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 9


Character Manipulation Functions
• SUBSTR extracts a string of a determined length
SELECT SUBSTR(country_name,3,3)
FROM wf_countries WHERE country_id = 229;

• LENGTH shows the length of a string as a number value


SELECT LENGTH(country_name )
FROM wf_countries WHERE country_id = 229;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 10


Try It!
• We will now try executing some SQL statements.
• We will use the Oracle Application Express (APEX)
database environment to do this
• To request Oracle Application Express accounts please
see the APEX Startup Guide located on the Oracle
Academy Member Website

Oracle
APEX
Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 11
Try It!
• Once logged into APEX, select SQL Workshop
• In SQL Workshop, select the SQL Commands option
• Enter the desired SQL code and click the Run button,
the results will be displayed in the lower pane

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 13


Try it!
• Create a list of employees names who have the job_id
of AD_VP, use the UPPER function in the WHERE
statement (click for solution)
SELECT first_name, last_name, job_id
FROM employees
WHERE LOWER(job_id) = 'ad_vp';

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 13


Try it!
• Create a list that includes the first initial of every
employee's first name, a space, and the last name of
the employee, call it “Employee Names”
(click for solution)
SELECT SUBSTR(first_name, 1, 1) || ' ' || last_name AS
"Employee Names "
FROM employees;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 14


Number Functions
• Number functions temporarily convert number data to
different values
• ROUND: Used to round numbers to a specified number
of decimal places

SELECT country_id, median_age, ROUND(median_age,-1)


FROM wf_countries WHERE country_id = 20;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 15


Number Functions
• TRUNC: Used to terminate the column, expression, or
value to a specified number of decimal places
SELECT TRUNC(999.128,2) FROM dual;

• MOD: Used to return the remainder when one number


is divided by another
SELECT country_id, population, MOD(population,2)
FROM wf_countries WHERE country_id = 3;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 16


Try it!
• Create a list of weekly salaries from the employees
table where the weekly salary is between 700 and
3000
• The salaries should be formatted to include a $-sign
and be rounded to two decimal points like: $9999.99
(click for solution)
SELECT '$' || ROUND((salary*12)/52, 2) AS "Weekly Salary "
FROM employees
WHERE (salary*12)/52 BETWEEN 700 AND 3000;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 17


Conversion Functions
• TO_CHAR converts dates stored in a database from the
default DD-MON-YY display format to another format
specified by you
• The syntax is:
TO_CHAR (date, 'format model you specify')

• Example:
SELECT TO_CHAR(SYSDATE,'Month ddth, yyyy') AS TODAY
FROM dual;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 18


Conversion Functions
• TO_CHAR converts columns of number data to a
desired format
• The syntax is:
TO_CHAR (number, 'format model you specify')

• Example:
SELECT country_id, TO_CHAR(population,'99,999,999,999')
FROM wf_countries;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 19


Conversion Functions
• TO_DATE converts a character string to a date format
• The syntax is:
TO_DATE('character string', 'format model')

• Example:
SELECT TO_DATE('January 1, 2006','Month DD, RRRR')
AS "New Year"
FROM dual;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 20


Conversion Functions
• TO_NUMBER converts a character string to a number
• The syntax is:
TO_NUMBER(character string, 'format model')

• Example:
SELECT TO_NUMBER('95.5','999.9') AS converted
FROM dual;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 21


Try it!
• Create a list of last_names and hire_dates for
employees with dates formated as ‘April 10th, 2018’,
call date “Hire Date” (click for solution)
SELECT last_name, TO_CHAR(hire_date, 'Month ddth, yyyy') as
"Hire Date"
FROM employees;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 22


Try it!
• Create Convert the string ‘March 20, 2018’ to a date
field with the column heading “First Day of Spring”
(click for solution)
SELECT TO_DATE('March 20, 2018','Month dd, YYYY') AS "First
Day of Spring"
FROM dual;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 23


Date Functions
• SYSDATE is a date function that returns the current
database server date and time
−Example:

SELECT SYSDATE+1 AS tomorrow


FROM dual;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 24


Date Functions
• MONTHS_BETWEEN returns the number of months
between two dates
−Example:
SELECT country_name "Country",
date_of_independence "Independence Day",
TO_CHAR(MONTHS_BETWEEN(SYSDATE,
date_of_independence), '999,999,999.99')
AS "Months Since"
FROM wf_countries
WHERE country_id = 229;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 25


Date Functions
• ADD_MONTHS increments a date by calendar months
−Example:

SELECT ADD_MONTHS(SYSDATE, 120) "10 yrs from today"


FROM dual;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 26


Try it!
• Calculate the number of months between today and
Christmas, rounded to a whole number
(click for solution)
SELECT ROUND(MONTHS_BETWEEN('25-DEC-2018', SYSDATE)
,0) AS "Months till Christmas"
FROM dual;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 27


Try it!
• Display each employee’s name and a calculation of the
date a year from their hire_date call it “First
Anniversary” (click for solution)
SELECT first_name, last_name, ADD_MONTHS(hire_date, 12)
as "First Anniversary "
FROM employees;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 28


General Functions
• NVL converts a null value to a date, a character, or a
number
−The syntax is:

NVL(value that may contain a null,


value to replace the null)

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 29


General Functions
• NVL examples:
SELECT currency_name, comments
FROM wf_currencies
WHERE currency_code = 'AUD';

SELECT currency_name,
NVL(comments,'No comment') AS comments
FROM wf_currencies
WHERE currency_code = 'AUD';

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 30


General Functions
• NULLIF compares two functions. If they are equal, the
function returns null
• If they are not equal, the function returns the first
expression
−The syntax is:
NULLIF(expression 1, expression 2)

SELECT country_translated_name "Country Name Trans",


country_name "Country Name",
NULLIF(country_translated_name, country_name) "nullif returns"
FROM wf_countries;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 31


Try it!
• Create a list of every employee's first initial and last
name, salary, and commission, if they don’t make a
commission substitute 0, call the column
“Commission” (click for solution)
SELECT SUBSTR(first_name, 1, 1) || ' ' || last_name AS
"Employee Name", salary AS "Salary", NVL(commission_pct, 0)
AS "Commission“
FROM employees;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 32


Group Functions
• These functions operate on a whole table or on a
specific grouping of rows to return one result
• AVG: Used with columns that store numeric data to
compute the average, ignoring null values

SELECT TO_CHAR(AVG(population),'9,999,999,999.99') average


FROM wf_countries;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 33


Group Functions
• COUNT: Returns the number of non-null column values
or whole rows

SELECT COUNT(country_id) "Number of Countries"


FROM wf_countries;

SELECT COUNT(*) "Number of Countries"


FROM wf_countries;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 34


Group Functions
• MIN:
−Used with columns that store any data type to return the
minimum value, ignoring null values
• MAX:
−Used with columns that store any data type to return the
maximum value, ignoring null values
• SUM:
−Used with columns that store numeric data to find the total
or sum of values, ignoring null values
SELECT MIN(lowest_elevation) "All time low"
FROM wf_countries;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 35


Group Functions

SELECT MAX(highest_elevation) "All time high"


FROM wf_countries;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 36


Group Functions

SELECT TO_CHAR(SUM(area), '999,999,999,999.99') "Total area"


FROM wf_countries;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 37


Try it!
• Show the “First” last name and the “Last” last name
from the employees table (click for solution)
SELECT MIN(last_name) AS "First Last Name", MAX(last_name)
AS "Last Last Name"
FROM employees;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 38


Try it!
• Produce a list of the earliest hire date as “Highest” the
latest hire date as “Lowest”, and the number of
employees as “No of Employees” from the employees
table (click for solution)
SELECT MAX(hire_date) AS "Highest", MIN(hire_date) AS
"Lowest",
COUNT(last_name) AS "No of Employees"
FROM employees;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 39


GROUP BY
• 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
• The WHERE clause first excludes rows
• The remaining data is divided into groups, and group
functions are applied
SELECT region_id,
COUNT(country_id)
FROM wf_countries
WHERE region_id < 15
GROUP BY region_id;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 40


HAVING
• Use the HAVING clause to restrict groups.
• In a query that uses 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 following is the syntax:

SELECT column, group_function


FROM table
WHERE <restrict rows>
GROUP BY <form subgroups>
HAVING <restrict groups>
ORDER BY <sort rows remaining>

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 41


HAVING

SELECT region_id, COUNT(country_id)


FROM wf_countries
WHERE region_id < 15
GROUP BY region_id
HAVING COUNT(country_id) < 20
ORDER BY region_id DESC;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 42


Try it!
• Show the highest average salary for the departments in
the employees table
• Round the result to the nearest whole number (click
for solution)
SELECT ROUND(MAX(AVG(salary)), 0) AS "Highest Avg Sal for
Depts"
FROM employees
GROUP BY department_id;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 43


Try it!
• Create list of departments and the number of
employees in them but only for departments with 3 or
more employees (click for solution)
SELECT department_id, COUNT(employee_id)
FROM employees
GROUP BY department_id
HAVING COUNT(employee_id) >= 3;

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 44


Workshop 2 Completed!
• Now that you’ve reviewed SQL Functions you may
want to complete some of the other review modules:
−Workshop 1 : SELECT Statements
−Workshop 2 : Functions
−Workshop 3 : Joins
−Workshop 4 : Subqueries
−Challenge Practice Problems (Located at end of Workshop 4)

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. 45

You might also like