154
Campus-Booster ID: **XXXXX www.supinfo.com Copyright © SUPINFO. All rights reserved Basic Orders

Campus-Booster ID: **XXXXX Copyright © SUPINFO. All rights reserved Basic Orders

Embed Size (px)

Citation preview

Page 1: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Campus-Booster ID: **XXXXX

www.supinfo.com

Copyright © SUPINFO. All rights reserved

Basic Orders

Page 2: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Votre formateur…

Formation Etudiant SUPINFO en 4ème année

SCT Oracle pour la 2ème année

Certifications

1Z0-007 Introduction to Oracle 9i SQL

1Z0-147 PL/SQL Development

Pour me contacter [email protected] (MSN)

SUPINFOne : 145776

ID Booster : 45776

Sébastien VITA

Basic Orders

Page 3: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Course objectives

Execute a basic SELECT statement

Limit and sort the rows that are retrieved by a query

Describe various types of functions that are available in SQL

Describe the use of group functions

By completing this course, you will be able to:

Basic Orders

Page 4: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Course topics

Course’s plan:

Basic Orders

Retrieving Data Using the SQL SELECT Statement

Restricting and Sorting Data

Using Single-Row Functions to Customize Output

Reporting Aggregated Data Using the Group Functions

Page 5: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

Basic Orders

Page 6: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

What is the SELECT statement ?

Arithmetic Expressions.

Other SELECT Possibilities.

Using iSQL*Plus.

Retrieving Data Using the SQL SELECT Statement

Preview

Page 7: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

What is the SELECT statement ?Retrieving Data Using the SQL SELECT Statement

Projection Selection

Join

Table 1

Table 2

Table 1

Table 1

Page 8: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

SELECT identifies the column to be displayed

FROM identifies the table containing those columns

Retrieving Data Using the SQL SELECT Statement

What is the SELECT statement ?Basic SELECT statement:

SELECT *|{[DISTINCT] column|expression [alias],...}FROM table;

Page 9: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

What is the SELECT statement ?Selecting all columns:

SELECT *FROM departments;

Page 10: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

What is the SELECT statement ?Selecting specific columns:

SELECT department_id, location_idFROM departments;

Page 11: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

SQL statements are not case-sensitive.

SQL statements can be on one or more lines.

Keywords cannot be abbreviated or split across lines.

Clauses are usually placed on separate lines.

Indents are used to enhance readability.

In iSQL*Plus, SQL statements can optionally be terminated by a semicolon (;). Semicolons are required if you execute multiple SQL statements.

In SQL*plus, you are required to end each SQL statement with a semicolon (;).

Retrieving Data Using the SQL SELECT Statement

What is the SELECT statement ?

Page 12: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

iSQL*Plus:

Default heading alignment: Center

Default heading display: Uppercase

SQL*Plus:

Character and Date column headings are left aligned

Number column headings are right-aligned

Default heading display: Uppercase

Retrieving Data Using the SQL SELECT Statement

What is the SELECT statement ?Column Heading Defaults:

Page 13: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Operator Description

+ Add

- Subtract

Multiply

Divide

*

/

Retrieving Data Using the SQL SELECT Statement

Arithmetic ExpressionsCreate expressions with number and date data by using

arithmetic operators.

Page 14: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

Arithmetic ExpressionsUsing Arithmetic Operators:

SELECT last_name, salary, salary + 300FROM employees;

Page 15: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

Arithmetic ExpressionsOperator Precedence:

SELECT last_name, salary, 12*salary+100FROM employees;

SELECT last_name, salary, 12*(salary+100)FROM employees;

Page 16: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

A null is a value that is unavailable, unassigned, unknown, or inapplicable.

A null is not the same as a zero or a blank space.

Retrieving Data Using the SQL SELECT Statement

Arithmetic ExpressionsDefining a Null Value:

SELECT last_name, job_id, salary, commission_pctFROM employees;

Page 17: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Arithmetic expressions containing a null value evaluate to null.

Retrieving Data Using the SQL SELECT Statement

Arithmetic ExpressionsNull Values in Arithmetic Expressions:

SELECT last_name, 12*salary*commission_pctFROM employees;

Page 18: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

A column alias:

Renames a column heading

Is useful with calculations

Immediately follows the column name (There can also be the optional AS keyword between the column name and alias.)

Requires double quotation marks if it contains spaces or special characters or if it is case sensitive

Retrieving Data Using the SQL SELECT Statement

Other SELECT PossibilitiesDefining a Column Alias:

Page 19: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

Other SELECT PossibilitiesUsing Column Aliases:

SELECT last_name AS name , commission_pct commFROM employees;

SELECT last_name "Name" , salary*12 "Annual Salary"FROM employees;

Page 20: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Links columns or character strings to other columns

Is represented by two vertical bars (||)

Creates a resultant column that is a character expression

Retrieving Data Using the SQL SELECT Statement

Other SELECT PossibilitiesConcatenation Operator:

SELECT last_name || job_id AS "Employees"FROM employees;

Page 21: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

A literal is a character, a number, or a date that is included in the SELECT statement.

Date and character literal values must be enclosed by single quotation marks.

Each character string is output once for each row returned.

Retrieving Data Using the SQL SELECT Statement

Other SELECT PossibilitiesLiteral Character Strings:

Page 22: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

Other SELECT PossibilitiesUsing Literal Character Strings:

SELECT last_name || ' is a ' || job_id AS "Employee Details"FROM employees;

Page 23: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Specify your own quotation mark delimiter

Choose any delimiter

Increase readability and usability

Retrieving Data Using the SQL SELECT Statement

Other SELECT PossibilitiesAlternative Quote (q) Operator:

SELECT department_name || q'[, it's assigned Manager Id: ]' || manager_id AS "Department and Manager"FROM departments;

Page 24: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

SELECT DISTINCT department_idFROM employees;

The default display of queries is all rows, including duplicate rows.

Retrieving Data Using the SQL SELECT Statement

Other SELECT PossibilitiesDuplicate Rows:

SELECT department_idFROM employees;

Page 25: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

SQL statements

Internet browser

iSQL*Plus commands

Query Result

Formatted report

Client

Retrieving Data Using the SQL SELECT Statement

Using iSQL*PlusSQL and iSQL*Plus Interaction:

Page 26: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

SQL iSQL*Plus

A language An environment

ANSI standard Oracle-proprietary

Keywords can be abbreviated

Commands do not allow manipulation of values in the database

Keyword cannot be abbreviated

Statements manipulate data and table definitions in the database

Retrieving Data Using the SQL SELECT Statement

Using iSQL*PlusSQL Statements Versus iSQL*Plus Commands:

Runs on a browser

Centrally loaded; does not have to be implemented on each machine

Page 27: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

After you log in to iSQL*Plus, you can:

Describe table structures

Enter, execute, and edit SQL statements

Save or append SQL statements to files

Execute or edit statements that are stored in saved script files

Retrieving Data Using the SQL SELECT Statement

Overview of iSQL*Plus:

Using iSQL*Plus

Page 28: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

From your browser environment

Retrieving Data Using the SQL SELECT Statement

Logging In to iSQL*Plus:

Using iSQL*Plus

Page 29: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

iSQL*Plus Environment:

Using iSQL*Plus

12 3 4 5

6

7

8 9

Page 30: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

DESCRIBE employees

Use the iSQL*Plus DESCRIBE command to display the structure of a table:

Retrieving Data Using the SQL SELECT Statement

Using iSQL*PlusDisplaying Table Structure:

DESC[RIBE] tablename

Example:

Page 31: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

Using iSQL*PlusInteracting with Script Files:

1

2

Page 32: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

Using iSQL*PlusInteracting with Script Files:

Page 33: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

Using iSQL*PlusInteracting with Script Files:

1

Page 34: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

Using iSQL*PlusInteracting with Script Files:

32

Page 35: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

Using iSQL*PlusiSQL*Plus History Page:

2

1

3

Page 36: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

Using iSQL*PlusiSQL*Plus History Page:

5

4

Page 37: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

Using iSQL*PlusSetting iSQL*Plus Preferences:

2

1

3

Page 38: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

Using iSQL*PlusSetting the Output Location Preference:

1

2

Page 39: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

What is the SELECT

statement

What is the SELECT

statement

Arithmetic ExpressionsArithmetic

Expressions

Using iSQL*Plus

Using iSQL*Plus

Part 1 Summary Retrieving Data Using the SQL SELECT Statement

Other SELECT Possibilities

Other SELECT Possibilities

Page 40: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Part 1 Stop-and-thinkRetrieving Data Using the SQL SELECT Statement

Do you have any questions ?

Page 41: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Restricting and Sorting Data

Basic Orders

Page 42: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Preview

How to Restrict Data

Comparison Conditions

Logical Conditions

How to Sort Data

Substitution Variables

Restricting and Sorting Data

Page 43: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Restricting and Sorting Data

How to Restrict Data

“retrieve all employees in department 90”

Page 44: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Restrict the rows that are returned by using the WHERE clause:

Restricting and Sorting Data

How to Restrict DataLimiting the Rows That Are Selected:

SELECT *|{[DISTINCT] column|expression [alias],...} FROM table[WHERE condition(s)] ;

The WHERE clause follows the FROM clause.

Page 45: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Restricting and Sorting Data

How to Restrict DataUsing the WHERE Clause:

SELECT employee_id, last_name, job_id, department_idFROM employeesWHERE department_id = 90 ;

Page 46: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Character strings and date values are enclosed by single quotation marks.

Character values are case-sensitive, and date values are format-sensitive.

The default date format is DD-MON-RR.

Restricting and Sorting Data

How to Restrict DataCharacter Strings and Dates:

SELECT last_name, job_id, department_idFROM employeesWHERE last_name = 'Whalen' ;

Page 47: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Operator Meaning

= Equal to

> Greater than

Greater than or equal to

Less than

>=

<

Restricting and Sorting Data

Comparison ConditionsCreate expressions with number and date data by using

arithmetic operators.

<= Less than or equal to

Not equal to

Between two values (inclusive)

<>

BETWEEN … AND …

IN (set) Match any of a list of values

Match a character pattern

Is a null value

LIKE

IS NULL

Page 48: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Restricting and Sorting Data

Comparison ConditionsUsing Comparison Conditions:

SELECT last_name, salaryFROM employeesWHERE salary <= 3000 ;

Page 49: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Use the BETWEEN condition to display rows based on a range of values:

Restricting and Sorting Data

Comparison ConditionsUsing the BETWEEN Condition:

SELECT last_name, salaryFROM employeesWHERE salary BETWEEN 2500 AND 3500 ;

Lower limit Upper limit

Page 50: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Use the IN membership condition to test for values in a list:

Restricting and Sorting Data

Comparison ConditionsUsing the IN Condition:

SELECT employee_id, last_name, salary, manager_idFROM employeesWHERE manager_id IN (100, 101, 201) ;

Page 51: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Use the LIKE condition to perform wildcard searches of valid search string values.

Search conditions can contain either literal characters or numbers:

% denotes zero or many characters.

_ denotes one character.

Restricting and Sorting Data

Comparison ConditionsUsing the LIKE Condition:

SELECT first_nameFROM employeesWHERE first_name LIKE 'S%' ;

Page 52: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

You can combine pattern-matching characters:

Restricting and Sorting Data

Comparison ConditionsUsing the LIKE Condition:

SELECT first_nameFROM employeesWHERE first_name LIKE '_o%' ;

Page 53: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Restricting and Sorting Data

Comparison Conditions

You can use the ESCAPE identifier to search for the actual % and _ symbols.

ESCAPE identifier:

SELECT employee_id, job_idFROM employeesWHERE job_id LIKE 'SA\_R%' ESCAPE '\';

Page 54: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Test for nulls with the IS NULL operator.

Restricting and Sorting Data

Comparison ConditionsUsing the IS NULL Condition:

SELECT last_name, manager_idFROM employeesWHERE manager_id IS NULL ;

Page 55: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Operator Meaning

AND Returns TRUE if both component conditions are true

OR Returns TRUE if either component condition is true

Returns TRUE if the following condition is false

NOT

Restricting and Sorting Data

Logical Conditions

Page 56: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

AND requires both conditions to be true:

Restricting and Sorting Data

Logical ConditionsUsing the AND Operator:

SELECT employee_id, last_name, job_id, salaryFROM employeesWHERE salary >= 10000AND job_id LIKE '%MAN%';

Page 57: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

OR requires either condition to be true:

Restricting and Sorting Data

Logical ConditionsUsing the OR Operator:

SELECT employee_id, last_name, job_id, salaryFROM employeesWHERE salary >= 10000OR job_id LIKE '%MAN%';

Page 58: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Restricting and Sorting Data

Logical ConditionsUsing the NOT Operator:

SELECT last_name, job_idFROM employeesWHERE job_id NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP‘);

Page 59: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Order Operators

1 Arithmetic operators

2 Concatenation operator

Comparison conditions

IS [NOT] NULL, LIKE, [NOT] IN

3

4

Restricting and Sorting Data

Logical ConditionsRules of Precedence

5 [NOT] BETWEEN

Not equal to

NOT logical condition

6

7

8 AND logical condition

OR logical condition9

You can use parentheses to override rules of precedence.

Page 60: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Restricting and Sorting Data

Logical ConditionsRules of Precedence

SELECT last_name, job_id, salaryFROM employeesWHERE job_id = 'SA_REP'OR job_id = 'AD_PRES'AND salary > 15000;

SELECT last_name, job_id, salaryFROM employeesWHERE (job_id = 'SA_REP'OR job_id = 'AD_PRES')AND salary > 15000;

Page 61: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Sort retrieved rows with the ORDER BY clause:

ASC: ascending order, default

DESC: descending order

The ORDER BY clause comes last in the SELECT statement:

Restricting and Sorting Data

How to Sort DataUsing the ORDER BY Clause:

SELECT last_name, job_id, department_id, hire_dateFROM employeesORDER BY hire_date ;

Page 62: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Sorting in descending order:

Restricting and Sorting Data

How to Sort DataSorting:

SELECT last_name, job_id, department_id, hire_dateFROM employeesORDER BY hire_date DESC ;

Sorting by column alias:SELECT employee_id, last_name, salary*12 annsalFROM employeesORDER BY annsal ;

Sorting by multiple columns:SELECT last_name, department_id, salaryFROM employeesORDER BY department_id, salary DESC;

Page 63: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Restricting and Sorting Data

Substitution Variables

I want to query different values.

... salary = ? ...

... department_id = ? ...

... last_name = ? ...

Page 64: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Use iSQL*Plus substitution variables to:

Temporarily store values with single-ampersand (&) and double-ampersand (&&) substitution

Use substitution variables to supplement the following:

WHERE conditions

ORDER BY clauses

Column expressions

Table names

Entire SELECT statements

Restricting and Sorting Data

Substitution Variables

Page 65: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Use a variable prefixed with an ampersand (&) to prompt the user for a value:

Restricting and Sorting Data

Substitution Variables

SELECT employee_id, last_name, salary, department_idFROM employeesWHERE employee_id = &employee_num ;

Page 66: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Restricting and Sorting Data

Substitution VariablesUsing the & Substitution Variable:

2

1

Page 67: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Use single quotation marks for date and character values:

Restricting and Sorting Data

Substitution Variables

SELECT last_name, department_id, salary*12FROM employeesWHERE job_id = '&job_title';

Character and Date Values with Substitution Variables:

Page 68: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Restricting and Sorting Data

Substitution Variables

SELECT employee_id, last_name, job_id, &column_nameFROM employeesWHERE &conditionORDER BY &order_column ;

Specifying Column Names, Expressions, and Text:

Page 69: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Use the double ampersand (&&) if you want to reuse the variable value without prompting the user each time:

Restricting and Sorting Data

Substitution Variables

SELECT employee_id, last_name, job_id, &&column_nameFROM employeesORDER BY &column_name ;

Using the && Substitution Variable:

Page 70: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Use the iSQL*Plus DEFINE command to create and assign a value to a variable.

Use the iSQL*Plus UNDEFINE command to remove a variable.

Restricting and Sorting Data

Substitution Variables

DEFINE employee_num = 200

SELECT employee_id, last_name, salary, department_idFROM employeesWHERE employee_id = &employee_num ;

UNDEFINE employee_num

Using the iSQL*Plus DEFINE Command:

Page 71: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Use the VERIFY command to toggle the display of the substitution variable, both before and after iSQL*Plus replaces substitution variables with values:

Restricting and Sorting Data

Substitution Variables

SET VERIFY ON

SELECT employee_id, last_name, salary, department_idFROM employeesWHERE employee_id = &employee_num;

Using the VERIFY Command:

old 3: WHERE employee_id = &employee_numnew 3: WHERE employee_id = 200

Page 72: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

How to Restrict Data

How to Restrict Data

Comparison Conditions

Comparison Conditions

How to Sort Data

How to Sort Data

Part 2 Summary Restricting and Sorting Data

Logical Conditions

Logical Conditions

Substitution Variables

Substitution Variables

Page 73: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Part 2 Stop-and-thinkRestricting and Sorting Data

Do you have any questions ?

Page 74: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Using Single-Row Functions to Customize Output

Basic Orders

Page 75: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

SQL Functions.

Character Functions.

Number Functions.

Date Functions.

Conversion Functions.

General Functions.

Conditional Expressions

Using Single-Row Functions to Customize Output

Preview

Page 76: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

SQL FunctionsUsing Single-Row Functions to Customize Output

FUNCTION

Result Value

OutputInput

arg 1

arg 2

arg n

Functions performs

actions

Page 77: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

SQL FunctionsUsing Single-Row Functions to Customize Output

FUNCTION

Single-row functions

Multiple-row functions

Return one result per row

Return one result per set of rows

Two Types of SQL Functions

Page 78: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Manipulate data items

Accept arguments and return one value

Act on each row that is returned

Return one result per row

May modify the data type

Can be nested

Accept arguments that can be a column or an expression

Using Single-Row Functions to Customize Output

SQL FunctionsSingle-row functions:

function_name [(arg1, arg2,...)]

Page 79: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

SQL FunctionsUsing Single-Row Functions to Customize Output

Single-row functions:

Conversion Date

Character

General NumberSingle-rowfunctions

Page 80: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Character FunctionsUsing Single-Row Functions to Customize Output

Case-manipulation

functions

Character

functions

Character-manipulation

functions

LOWER

UPPER

INITCAP

CONCATSUBSTRLENGTHINSTRLPAD | RPADTRIMREPLACE

Page 81: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Function Result

LOWER('SQL Course') sql course

UPPER('SQL Course') SQL COURSE

Sql CourseINITCAP('SQL Course')

Using Single-Row Functions to Customize Output

Character FunctionsUsing Case-Manipulation Functions

These functions convert case for character strings:

Page 82: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Using Single-Row Functions to Customize Output

Character Functions

SELECT employee_id, last_name, department_idFROM employeesWHERE last_name = 'higgins' ;

no rows selected

SELECT employee_id, last_name, department_idFROM employeesWHERE LOWER(last_name) = 'higgins';

Using Case-Manipulation Functions

Display the employee number, name, and department number for employee Higgins:

Page 83: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Function Result

CONCAT('Hello', 'World') HelloWorld

SUBSTR('HelloWorld',1,5) Hello

10

6

LENGTH('HelloWorld')

INSTR('HelloWorld', 'W')

Using Single-Row Functions to Customize Output

Character FunctionsThese functions manipulate character strings:

*****24000LPAD(salary,10,'*')

24000*****RPAD(salary, 10, '*')

BLACK and BLUEREPLACE('JACK and JUE','J','BL')

elloWorldTRIM('H' FROM 'HelloWorld')

Page 84: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Character FunctionsUsing Single-Row Functions to Customize Output

SELECT employee_id, CONCAT(first_name, last_name) NAME,job_id, LENGTH (last_name), INSTR(last_name, 'a') "Contains 'a'?"FROM employeesWHERE SUBSTR(job_id, 4) = 'REP';

Using the Character-Manipulation Functions

1

1

2

2 3

3

Page 85: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Function Result

ROUND(45.926, 2) 45.93

TRUNC(45.926, 2) 45.92

100MOD(1600, 300)

Using Single-Row Functions to Customize Output

Number Functions

ROUND: Rounds value to specified decimal

TRUNC: Truncates value to specified decimal

MOD: Returns remainder of division

Page 86: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Number FunctionsUsing Single-Row Functions to Customize Output

Using the ROUND Function

SELECT ROUND(45.923,2), ROUND(45.923,0), ROUND(45.923,-1)FROM DUAL;

1

1

2

2 3

3

DUAL is a dummy table that you can use to view results from functions and calculations.

Page 87: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Number FunctionsUsing Single-Row Functions to Customize Output

Using the TRUNC Function

SELECT TRUNC(45.923,2), TRUNC(45.923), TRUNC(45.923,-1)FROM DUAL;

1

1

2

2

3

3

Page 88: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Number Functions

Using Single-Row Functions to Customize Output

Using the MOD Function

SELECT last_name, salary, MOD(salary, 5000)FROM employeesWHERE job_id = 'SA_REP';

For all employees with job title of Sales Representative, calculate the remainder of the salary after it is divided by 5,000.

Page 89: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Date FunctionsUsing Single-Row Functions to Customize Output

Working with Dates The Oracle database stores dates in an internal numeric

format: century, year, month, day, hours, minutes, and seconds.

The default date display format is DD-MON-RR.

Enables you to store 21st-century dates in the 20th century by specifying only the last two digits of the year

Enables you to store 20th-century dates in the 21st century in the same way

SELECT last_name, hire_dateFROM employeesWHERE hire_date < '01-FEB-88';

Page 90: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Date FunctionsUsing Single-Row Functions to Customize Output

Working with Dates

SYSDATE is a function that returns:

Date

Time

Page 91: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Date FunctionsUsing Single-Row Functions to Customize Output

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.

Page 92: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Date FunctionsUsing Single-Row Functions to Customize Output

Using Arithmetic Operators with Dates

SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKSFROM employeesWHERE department_id = 90;

Page 93: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Function Result

MONTHS_BETWEEN Number of months between two dates

ADD_MONTHS Add calendar months to date

Next day of the date specifiedNEXT_DAY

Using Single-Row Functions to Customize Output

Date Functions

LAST_DAY Last day of the month

ROUND Round date

Truncate dateTRUNC

Page 94: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Function Result

MONTHS_BETWEEN

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

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

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

Using Single-Row Functions to Customize Output

Date Functions

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

Page 95: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Function Result

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

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

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

Using Single-Row Functions to Customize Output

Date FunctionsExample

Assume SYSDATE = '25-JUL-03':

TRUNC(SYSDATE,'YEAR') 01-JAN-03

Page 96: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Conversion FunctionsUsing Single-Row Functions to Customize Output

Implicit data type conversion

Explicit data type conversion

Data typeconversion

Page 97: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

From To

VARCHAR2 or CHAR NUMBER

VARCHAR2 or CHAR DATE

VARCHAR2NUMBER

Using Single-Row Functions to Customize Output

Conversion FunctionsImplicit Data Type Conversion

DATE VARCHAR2

For assignments, the Oracle server can automatically convert the following:

Page 98: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

From To

VARCHAR2 or CHAR NUMBER

VARCHAR2 or CHAR DATE

Using Single-Row Functions to Customize Output

Conversion FunctionsImplicit Data Type Conversion

For expression evaluation, the Oracle Server can automatically convert the following:

Page 99: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Retrieving Data Using the SQL SELECT Statement

Conversion FunctionsExplicit Data Type Conversion

TO_DATETO_DATE

DATEDATE

TO_CHARTO_CHAR

TO_NUMBERTO_NUMBER

TO_CHARTO_CHAR

NUMBERNUMBER CHARACTERCHARACTER

Page 100: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

The format model:

Must be enclosed by single quotation marks

Is case-sensitive

Can include any valid date format element

Has an fm element to remove padded blanks or suppress leading zeros

Is separated from the date value by a comma

Using Single-Row Functions to Customize Output

Conversion FunctionsUsing the TO_CHAR Function with Dates

TO_CHAR(date, 'format_model')

Page 101: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Element Result

YYYY Full year in numbers

YEAR Year spelled out (in English)

Two-digit value for month

Full name of the month

MM

MONTH

Using Single-Row Functions to Customize Output

Conversion FunctionsElements of the Date Format Model

Three-letter abbreviation of the monthMON

Three-letter abbreviation of the day of the weekDY

Full name of the day of the weekDAY

Numeric day of the monthDD

Page 102: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Time elements format the time portion of the date:

Add character strings by enclosing them in double quotation marks:

Number suffixes spell out numbers:

Using Single-Row Functions to Customize Output

Conversion FunctionsElements of the Date Format Model

HH24:MI:SS AM 15:45:32 PM

DD "of" MONTH 12 of OCTOBER

ddspth fourteenth

Page 103: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Using Single-Row Functions to Customize Output

Conversion FunctionsUsing the TO_CHAR Function with Dates

SELECT last_name, TO_CHAR(hire_date, 'fmDD Month YYYY') AS HIREDATEFROM employees;

20 rows selected.

Page 104: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Element Result

9 Represents a number

0 Forces a zero to be displayed

Places a floating dollar sign$

Using Single-Row Functions to Customize Output

Conversion FunctionsUsing the TO_CHAR Function with Numbers

L Uses the floating local currency symbol

. Prints a decimal point

TO_CHAR(number, 'format_model')

, Prints a comma as thousands indicator

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

Page 105: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Using Single-Row Functions to Customize Output

Conversion FunctionsUsing the TO_CHAR Function with Numbers

SELECT TO_CHAR(salary, '$99,999.00') SALARYFROM employeesWHERE last_name = 'Ernst';

Page 106: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Convert a character string to a number format using the TO_NUMBER function:

Convert a character string to a date format using the TO_DATE function:

These functions have an fx modifier. This modifier specifies the exact matching for the character argument and date format model of a TO_DATE function.

Using Single-Row Functions to Customize Output

Conversion FunctionsUsing the TO_NUMBER and TO_DATE Functions:

TO_NUMBER(char[, 'format_model'])

TO_DATE(char[, 'format_model'])

Page 107: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Using Single-Row Functions to Customize Output

Conversion FunctionsRR Date Format

If two digits of the

current year are:

0-49 50-99

0-49

If the specified two-digit year is:

50-99

The return date is in the current century

The return date is in the century before

the current one

The return date is in the century after the

current one

The return date is in the current century

Page 108: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Using Single-Row Functions to Customize Output

Conversion FunctionsRR Date Format

Current Year

1995

1995

2001

2001

Specified Date

27-OCT-95

27-OCT-17

27-OCT-17

27-OCT-95

RR Format

1995

2017

2017

1995

YY Format

1995

1917

2017

2095

Page 109: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

To find employees hired prior to 1990, use the RR date format, which produces the same results whether the command is run in 1999 or now:

Using Single-Row Functions to Customize Output

Conversion FunctionsExample of RR Date Format

SELECT last_name,TO_CHAR(hire_date,'DD-Mon-YYYY')FROM employeesWHERE hire_date < TO_DATE('01-Jan-90','DD-Mon-RR');

Page 110: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Single-row functions can be nested to any level.

Nested functions are evaluated from deepest level to the least deep level.

Using Single-Row Functions to Customize Output

Conversion FunctionsNesting Functions

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

Step 3 = Result 3

Step 2 = Result 2

Step 1 = Result 1

Page 111: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Using Single-Row Functions to Customize Output

Conversion FunctionsNesting Functions

SELECT last_name,UPPER(CONCAT(SUBSTR(LAST_NAME,1,8),'_US'))

FROM employeesWHERE department_id = 60;

Page 112: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

The following functions work with any data type and pertain to using nulls:

NVL (expr1, expr2)

NVL2 (expr1, expr2, expr3)

NULLIF (expr1, expr2)

COALESCE (expr1, expr2, ..., exprn)

Using Single-Row Functions to Customize Output

General Functions

Page 113: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

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')

Using Single-Row Functions to Customize Output

General FunctionsNVL Function

Page 114: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Using Single-Row Functions to Customize Output

General FunctionsUsing the NVL Function

SELECT last_name, salary, NVL(commission_pct, 0),(salary*12) + (salary*12*NVL(commission_pct, 0)) AN_SAL

FROM employees;

1

1 2

2

Page 115: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Using Single-Row Functions to Customize Output

General FunctionsUsing the NVL2 Function

SELECT last_name, salary, commission_pct , NVL2(commission_pct, 'SAL+COMM', 'SAL') incomeFROM employees WHERE department_id IN (50, 80);

1

1 2

2

Page 116: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Using Single-Row Functions to Customize Output

General FunctionsUsing the NULLIF Function

SELECT first_name, LENGTH(first_name) "expr1",last_name, LENGTH(last_name) "expr2",NULLIF(LENGTH(first_name),

LENGTH(last_name))resultFROM employees;

1

1 2

2

3

3

Page 117: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

The advantage of the COALESCE function over the NVL function is that the COALESCE function can take multiple alternate values.

If the first expression is not null, the COALESCE function returns that expression; otherwise, it does a COALESCE of the remaining expressions.

Using Single-Row Functions to Customize Output

Conditional ExpressionsUsing the COALESCE Function

Page 118: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Using Single-Row Functions to Customize Output

Conditional ExpressionsUsing the COALESCE Function

SELECT last_name, COALESCE(manager_id,commission_pct, -1) commFROM employeesORDER BY commission_pct;

Page 119: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

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

Use two methods:

CASE expression

DECODE function

Using Single-Row Functions to Customize Output

Conditional ExpressionsConditional Expressions

Page 120: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Facilitates conditional inquiries by doing the work of an IF-THEN-ELSE statement:

Using Single-Row Functions to Customize Output

Conditional ExpressionsCASE Expression

CASE expr WHEN comparison_expr1 THEN return_expr1 [WHEN comparison_expr2 THEN return_expr2 WHEN comparison_exprn THEN return_exprn ELSE else_expr]END

Page 121: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Using Single-Row Functions to Customize Output

Conditional ExpressionsUsing 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.

Page 122: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Facilitates conditional inquiries by doing the work of a CASE expression or an IF-THEN-ELSE statement:

Using Single-Row Functions to Customize Output

Conditional ExpressionsDECODE Function

DECODE(col|expression, search1, result1 [, search2, result2,...,] [, default])

Page 123: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Using Single-Row Functions to Customize Output

Conditional ExpressionsUsing 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_SALARYFROM employees;

20 rows selected.

Page 124: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Display the applicable tax rate for each employee in department 80:

Using Single-Row Functions to Customize Output

Conditional ExpressionsUsing the DECODE Function

SELECT last_name, salary, DECODE (TRUNC(salary/2000, 0), 0, 0.00, 1, 0.09, 2, 0.20, 3, 0.30, 4, 0.40, 5, 0.42, 6, 0.44,

0.45) TAX_RATEFROM employeesWHERE department_id = 80;

Page 125: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

SQL FunctionsSQL FunctionsNumber FunctionNumber Function

Conversion Function

Conversion Function

Part 3 Summary Using Single-Row Functions to Customize Output

Character Function

Character Function

Expression of conditionExpression of condition

Global FunctionGlobal

Function

Page 126: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Part 3 Stop-and-thinkUsing Single-Row Functions to Customize Output

Do you have any questions ?

Page 127: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated DataUsing the Group Functions

Basic Orders

Page 128: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Presentation

Creating groups

Restricting Group Results

Reporting Aggregated Data Using the Group Functions

Preview

Page 129: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Group functions operate on sets of rows to give one result per group.

Reporting Aggregated Data Using the Group Functions

What Are Group Functions?

EMPLOYEES

Presentation

Maximum salary in EMPLOYEES table

Page 130: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Presentation

AVG

COUNT

MAX

MIN

STDDEV

SUM

VARIANCE

Types of Group Functions

Group

Functions

Page 131: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Presentation

SELECT [column,] group_function(column), ... FROM table[WHERE condition][GROUP BY column][ORDER BY column];

Group Functions: Syntax

Page 132: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Presentation

SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary)FROM employeesWHERE job_id LIKE '%REP%';

You can use AVG and SUM for numeric data.

Page 133: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Presentation

SELECT MIN(hire_date), MAX(hire_date)FROM employees;

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

Page 134: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

COUNT(expr) returns the number of rows with non null values for the expr:

Reporting Aggregated Data Using the Group Functions

Presentation

SELECT COUNT(*)FROM employeesWHERE department_id = 50;

Using the COUNT Function

SELECT COUNT(commission_pct)FROM employeesWHERE department_id = 80;

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

Page 135: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

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:

Reporting Aggregated Data Using the Group Functions

PresentationUsing the DISTINCT Keyword

SELECT COUNT(DISTINCT department_id)FROM employees;

Page 136: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Presentation

SELECT AVG(commission_pct)FROM employees;

Group Functions and Null Values

SELECT AVG(NVL(commission_pct, 0))FROM employees;

Group functions ignore null values in the column:

The NVL function forces group functions to include null values:

Page 137: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Creating Groups of Data

EMPLOYEES

4400

9500

3500

6400

10033

Creating Groups

Average salaryin EMPLOYEEStable for eachdepartment

Page 138: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

You can divide rows in a table into smaller groups by using the GROUP BY clause.

Reporting Aggregated Data Using the Group Functions

Creating GroupsGROUP BY Clause Syntax

SELECT column, group_function(column) FROM table[WHERE condition][GROUP BY group_by_expression][ORDER BY column];

Page 139: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Creating Groups

SELECT department_id , AVG(salary)FROM employeesGROUP BY department_id;

Using the GROUP BY Clause

All columns in the SELECT list that are not in group functions must be in the GROUP BY clause.

Page 140: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Creating Groups

SELECT AVG(salary)FROM employeesGROUP BY department_id ;

Using the GROUP BY Clause

The GROUP BY column does not have to be in the SELECT list.

Page 141: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Grouping by More Than One Column

EMPLOYEES

Creating Groups

Add the salariesin the EMPLOYEEStable for each job,grouped bydepartment.

Page 142: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Creating Groups

SELECT department_id dept_id, job_id, SUM(salary)FROM employeesGROUP BY department_id, job_id ;

Using the GROUP BY Clause on Multiple Columns

Page 143: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Creating Groups

SELECT department_id, COUNT(last_name)FROM employees;

Illegal Queries Using Group Functions

Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause:

SELECT department_id, COUNT(last_name) *ERROR at line 1:ORA-00937: not a single-group group function

Column missing in the GROUP BY clause

Page 144: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Creating Groups

SELECT department_id, AVG(salary)FROM employeesWHERE AVG(salary) > 8000GROUP BY department_id;

Illegal Queries Using Group Functions

You cannot use the WHERE clause to restrict groups.

You use the HAVING clause to restrict groups.

You cannot use group functions in the WHERE clause.

WHERE AVG(salary) > 8000 *ERROR at line 3:ORA-00934: group function is not allowed here

Cannot use the WHERE clause to restrict groups

Page 145: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

EMPLOYEES

Restricting Group Results

The maximum salaryper departmentwhien it isgreater than$10,000

Page 146: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Restricting Group Results

SELECT column, group_function FROM table[WHERE condition][GROUP BY group_by_expression][HAVING group_condition][ORDER BY column];

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.

Page 147: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Restricting Group Results

SELECT department_id, MAX(salary)FROM employeesGROUP BY department_idHAVING MAX(salary)>10000;

Using the HAVING Clause

Page 148: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Restricting Group Results

SELECT job_id, SUM(salary) PAYROLLFROM employeesWHERE job_id NOT LIKE '%REP%'GROUP BY job_idHAVING SUM(salary) > 13000ORDER BY SUM(salary);

Using the HAVING Clause

Page 149: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Reporting Aggregated Data Using the Group Functions

Restricting Group Results

SELECT MAX(AVG(salary))FROM employeesGROUP BY department_id;

Display the maximum average salary:

Page 150: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Use the HAVING clause

Use the HAVING clause

COUNT, MAX, MIN and AVGCOUNT, MAX, MIN and AVG

Part 4 Summary

Use the GROUP BY clause

Use the GROUP BY clause

Reporting Aggregated Data Using the Group Functions

Page 151: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Part 4 Stop-and-thinkReporting Aggregated Data Using the Group Functions

Do you have any questions ?

Page 152: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

For moreIf you want to go into these subjects more deeply, …

Courses

SQLP 10g

ADVANCED RECOVERY

Sites web

www.supinfo.com

www.labo-oracle.com

Basic Orders

Page 153: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

Congratulations

You have successfully completed the SUPINFO course n°2

ORACLEBasic Orders

Page 154: Campus-Booster ID: **XXXXX  Copyright © SUPINFO. All rights reserved Basic Orders

The endBasic Orders