0% found this document useful (0 votes)
6 views

En-Functions in SQL

Uploaded by

oumaima nouari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

En-Functions in SQL

Uploaded by

oumaima nouari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Functions in SQL

Functions in SQL

Course objectives
By completing this course, you will be able to:

 Describe various types of


functions that are available in
SQL
 Describe the use of group
functions
Functions in SQL

Course topics
Course’s plan:
 Using Single-Row
Functions to Customize
Output
 Reporting Aggregated
Data Using the Group
Functions
Functions in SQL

Single-Row Functions
Single-Row Functions

Preview

 SQL Functions.
 Character Functions.
 Number Functions.
 Date Functions.
 Conversion Functions.
 General Functions.
 Conditional Expressions.
Single-Row Functions

SQL Functions

Input Output
FUNCTION

Functions performs
arg 1 actions
Result Value
arg 2

arg n
Single-Row Functions

SQL Functions
Two Types of SQL Functions

FUNCTION

Single-row Multiple-row
functions functions

Return one result Return one result


per row per set of rows
Single-Row Functions

SQL Functions
Single-row functions:

Character

Single-row
General Number
functions

Conversion Date
Single-Row Functions

Character Functions

Character
functions

Case-manipulation Character-manipulation
functions functions

LOWER CONCAT
SUBSTR
UPPER LENGTH
INITCAP INSTR
LPAD | RPAD
TRIM
REPLACE
Single-Row Functions

Character Functions
Using Case-Manipulation Functions

 These functions convert case for character strings:

Function Result
LOWER('SQL Course') sql course

UPPER('SQL Course') SQL COURSE

INITCAP('SQL Course') Sql Course


Single-Row Functions

Character Functions
Using Case-Manipulation Functions
 Display the employee number, name, and department
number for employee Higgins:
SELECT employee_id, last_name, department_id
FROM employees
WHERE last_name = 'higgins' ;

no rows selected

SELECT employee_id, last_name, department_id


FROM employees
WHERE LOWER(last_name) = 'higgins';
Single-Row Functions

Character Functions
These functions manipulate character strings:

Function Result
CONCAT('Hello', 'World') HelloWorld
SUBSTR('HelloWorld',6,5) World
LENGTH('HelloWorld') 10
INSTR('HelloWorld', 'W') 6
LPAD(salary,10,'*') *****24000
RPAD(salary, 10, '*') 24000*****
REPLACE('JACK and JUE','J','BL') BLACK and BLUE
TRIM('H' FROM 'HelloWorld') elloWorld
Single-Row Functions

Character Functions
Using the Character-Manipulation Functions
1
SELECT employee_id, CONCAT(first_name, last_name)
NAME,job_id, LENGTH (last_name), 2
INSTR(last_name, 'a') "Contains 'a'?" 3
FROM employees
WHERE SUBSTR(job_id, 4) = 'REP';

1 2 3
Single-Row Functions

Character Functions
Using SUBSTR Function with different arguments:
SELECT SUBSTR('Hello World', 4)
FROM DUAL;

Lo World

SELECT SUBSTR('Hello World', -4) L1


FROM DUAL;

orld

SELECT SUBSTR('Hello World', -4,3) L2


FROM DUAL;

orl
Single-Row Functions

Number Functions
 ROUND: Rounds value to specified decimal
 TRUNC: Truncates value to specified decimal
 MOD: Returns remainder of division

Function Result
ROUND(45.926, 2) 45.93
TRUNC(45.926, 2) 45.92
MOD(1600, 300) 100
Single-Row Functions

Number Functions
Using the MOD Function
 For all employees with job title of Sales Representative,
calculate the remainder of the salary after it is divided by
5,000.
SELECT last_name, salary, MOD(salary, 5000)
FROM employees
WHERE job_id = 'SA_REP';
Single-Row Functions

Date Functions
Working with Dates
 The Oracle database stores dates in an internal numeric
format: century, year, month, day, hours, minutes, and
seconds..

SELECT last_name, hire_date


FROM employees
WHERE hire_date < '01-FEB-88';
Single-Row Functions

Date Functions
Working with Dates

 SYSDATE is a function that returns:


 Date
 Time
Single-Row Functions

Date Functions
Arithmetic with Dates
 Add or subtract a number to or from a date for a resultant
date value.
 Subtract two dates to find the number of days between
those dates.
 Add hours to a date by dividing the number of hours by
24.
Single-Row Functions

Date Functions
Using Arithmetic Operators with Dates

SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS


FROM employees
WHERE department_id = 90;
Single-Row Functions

Date Functions

Function Result
MONTHS_BETWEEN Number of months between two dates

ADD_MONTHS Add calendar months to date

NEXT_DAY Next day of the date specified

LAST_DAY Last day of the month

ROUND Round date

TRUNC Truncate date


Single-Row Functions

Date Functions

Function Result
MONTHS_BETWEEN
19.6774194
('01-SEP-95','11-JAN-94')

ADD_MONTHS ('11-JAN-94',6) '11-JUL-94'

NEXT_DAY ('01-SEP-95','FRIDAY') '08-SEP-95'

LAST_DAY ('01-FEB-95') '28-FEB-95'


Single-Row Functions

Date Functions
Example
Assume SYSDATE = '25-JUL-03':

Function Result
ROUND(SYSDATE,'MONTH') 01-AUG-03

ROUND(SYSDATE,'YEAR') 01-JAN-04

TRUNC(SYSDATE,'MONTH') 01-JUL-03

TRUNC(SYSDATE,'YEAR') 01-JAN-03
Single-Row Functions

Conversion Functions

Data type
conversion

Implicit data type Explicit data type


conversion conversion
Single-Row Functions

Conversion Functions
Implicit Data Type Conversion
 For assignments, the Oracle server can automatically
convert the following:

From To
VARCHAR2 or CHAR NUMBER

VARCHAR2 or CHAR DATE

NUMBER VARCHAR2

DATE VARCHAR2
Single-Row Functions

Conversion Functions
Implicit Data Type Conversion
 For expression evaluation, the Oracle Server can
automatically convert the following:

From To
VARCHAR2 or CHAR NUMBER

VARCHAR2 or CHAR DATE


Retrieving Data Using the SQL SELECT Statement

Conversion Functions
Explicit Data Type Conversion

TO_NUMBER TO_DATE

NUMBER CHARACTER DATE

TO_CHAR TO_CHAR
Single-Row Functions

Conversion Functions
Using the TO_CHAR Function with Dates
TO_CHAR(date, 'format_model')

 The format model:


 Must be enclosed by single quotation marks
 Is case-sensitive
 Can include any valid date format element
Single-Row Functions

Conversion Functions
Elements of the Date Format Model

Element Result
YYYY Full year in numbers
YEAR Year spelled out (in English)
MM Two-digit value for month
MONTH Full name of the month
MON Three-letter abbreviation of the month
DY Three-letter abbreviation of the day of the week
DAY Full name of the day of the week
DD Numeric day of the month
D Numeric day of the week
Single-Row Functions

Conversion Functions
Using the TO_CHAR Function with Dates
SELECT last_name,
TO_CHAR(hire_date, 'DD Month YYYY')
AS HIREDATE
FROM employees;


20 rows selected.
Single-Row Functions

Conversion Functions
Using the TO_CHAR Function with Numbers
TO_CHAR(number, 'format_model')

 These are some of the format elements that you can use
with the TO_CHAR function to display a number value as a
character:

Element Result
9 Represents a number
0 Forces a zero to be displayed
$ Places a floating dollar sign
L Uses the floating local currency symbol
. Prints a decimal point
, Prints a comma as thousands indicator
Single-Row Functions

Conversion Functions
Using the TO_CHAR Function with Numbers

SELECT TO_CHAR(salary, '$99, 999.00') SALARY


FROM employees
WHERE last_name = 'Ernst';
Single-Row Functions

Conversion Functions
Nesting Functions
 Single-row functions can be nested to any level.
 Nested functions are evaluated from deepest level to the
least deep level.

F3 ( F2 ( F1( col, arg1 ), arg2 ), arg3 )


Step 1 = Result 1

Step 2 = Result 2

Step 3 = Result 3
Single-Row Functions

Conversion Functions
Nesting Functions

SELECT last_name,
UPPER(CONCAT(SUBSTR(LAST_NAME,1,8),'_US'))
FROM employees
WHERE department_id = 60;
Single-Row Functions

General Functions
NVL Function
 Converts a null value to an actual value:
 Data types that can be used are date, character, and
number.
 Data types must match:
 NVL(commission_pct,0)
 NVL(hire_date,'01-JAN-97')
 NVL(job_id,'No Job Yet')
Single-Row Functions

General Functions
Using the NVL Function
1
SELECT last_name, salary, NVL(commission_pct, 0),
(salary*12) + 2
(salary*12*NVL(commission_pct, 0)) AN_SAL
FROM employees;

1 2
Single-Row Functions

General Functions
Using the NVL2 Function

SELECT last_name, salary, commission_pct , 1


NVL2(commission_pct, 'SAL+COMM', 'SAL')
income 2
FROM employees
WHERE department_id IN (50, 80);

1 2
Single-Row Functions

General Functions
Using the NULLIF Function
1
SELECT first_name, LENGTH(first_name) "expr1",
last_name, LENGTH(last_name) "expr2", 2
NULLIF(LENGTH(first_name),
LENGTH(last_name))result 3
FROM employees;

1 2 3
Single-Row Functions

Conditional Expressions
Conditional Expressions

 Provide the use of IF-THEN-ELSE logic within a SQL


statement
 Use two methods:
 CASE expression
 DECODE function
Single-Row Functions

Conditional Expressions
CASE Expression
 Facilitates conditional inquiries by doing the work of an
IF-THEN-ELSE statement:
CASE expr
WHEN comparison_expr1 THEN return_expr1
[WHEN comparison_expr2 THEN return_expr2
WHEN comparison_exprn THEN return_exprn
ELSE else_expr]
END
Single-Row Functions

Conditional Expressions
Using the CASE Expression

SELECT last_name, job_id, salary,


CASE job_id
WHEN 'IT_PROG‘ THEN 1.10*salary
WHEN 'ST_CLERK' THEN 1.15*salary
WHEN 'SA_REP' THEN 1.20*salary
ELSE salary
END "REVISED_SALARY"
FROM employees;


20 rows selected.
Single-Row Functions

Conditional Expressions
DECODE Function
 Facilitates conditional inquiries by doing the work of a
CASE expression or an IF-THEN-ELSE statement:
DECODE(col|expression, search1, result1
[, search2, result2,...,]
[, default])
Single-Row Functions

Conditional Expressions
Using the DECODE Function

SELECT last_name, job_id, salary,


DECODE(job_id, 'IT_PROG', 1.10*salary,
'ST_CLERK', 1.15*salary,
'SA_REP', 1.20*salary,
salary)
REVISED_SALARY
FROM employees;


20 rows selected.
Single-Row Functions

Part 1 Summary

Number Character
SQL Functions Function Function

Conversion Global Expression


Function Function of condition
Functions in SQL

Group Functions
Group Functions

Preview

 Presentation
 Creating groups
 Restricting Group Results
Group Functions

Presentation
What Are Group Functions?

 Group functions operate on sets of rows to give one result


per group.

EMPLOYEES

Maximum salary in
EMPLOYEES table
Group Functions

Presentation
Types of Group Functions
 AVG
 COUNT
 MAX Group

 MIN Functions

 SUM
Group Functions

Presentation
Group Functions: Syntax
SELECT [column,] group_function(column), ...
FROM table
[WHERE condition]
[GROUP BY column]
[ORDER BY column];
Group Functions

Presentation
You can use AVG and SUM for numeric data.
SELECT AVG(salary), MAX(salary),
MIN(salary), SUM(salary)
FROM employees
WHERE job_id LIKE '%REP%';
Group Functions

Presentation
You can use MIN and MAX for numeric, character,
and date data types.

SELECT MIN(hire_date), MAX(hire_date)


FROM employees;
Group Functions

Presentation
Using the COUNT Function

 COUNT(*) returns the number of rows in a table:


SELECT COUNT(*)
FROM employees
WHERE department_id = 50;

 COUNT(expr) returns the number of rows with non null


values for the expr:
SELECT COUNT(commission_pct)
FROM employees
WHERE department_id = 80;
Group Functions

Presentation
Using the DISTINCT Keyword
 COUNT(DISTINCT expr) returns the number of distinct
non-null values of the expr.
 To display the number of distinct department values in
the EMPLOYEES table:

SELECT COUNT(DISTINCT department_id)


FROM employees;
Group Functions

Presentation
Group Functions and Null Values

 Group functions ignore null values in the column:


SELECT AVG(commission_pct)
FROM employees;

 The NVL function forces group functions to include null


values:
SELECT AVG(NVL(commission_pct, 0))
FROM employees;
Group Functions

Creating Groups
Creating Groups of Data

EMPLOYEES
4400
9500

3500 Average salary


in EMPLOYEES
table for each
6400 department

10033
Group Functions

Creating Groups
GROUP BY Clause Syntax

SELECT column, group_function(column)


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];

 You can divide rows in a table into smaller groups by


using the GROUP BY clause.
Group Functions

Creating Groups
Using the GROUP BY Clause

SELECT department_id , AVG(salary)


FROM employees
GROUP BY department_id;
Group Functions

Creating Groups
Using the GROUP BY Clause
 The GROUP BY column does not have to be in the
SELECT list.
SELECT AVG(salary)
FROM employees
GROUP BY department_id ;
Group Functions

Creating Groups
Grouping by More Than One Column

EMPLOYEES

Add the salaries


in the
EMPLOYEES
table for each job,
grouped by
department.
Group Functions

Creating Groups
Using the GROUP BY Clause on Multiple Columns

SELECT department_id dept_id, job_id, SUM(salary)


FROM employees
GROUP BY department_id, job_id ;
Group Functions

Creating Groups
Illegal Queries Using Group Functions
 You use the HAVING clause to restrict groups.
 You cannot use group functions in the WHERE clause.

SELECT department_id, AVG(salary)


FROM employees
WHERE AVG(salary) > 8000
GROUP BY department_id;

WHERE AVG(salary) > 8000


*
ERROR at line 3:
ORA-00934: group function is not allowed
here

Cannot use the WHERE clause to restrict groups


Group Functions

Restricting Group Results

EMPLOYEES

The maximum
salary
per department
whien it is
greater than
$10,000
Group Functions

Restricting Group Results


Restricting Group Results with the HAVING Clause

 When you use the HAVING clause, the Oracle server


restricts groups as follows:
 Rows are grouped.
 The group function is applied.
 Groups matching the HAVING clause are displayed.

SELECT column, group_function


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
Group Functions

Restricting Group Results


Using the HAVING Clause

SELECT department_id, MAX(salary)


FROM employees
GROUP BY department_id
HAVING MAX(salary)>10000;
Group Functions

Restricting Group Results


Using the HAVING Clause

SELECT job_id, SUM(salary) PAYROLL


FROM employees
WHERE job_id NOT LIKE '%REP%'
GROUP BY job_id
HAVING SUM(salary) > 13000
ORDER BY SUM(salary);
Group Functions

Restricting Group Results


Display the maximum average salary:

SELECT MAX(AVG(salary))
FROM employees
GROUP BY department_id;
Group Functions

Part 2 Summary

COUNT, MAX,
MIN and AVG

Use the GROUP


BY clause
Use the HAVING
clause
Labs: Functions in SQL

Part 3 Stop-and-think

Do you have any questions ?

You might also like