campus-booster id: **xxxxx copyright © supinfo. all rights reserved basic orders
TRANSCRIPT
Campus-Booster ID: **XXXXX
www.supinfo.com
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
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
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
Retrieving Data Using the SQL SELECT Statement
Basic Orders
What is the SELECT statement ?
Arithmetic Expressions.
Other SELECT Possibilities.
Using iSQL*Plus.
Retrieving Data Using the SQL SELECT Statement
Preview
What is the SELECT statement ?Retrieving Data Using the SQL SELECT Statement
Projection Selection
Join
Table 1
Table 2
Table 1
Table 1
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;
Retrieving Data Using the SQL SELECT Statement
What is the SELECT statement ?Selecting all columns:
SELECT *FROM departments;
Retrieving Data Using the SQL SELECT Statement
What is the SELECT statement ?Selecting specific columns:
SELECT department_id, location_idFROM departments;
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 ?
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:
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.
Retrieving Data Using the SQL SELECT Statement
Arithmetic ExpressionsUsing Arithmetic Operators:
SELECT last_name, salary, salary + 300FROM employees;
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;
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;
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;
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:
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;
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;
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:
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;
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;
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;
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:
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
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
From your browser environment
Retrieving Data Using the SQL SELECT Statement
Logging In to iSQL*Plus:
Using iSQL*Plus
Retrieving Data Using the SQL SELECT Statement
iSQL*Plus Environment:
Using iSQL*Plus
12 3 4 5
6
7
8 9
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:
Retrieving Data Using the SQL SELECT Statement
Using iSQL*PlusInteracting with Script Files:
1
2
Retrieving Data Using the SQL SELECT Statement
Using iSQL*PlusInteracting with Script Files:
Retrieving Data Using the SQL SELECT Statement
Using iSQL*PlusInteracting with Script Files:
1
Retrieving Data Using the SQL SELECT Statement
Using iSQL*PlusInteracting with Script Files:
32
Retrieving Data Using the SQL SELECT Statement
Using iSQL*PlusiSQL*Plus History Page:
2
1
3
Retrieving Data Using the SQL SELECT Statement
Using iSQL*PlusiSQL*Plus History Page:
5
4
Retrieving Data Using the SQL SELECT Statement
Using iSQL*PlusSetting iSQL*Plus Preferences:
2
1
3
Retrieving Data Using the SQL SELECT Statement
Using iSQL*PlusSetting the Output Location Preference:
1
2
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
Part 1 Stop-and-thinkRetrieving Data Using the SQL SELECT Statement
Do you have any questions ?
Restricting and Sorting Data
Basic Orders
Preview
How to Restrict Data
Comparison Conditions
Logical Conditions
How to Sort Data
Substitution Variables
Restricting and Sorting Data
Restricting and Sorting Data
How to Restrict Data
“retrieve all employees in department 90”
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.
Restricting and Sorting Data
How to Restrict DataUsing the WHERE Clause:
SELECT employee_id, last_name, job_id, department_idFROM employeesWHERE department_id = 90 ;
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' ;
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
Restricting and Sorting Data
Comparison ConditionsUsing Comparison Conditions:
SELECT last_name, salaryFROM employeesWHERE salary <= 3000 ;
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
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) ;
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%' ;
You can combine pattern-matching characters:
Restricting and Sorting Data
Comparison ConditionsUsing the LIKE Condition:
SELECT first_nameFROM employeesWHERE first_name LIKE '_o%' ;
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 '\';
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 ;
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
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%';
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%';
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‘);
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.
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;
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 ;
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;
Restricting and Sorting Data
Substitution Variables
I want to query different values.
... salary = ? ...
... department_id = ? ...
... last_name = ? ...
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
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 ;
Restricting and Sorting Data
Substitution VariablesUsing the & Substitution Variable:
2
1
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:
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:
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:
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:
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
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
Part 2 Stop-and-thinkRestricting and Sorting Data
Do you have any questions ?
Using Single-Row Functions to Customize Output
Basic Orders
SQL Functions.
Character Functions.
Number Functions.
Date Functions.
Conversion Functions.
General Functions.
Conditional Expressions
Using Single-Row Functions to Customize Output
Preview
SQL FunctionsUsing Single-Row Functions to Customize Output
FUNCTION
Result Value
OutputInput
arg 1
arg 2
arg n
Functions performs
actions
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
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,...)]
SQL FunctionsUsing Single-Row Functions to Customize Output
Single-row functions:
Conversion Date
Character
General NumberSingle-rowfunctions
Character FunctionsUsing Single-Row Functions to Customize Output
Case-manipulation
functions
Character
functions
Character-manipulation
functions
LOWER
UPPER
INITCAP
CONCATSUBSTRLENGTHINSTRLPAD | RPADTRIMREPLACE
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:
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:
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')
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
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
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.
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
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.
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';
Date FunctionsUsing Single-Row Functions to Customize Output
Working with Dates
SYSDATE is a function that returns:
Date
Time
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.
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;
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
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'
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
Conversion FunctionsUsing Single-Row Functions to Customize Output
Implicit data type conversion
Explicit data type conversion
Data typeconversion
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:
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:
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
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')
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
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
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.
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:
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';
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'])
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
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
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');
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
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;
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
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
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
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
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
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
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;
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
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
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.
…
…
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])
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.
…
…
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;
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
Part 3 Stop-and-thinkUsing Single-Row Functions to Customize Output
Do you have any questions ?
Reporting Aggregated DataUsing the Group Functions
Basic Orders
Presentation
Creating groups
Restricting Group Results
Reporting Aggregated Data Using the Group Functions
Preview
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
Reporting Aggregated Data Using the Group Functions
Presentation
AVG
COUNT
MAX
MIN
STDDEV
SUM
VARIANCE
Types of Group Functions
Group
Functions
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
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.
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.
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:
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;
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:
Reporting Aggregated Data Using the Group Functions
Creating Groups of Data
EMPLOYEES
4400
9500
3500
6400
10033
Creating Groups
Average salaryin EMPLOYEEStable for eachdepartment
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];
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.
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.
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.
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
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
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
Reporting Aggregated Data Using the Group Functions
EMPLOYEES
Restricting Group Results
The maximum salaryper departmentwhien it isgreater than$10,000
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.
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
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
Reporting Aggregated Data Using the Group Functions
Restricting Group Results
SELECT MAX(AVG(salary))FROM employeesGROUP BY department_id;
Display the maximum average salary:
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
Part 4 Stop-and-thinkReporting Aggregated Data Using the Group Functions
Do you have any questions ?
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
Congratulations
You have successfully completed the SUPINFO course n°2
ORACLEBasic Orders
The endBasic Orders