ALLSLIDE SQL PLSQL-412

download ALLSLIDE SQL PLSQL-412

of 412

Transcript of ALLSLIDE SQL PLSQL-412

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    1/411

    Copyright 2004, Oracle. All rights reserved.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    2/411

    Copyright 2004, Oracle. All rights reserved.

    Oracle SQL & PL/SQL

    Huiyun Mao

    [email protected]

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    3/411

    Copyright 2004, Oracle. All rights reserved.

    SQL OverviewSQL Overview

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    4/411Copyright 2004, Oracle. All rights reserved.

    Data retrieval language (DRL)Data retrieval language (DRL)

    Data manipulation language (DML)Data manipulation language (DML)

    Data definition language (DDL)Data definition language (DDL)

    Transaction controlTransaction control

    Data control language (DCL)Data control language (DCL)

    SELECTSELECT

    INSERTINSERT

    UPDATEUPDATE

    DELETEDELETE

    CREATECREATE

    ALTERALTER

    DROPDROP

    RENAMERENAME

    TRUNCATETRUNCATE

    COMMITCOMMIT

    ROLLBACKROLLBACKSAVEPOINTSAVEPOINT

    GRANTGRANT

    REVOKEREVOKE

    SQL StatementsSQL Statements

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    5/411

    Copyright 2004, Oracle. All rights reserved.

    Tables Used in the CourseTables Used in the Course

    y Three main tables are used in this course:

    EMP table

    DEPT table

    y Three main tables are used in this course:

    EMP table

    DEPT table

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    6/411

    Copyright 2004, Oracle. All rights reserved.

    The EMP TableThe EMP TableEMPEMP

    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

    --------- ---------- --------- --------- --------- --------- --------- ---------

    7839 KING PRESIDENT 17-NOV-81 5000 10

    7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

    7782 CLARK MANAGER 7839 09-JUN-81 1500 10

    7566 JONES MANAGER 7839 02-APR-81 2975 20

    7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30

    7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

    7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30

    7900 JAMES CLERK 7698 03-DEC-81 950 30

    7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30

    7902 FORD ANALYST 7566 03-DEC-81 3000 20

    7369 SMITH CLERK 7902 17-DEC-80 800 20

    7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

    7876 ADAMS CLERK 7788 12-JAN-83 1100 207934 MILLER CLERK 7782 23-JAN-82 1300 10

    Foreign keyForeign keyPrimary keyPrimary key Foreign keyForeign key

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    7/411

    Copyright 2004, Oracle. All rights reserved.

    DEPT TablesDEPT Tables

    DEPTDEPT

    DEPTNO DNAME LOC

    --------- -------------- ----------

    10 ACCOUNTING NEW YORK

    20 RESEARCH DALLAS

    30 SALES CHICAGO

    40 OPERATIONS BOSTON

    Primary keyPrimary key

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    8/411

    Copyright 2004, Oracle. All rights reserved.

    Writing BasicSQL StatementsWriting BasicSQL Statements

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    9/411

    Copyright 2004, Oracle. All rights reserved.

    Capabilities of SQL SELECT

    Statements

    Capabilities of SQL SELECT

    Statements

    ProjectionProjectionRestrictionRestriction

    Table 1Table 1 Table 2Table 2

    Table 1Table 1 Table 1Table 1

    JoinJoin

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    10/411

    Copyright 2004, Oracle. All rights reserved.

    Basic SELECT StatementBasic SELECT Statement

    SELECT [DISTINCT] {*, column [alias],...}

    FROM table

    [WHERE condition(s)]

    [GROUP BY group_by_expression]

    [ORDER BY column];

    SELECT identifies the columns to be displayed.

    FROM identifies the table that contains the columns.

    SELECT identifies the columns to be displayed.

    FROM identifies the table that contains the columns.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    11/411

    Copyright 2004, Oracle. All rights reserved.

    Writing SQL StatementsWriting SQL Statements

    SQL statements are not case sensitive.

    SQL statements can be on one ormore lines.

    Keywords cannot be abbreviated or split across lines.

    Clauses are usually placed on

    separate lines.

    Tabs and indents are used to enhance readability.

    SQL statements are not case sensitive.

    SQL statements can be on one ormore lines.

    Keywords cannot be abbreviated or split across lines.

    Clauses are usually placed on

    separate lines.

    Tabs and indents are used to enhance readability.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    12/411

    Copyright 2004, Oracle. All rights reserved.

    Retrieving All Columns

    from a Table

    Retrieving All Columns

    from a Table

    DEPTNO DNAME LOC

    10 ACCOUNTING NEW YORK

    20 RESEARCH DALLAS

    30 SALES CHICAGO

    40 OPERATIONS BOSTON

    DEPTDEPT Retrieve allRetrieve allcolumns from thecolumns from the

    DEPT tableDEPT table

    DEPTDEPTDEPTNO DNAME LOC

    10 ACCOUNTING NEW YORK20 RESEARCH DALLAS

    30 SALES CHICAGO

    40 OPERATIONS BOSTON

    All columns are displayedAll columns are displayed

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    13/411

    Copyright 2004, Oracle. All rights reserved.

    Selecting All ColumnsSelecting All Columns

    DEPTNO DNAME LOC

    --------- -------------- -------------

    10 ACCOUNTING NEW YORK20 RESEARCH DALLAS

    30 SALES CHICAGO

    40 OPERATIONS BOSTON

    SQL> SELECT *

    2 FROM dept;

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    14/411

    Copyright 2004, Oracle. All rights reserved.

    Creating a Projection on a TableCreating a Projection on a Table

    Retrieve DEPTNORetrieve DEPTNOand LOC columnsand LOC columns

    from the DEPTfrom the DEPTtabletable

    DEPTDEPTDEPTNO LOC

    10 NEW YORK20 DALLAS

    30 CHICAGO

    40 BOSTON

    DEPTNO DNAME LOC

    10 ACCOUNTING NEW YORK20 RESEARCH DALLAS

    30 SALES CHICAGO

    40 OPERATIONS BOSTON

    DEPTDEPT

    OnlyOnly two columns are displayedtwo columns are displayed

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    15/411

    Copyright 2004, Oracle. All rights reserved.

    Selecting Specific ColumnsSelecting Specific Columns

    DEPTNO LOC

    --------- -------------

    10 NEW YORK20 DALLAS

    30 CHICAGO

    40 BOSTON

    SQL> SELECT deptno, loc

    2 FROM dept;

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    16/411

    Copyright 2004, Oracle. All rights reserved.

    Default Column JustificationDefault Column Justification

    EMPEMP

    CharacterCharacter

    left justifiedleft justified

    DateDate

    left justifiedleft justifiedNumberNumber

    right justifiedright justified

    ENAME HIREDATE SAL

    ---------- --------- ---------

    KING 17-NOV-81 5000

    BLAKE 01-MAY-81 2850CLARK 09-JUN-81 2450

    JONES 02-APR-81 2975

    MARTIN 28-SEP-81 1250

    ALLEN 20-FEB-81 1600...

    14 rows selected.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    17/411

    Copyright 2004, Oracle. All rights reserved.

    Arithmetic ExpressionsArithmetic Expressions

    y Create expressions on NUMBER and DATE data

    types by using arithmetic operators.

    y Create expressions on NUMBER and DATE data

    types by using arithmetic operators.

    Operator+

    -

    *

    /

    DescriptionAdd

    Subtract

    Multiply

    Divide

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    18/411

    Copyright 2004, Oracle. All rights reserved.

    Using Arithmetic OperatorsUsing Arithmetic Operators

    SQL> SELECT ename, sal, sal+300

    2 FROM emp;

    ENAME SAL SAL+300

    ---------- --------- ---------

    KING 5000 5300

    BLAKE 2850 3150CLARK 2450 2750

    JONES 2975 3275

    MARTIN 1250 1550

    ALLEN 1600 1900...

    14 rows selected.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    19/411

    Copyright 2004, Oracle. All rights reserved.

    Using Arithmetic Operators on

    Multiple Columns

    Using Arithmetic Operators on

    Multiple Columns

    SQL> SELECT grade, hisal-losal2 FROM salgrade;

    GRADE HISAL-LOSAL

    --------- -----------1 500

    2 199

    3 599

    4 999

    5 6998

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    20/411

    Copyright 2004, Oracle. All rights reserved.

    Operator PrecedenceOperator Precedence

    Multiplication and division take priority over addition

    and subtraction.

    Operators of the same priority are evaluated from left to

    right.

    Parentheses are used to force prioritized evaluation

    and to clarify statements.

    Multiplication and division take priority over addition

    and subtraction.

    Operators of the same priority are evaluated from left to

    right.

    Parentheses are used to force prioritized evaluation

    and to clarify statements.

    ** // ++__

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    21/411

    Copyright 2004, Oracle. All rights reserved.

    Operator PrecedenceOperator Precedence

    SQL> SELECT ename, sal, 12*sal+100

    2 FROM emp;

    ME SAL 12*SAL+100

    ------- --------- ----------

    G 5000 60100

    KE 2850 34300RK 2450 29500

    ES 2975 35800

    TIN 1250 15100

    EN 1600 19300

    14 rows selected.

    ENA

    ---

    KIN

    BLACLA

    JON

    MAR

    ALL...

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    22/411

    Copyright 2004, Oracle. All rights reserved.

    Using ParenthesesUsing Parentheses

    SQL> SELECT ename, sal, 12*(sal+100)

    2 FROM emp;

    ME SAL 12*(SAL+100)

    ------- --------- -----------

    G 5000 61200

    KE 2850 35400RK 2450 30600

    ES 2975 36900

    TIN 1250 16200

    14 rows selected.

    ENA

    ---

    KIN

    BLACLA

    JON

    MAR

    ...

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    23/411

    Copyright 2004, Oracle. All rights reserved.

    Defining a Column AliasDefining a Column Alias

    Renames a column heading

    Is useful with calculations Immediately follows column name; optional AS

    keyword between column name and alias

    Requires double quotation marks if it is case sensitive

    or contains spaces or special characters

    Renames a column heading

    Is useful with calculations Immediately follows column name; optional AS

    keyword between column name and alias

    Requires double quotation marks if it is case sensitive

    or contains spaces or special characters

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    24/411

    Copyright 2004, Oracle. All rights reserved.

    Using Column AliasesUsing Column Aliases

    SQL> SELECT ename AS name, sal salary

    2 FROM emp;

    NAME SALARY

    ------------- ---------KING 5000

    BLAKE 2850

    CLARK 2450

    JONES 2975

    ...

    14 rows selected.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    25/411

    Copyright 2004, Oracle. All rights reserved.

    Using Column AliasesUsing Column Aliases

    SQL> SELECT ename "Name",

    2 sal*12 "Annual Salary"

    3 FROM emp;

    Name Annual Salary------------- -------------

    KING 60000

    BLAKE 34200

    CLARK 29400

    ...

    14 rows selected.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    26/411

    Copyright 2004, Oracle. All rights reserved.

    Concatenation OperatorConcatenation Operator

    Concatenates columns or character strings to other

    columns Is represented by two vertical bars ||

    Creates a result column that is a character expression

    Concatenates columns or character strings to other

    columns

    Is represented by two vertical bars ||

    Creates a result column that is a character expression

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    27/411

    Copyright 2004, Oracle. All rights reserved.

    Using the Concatenation OperatorUsing the Concatenation Operator

    SQL> SELECT ename||job AS "Employees"

    2 FROM emp;

    Employees

    -------------------

    KINGPRESIDENT

    BLAKEMANAGER

    CLARKMANAGER

    JONESMANAGER

    MARTINSALESMANALLENSALESMAN

    ...

    14 rows selected.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    28/411

    Copyright 2004, Oracle. All rights reserved.

    LiteralsLiterals

    A literal is a constant value of character, expression, or

    number that can be included in the SELECT list.

    Date and character literal values must be enclosed in

    single quotation marks.

    Each character string is output once for each row

    returned.

    A literal is a constant value of character, expression, or

    number that can be included in the SELECT list.

    Date and character literal values must be enclosed in

    single quotation marks.

    Each character string is output once for each row

    returned.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    29/411

    Copyright 2004, Oracle. All rights reserved.

    Using Literal Character StringsUsing Literal Character Strings

    SQL> SELECT ename||' is a '||job AS

    2 "Employee Details"

    3 FROM emp;

    Employee Details

    -------------------------

    KING is a PRESIDENT

    BLAKE is a MANAGER

    CLARK is a MANAGER

    JONES is a MANAGER

    MARTIN is a SALESMAN...

    14 rows selected.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    30/411

    Copyright 2004, Oracle. All rights reserved.

    Duplicate RowsDuplicate Rows

    y The default display of queries is all rows, including

    duplicate rows.

    y The default display of queries is all rows, including

    duplicate rows.

    SQL> SELECT

    2 FROM emp;

    deptno

    DEPTNO

    ---------

    10

    3010

    20

    ..

    14 rows selected.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    31/411

    Copyright 2004, Oracle. All rights reserved.

    Eliminating Duplicate RowsEliminating Duplicate Rows

    y Eliminate duplicate rows by using the DISTINCT

    keyword in the SELECT clause.

    y Eliminate duplicate rows by using the DISTINCT

    keyword in the SELECT clause.

    SQL> SELECT DISTINCT deptno

    2 FROM emp;

    DEPTNO

    ---------

    10

    2030

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    32/411

    Copyright 2004, Oracle. All rights reserved.

    Restricting and Sorting DataRestricting and Sorting Data

    Limiting Rows by Using a RestrictionLimiting Rows by Using a Restriction

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    33/411

    Copyright 2004, Oracle. All rights reserved.

    Limiting Rows by Using a RestrictionLimiting Rows by Using a Restriction

    EMPNO ENAME JOB ... DEPTNO

    7839 KING PRESIDENT 10

    7698 BLAKE MANAGER 307782 CLARK MANAGER 107566 JONES MANAGER 20

    ...

    EMPNO ENAME JOB ... DEPTNO

    7839 KING PRESIDENT 107782 CLARK MANAGER 10

    7934 MILLER CLERK 10

    Retrieve allRetrieve allemployeesemployees

    in department 10in department 10

    EMPEMP

    EMPEMP

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    34/411

    Copyright 2004, Oracle. All rights reserved.

    Using the WHERE ClauseUsing the WHERE Clause

    SQL> SELECT ename, job, deptno

    2 FROM emp

    3 WHERE deptno=10;

    ENAME JOB DEPTNO

    ---------- --------- ---------KING PRESIDENT 10

    CLARK MANAGER 10

    MILLER CLERK 10

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    35/411

    Copyright 2004, Oracle. All rights reserved.

    Character Strings and DatesCharacter Strings and Dates

    Character strings and date values are enclosed in

    single quotation marks.

    Character values are case sensitive and date values

    are format sensitive.

    Default date format is DD-MON-YY.

    Character strings and date values are enclosed in

    single quotation marks.

    Character values are case sensitive and date values

    are format sensitive.

    Default date format is DD-MON-YY.

    SQL> SELECT ename, job, deptno, hiredate

    2 FROM emp3 WHERE ename = 'JAMES';

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    36/411

    Copyright 2004, Oracle. All rights reserved.

    Comparison OperatorsComparison Operators

    Operator

    =

    >

    >=

    SELECT ename, sal, comm2 FROM emp

    3 WHERE sal

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    38/411

    Copyright 2004, Oracle. All rights reserved.

    Using the Comparison Operators

    with Characters

    Using the Comparison Operators

    with Characters

    SQL> SELECT ename, mgr2 FROM emp

    3 WHERE ename='SMITH';

    ENAME MGR

    ---------- ---------

    SMITH 7902

    O h SQL C i OOth SQL C i O t

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    39/411

    Copyright 2004, Oracle. All rights reserved.

    Other SQL Comparison OperatorsOther SQL Comparison Operators

    Operator

    BETWEEN

    ...AND...

    IN(list)

    LIKE

    IS NULL

    Meaning

    Between two values (inclusive)

    Match any of a list of values

    Match a character pattern

    Is a null value

    U i h BETWEEN OU i th BETWEEN O t

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    40/411

    Copyright 2004, Oracle. All rights reserved.

    Using the BETWEEN OperatorUsing the BETWEEN Operator

    y Use the BETWEEN operator to display rows based on

    a range of values.

    y Use the BETWEEN operator to display rows based on

    a range of values.

    ENAME SAL

    ---------- ---------

    MARTIN 1250

    TURNER 1500WARD 1250

    ADAMS 1100

    MILLER 1300

    SQL> SELECT ename, sal

    2 FROM emp

    3 WHERE sal BETWEEN 1000 AND 1500;

    Lowerlimit

    Higherlimit

    U i th IN O tU i th IN O t

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    41/411

    Copyright 2004, Oracle. All rights reserved.

    Using the IN OperatorUsing the IN Operator

    y Use the IN operator to test for values in a list.y Use the IN operator to test for values in a list.

    SQL> SELECT empno, ename, sal, mgr

    2 FROM emp

    3 WHERE mgr IN (7902, 7566, 7788);

    EMPNO ENAME SAL MGR

    --------- ---------- --------- ---------

    7902 FORD 3000 75667369 SMITH 800 7902

    7788 SCOTT 3000 7566

    7876 ADAMS 1100 7788

    U i th IN O t ith St iUsing the IN Operator with Strings

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    42/411

    Copyright 2004, Oracle. All rights reserved.

    Using the IN Operator with StringsUsing the IN Operator with Strings

    y Use the IN operator to test for values in a list of

    strings.

    y Use the IN operator to test for values in a list of

    strings.

    SQL> SELECT ename, deptno, hiredate

    2 FROM emp

    3 WHERE ename IN ('BLAKE','MARTIN');

    ENAME DEPTNO HIREDATE

    ---------- --------- ---------

    BLAKE 30 01-MAY-81MARTIN 30 28-SEP-81

    U i th LIKE O tUsing the LIKE Operator

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    43/411

    Copyright 2004, Oracle. All rights reserved.

    Using the LIKE OperatorUsing the LIKE Operator

    Use the LIKE operator to perform wildcard searches of

    valid search string values.

    Search conditions can contain either literal characters

    or numbers.

    y % denotes zero or many characters

    y_ denotes one character

    Use the LIKE operator to perform wildcard searches of

    valid search string values.

    Search conditions can contain either literal characters

    or numbers.

    y % denotes zero or many characters

    y

    _ denotes one character

    SQL> SELECT ename

    2 FROM emp

    3 WHERE ename LIKE 'S%';

    Using the LIKE OperatorUsing the LIKE Operator

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    44/411

    Copyright 2004, Oracle. All rights reserved.

    Using the LIKE OperatorUsing the LIKE Operator

    SQL> SELECT ename

    2 FROM emp

    3 WHERE ename LIKE '_A%';

    ENAME

    ----------

    MARTIN

    JAMES

    WARD

    You can combine pattern matchingcharacters.

    Use the ESCAPE identifier to search for

    % or _.

    You can combine pattern matchingcharacters.

    Use the ESCAPE identifier to search for

    % or _.

    Using the IS NULL OperatorUsing the IS NULL Operator

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    45/411

    Copyright 2004, Oracle. All rights reserved.

    Using the IS NULL OperatorUsing the IS NULL Operator

    y Test for null values with the IS NULL operator.y Test for null values with the IS NULL operator.

    SQL> SELECT ename, mgr

    2 FROM emp

    3 WHERE mgr IS NULL;

    ENAME MGR

    ---------- ---------

    KING

    Logical OperatorsLogical Operators

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    46/411

    Copyright 2004, Oracle. All rights reserved.

    Logical OperatorsLogical Operators

    Operator

    AND

    OR

    NOT

    Meaning

    Returns TRUE if bothcomponent

    conditions are TRUE

    Returns TRUE if eithercomponent

    condition is TRUE

    Returns TRUE if the following

    condition is FALSE

    Using the AND OperatorUsing the AND Operator

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    47/411

    Copyright 2004, Oracle. All rights reserved.

    Using the AND OperatorUsing the AND Operator

    y AND requires both conditions to be TRUE.y AND requires both conditions to be TRUE.

    SQL> SELECT empno, ename, job, sal2 FROM emp

    3 WHERE sal>=1100

    4 AND job='CLERK';

    EMPNO ENAME JOB SAL

    ------ ---------- --------- ---------

    7876 ADAMS CLERK 1100

    7934 MILLER CLERK 1300

    ---

    Using the AND OperatorUsing the AND Operator

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    48/411

    Copyright 2004, Oracle. All rights reserved.

    Using the AND OperatorUsing the AND Operator

    y AND requires both conditions to be TRUE.y AND requires both conditions to be TRUE.

    SQL> SELECT ename, mgr, sal,deptno2 FROM emp

    3 WHERE sal>1000

    4 AND deptno = 10;

    ENAME MGR SAL DEPTNO

    ---------- --------- --------- ---------

    KING 5000 10

    CLARK 7839 2450 10

    MILLER 7782 1300 10

    Using the OR OperatorUsing the OR Operator

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    49/411

    Copyright 2004, Oracle. All rights reserved.

    Using the OR OperatorUsing the OR Operator

    OR requires either condition to be TRUE.OR requires either condition to be TRUE.OR requires either condition to be TRUE.

    SQL> SELECT empno, ename, job, sal

    2 FROM emp

    3 WHERE sal>=2000

    4 OR job='CLERK';

    EMPNO ENAME JOB SAL

    --------- ---------- --------- ---------

    7839 KING PRESIDENT 5000

    7698 BLAKE MANAGER 2850

    7782 CLARK MANAGER 2450

    7566 JONES MANAGER 29757900 JAMES CLERK 950

    7902 FORD ANALYST 3000

    ...

    10 rows selected.

    Using the OR OperatorUsing the OR Operator

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    50/411

    Copyright 2004, Oracle. All rights reserved.

    Using the OR OperatorUsing the OR Operator

    OR requires either condition to be TRUE.OR requires either condition to be TRUE.

    ENAME

    ----------

    KING

    BLAKE

    CLARK

    JONES

    MILLER

    SQL> SELECT ename, deptno, mgr

    2 FROM emp

    3

    4

    WHERE deptno = 10

    OR mgr = 7839;

    DEPTNO

    --------

    10

    30

    10

    20

    10

    MGR

    ---------

    7839

    7839

    7839

    7782

    Using the NOT OperatorUsing the NOT Operator

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    51/411

    Copyright 2004, Oracle. All rights reserved.

    Using the NOT OperatorUsing the NOT Operator

    SQL> SELECT ename, job

    2 FROM emp

    3 WHERE job NOT IN ('CLERK','MANAGER','ANALYST');

    ENAME JOB

    ---------- ---------KING PRESIDENT

    MARTIN SALESMAN

    ALLEN SALESMAN

    TURNER SALESMAN

    WARD SALESMAN

    Using the NOT OperatorUsing the NOT Operator

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    52/411

    Copyright 2004, Oracle. All rights reserved.

    Using the NOT OperatorUsing the NOT Operator

    > SELECT empno,ename,deptno,mgr

    2 FROM emp

    3 WHERE mgr NOT LIKE '78%';

    SQL

    EMPNO ENAME DEPTNO MGR

    --------- ---------- --------- ---------

    7654 MARTIN 30 76987499 ALLEN 30 7698

    ...

    ...

    7902 FORD 20 75667369 SMITH 20 7902

    ...

    10 rows selected.

    Using the NOT OperatorUsing the NOT Operator

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    53/411

    Copyright 2004, Oracle. All rights reserved.

    Using the NOT OperatorUsing the NOT Operator

    SQL> SELECT empno, sal, mgr

    2 FROM emp

    3 WHERE sal NOT BETWEEN 1000 AND 1500;

    EMPNO SAL MGR

    --------- --------- ---------

    7839 5000

    7698 2850 78397782 2450 7839

    7566 2975 7839

    7499 1600 7698

    7900 950 7698

    7902 3000 7566

    7369 800 7902

    7788 3000 7566

    9 rows selected.

    Using the NOT OperatorUsing the NOT Operator

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    54/411

    Copyright 2004, Oracle. All rights reserved.

    Using the NOT OperatorUsing the NOT Operator

    SQL> SELECT ename, sal AS "Salary Before Commission",

    2 comm

    3 FROM emp

    4 WHERE comm IS NOT NULL;

    ENAME Salary Before Commission COMM

    ---------- ------------------------ ---------

    MARTIN 1250 1400ALLEN 1600 300

    TURNER 1500 0

    WARD 1250 500

    Rules of PrecedenceRules of Precedence

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    55/411

    Copyright 2004, Oracle. All rights reserved.

    Rules of Precedence

    Order Evaluated Operator

    1 All comparisonoperators

    2 NOT

    3 AND4 OR

    y Use parentheses to override rules of precedence.y Use parentheses to override rules of precedence.

    Rules of PrecedenceRules of Precedence

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    56/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT ename, job, sal

    2 FROM emp

    3 WHERE job='SALESMAN'

    4 OR job='PRESIDENT'5 AND sal>1500;

    ENAME

    ----------

    KING

    MARTIN

    ALLENTURNER

    WARD

    SAL

    ---------

    5000

    1250

    16001500

    1250

    JOB

    -------

    PRESIDENT

    SALESMAN

    SALESMANSALESMAN

    SALESMAN

    Rules of PrecedenceRules of Precedence

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    57/411

    Copyright 2004, Oracle. All rights reserved.

    Use parentheses to force priority.Use parentheses to force priority.Use parentheses to force priority.

    SQL> SELECT ename, job, sal

    2 FROM emp3 WHERE (job='SALESMAN'

    4 OR job='PRESIDENT')

    5 AND sal>1500;

    ENAME

    ----------

    KING

    ALLEN

    JOB

    ---------

    PRESIDENT

    SALESMAN

    SAL

    ---------

    5000

    1600

    ORDER BY ClauseORDER BY Clause

    S t ith th ORDER BY lSort rows with the ORDER BY clause:

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    58/411

    Copyright 2004, Oracle. All rights reserved.

    Sort rows with the ORDER BY clause:y

    ASC: ascending order, defaulty DESC: descending order

    The ORDER BY clause comes last in the SELECTstatement.

    Sort rows with the ORDER BY clause:y

    ASC: ascending order, defaulty DESC: descending order

    The ORDER BY clause comes last in the SELECTstatement.

    SQL> SELECT ename, job, deptno

    2 FROM emp

    3 ORDER BY deptno;

    ENAME JOB DEPTNO

    ---------- --------- ---------

    KING PRESIDENT 10

    CLARK MANAGER 10

    ...

    JONES MANAGER 20

    SCOTT ANALYST 20

    ...

    14 rows selected.

    Sorting in Descending OrderSorting in Descending Order

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    59/411

    Copyright 2004, Oracle. All rights reserved.

    g gg g

    SQL> SELECT ename, job, deptno, sal

    2 FROM emp

    3 ORDER BY sal DESC;

    ENAME JOB DEPTNO SAL

    ---------- --------- --------- ---------

    KING PRESIDENT 10 5000FORD ANALYST 20 3000

    SCOTT ANALYST 20 3000

    JONES MANAGER 20 2975

    BLAKE MANAGER 30 2850CLARK MANAGER 10 2450

    ALLEN SALESMAN 30 1600

    ...

    14 rows selected.

    Sorting by Column AliasSorting by Column Alias

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    60/411

    Copyright 2004, Oracle. All rights reserved.

    g y

    SQL> SELECT empno, ename, sal*12 annsal

    2 FROM emp

    3 ORDER BY annsal;

    EMPNO ENAME ANNSAL

    --------- ---------- ---------

    7369 SMITH 96007900 JAMES 11400

    7876 ADAMS 13200

    7654 MARTIN 15000

    7521 WARD 15000

    7934 MILLER 15600

    7844 TURNER 18000

    ...

    14 rows selected.

    Sorting by Multiple ColumnsSorting by Multiple Columns

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    61/411

    Copyright 2004, Oracle. All rights reserved.

    g y p

    y The order of an ORDER BY list is the order of the

    sort.

    y The order of an ORDER BY list is the order of the

    sort.

    SQL> SELECT ename, deptno, sal

    2 FROM emp

    3 ORDER BY deptno, sal DESC;

    ENAME DEPTNO SAL

    ---------- --------- ---------

    KING 10 5000

    CLARK 10 2450MILLER 10 1300

    FORD 20 3000

    ...

    14 rows selected.

    Sorting by a Column Not in theSELECT ListSorting by a Column Not in theSELECT List

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    62/411

    Copyright 2004, Oracle. All rights reserved.

    SELECT ListSELECT List

    SQL> SELECT ename, deptno

    2 FROM emp

    3 ORDER BY sal;

    ENAME DEPTNO

    ---------- ---------

    SMITH 20

    JAMES 30ADAMS 20

    MARTIN 30

    WARD 30

    MILLER 10

    ...

    14 rows selected.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    63/411

    Copyright 2004, Oracle. All rights reserved.

    Single-Row Number and CharacterFunctionsSingle-Row Number and CharacterFunctions

    How a Function WorksHow a Function Works

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    64/411

    Copyright 2004, Oracle. All rights reserved.

    OutputOutputFunctionFunctionInputInput

    PerformsPerforms

    operationoperation

    Two Types of SQL FunctionsTwo Types of SQL Functions

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    65/411

    Copyright 2004, Oracle. All rights reserved.

    SingleSingle--rowrow

    functionsfunctionsMultipleMultiple--rowrow

    functionsfunctions

    FunctionsFunctions

    Single-Row FunctionsSingle-Row Functions

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    66/411

    Copyright 2004, Oracle. All rights reserved.

    Manipulate data items

    Accept arguments and return one value

    Act on each row returned

    Return one result per row

    Can modify the data type

    Can be nested

    Manipulate data items

    Accept arguments and return one value

    Act on each row returned

    Return one result per row

    Can modify the data type

    Can be nested

    Single-Row FunctionsSingle-Row Functions

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    67/411

    Copyright 2004, Oracle. All rights reserved.

    ConversionConversion

    NumberNumber

    DateDate

    SingleSingle--rowrow

    functionsfunctions

    CharacterCharacter

    Character FunctionsCharacter Functions

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    68/411

    Copyright 2004, Oracle. All rights reserved.

    Case conversionCase conversion

    functionsfunctionsCharacter manipulationCharacter manipulation

    functionsfunctions

    CharacterCharacter

    functionsfunctions

    LOWERLOWER

    UPPERUPPER

    INITCAPINITCAP

    Case Conversion FunctionsCase Conversion Functions

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    69/411

    Copyright 2004, Oracle. All rights reserved.

    y Convert the case for character strings

    Function Result

    y Convert the case for character strings

    sql course

    SQL COURSE

    Sql Course

    LOWER('SQL Course')

    UPPER('SQL Course')INITCAP('SQL Course')

    Using Case Conversion FunctionsUsing Case Conversion Functions

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    70/411

    Copyright 2004, Oracle. All rights reserved.

    y Display the employee number, name, and department

    number for employee Blake.

    y Display the employee number, name, and department

    number for employee Blake.

    SQL> SELECT empno, ename, deptno

    2 FROM emp

    3 WHERE ename = 'blake';

    no rows selectedno rows selected

    SQL> SELECT empno, ename, deptno

    2 FROM emp

    3 WHERE ename = UPPER('blake');

    EMPNO ENAME DEPTNO--------- ---------- ---------

    7698 BLAKE 30

    Using Case Conversion FunctionsUsing Case Conversion Functions

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    71/411

    Copyright 2004, Oracle. All rights reserved.

    y Display the employee name for all employees with an

    initial capital.

    y Display the employee name for all employees with an

    initial capital.

    SQL> SELECT INITCAP(ename) as EMPLOYEE

    2 FROM emp;

    EMPLOYEE----------

    King

    Blake

    ClarkJones

    Martin

    ...

    14 rows selected.

    Number FunctionsNumber Functions

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    72/411

    Copyright 2004, Oracle. All rights reserved.

    ROUND: Rounds value to specified decimal

    ROUND(45.926, 2)

    45.93

    TRUNC: Truncates value to specified decimal

    TRUNC(45.926, 2)

    45.92 MOD: Returns remainder of division

    MOD(1600, 300)

    100

    ROUND: Rounds value to specified decimal

    ROUND(45.926, 2)

    45.93

    TRUNC: Truncates value to specified decimal

    TRUNC(45.926, 2)

    45.92 MOD: Returns remainder of division

    MOD(1600, 300)

    100

    Defining a Null ValueDefining a Null Value

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    73/411

    Copyright 2004, Oracle. All rights reserved.

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

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

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

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

    SQL> SELECT ename, job, comm

    2 FROM emp;

    ENAME JOB COMM

    ---------- --------- ---------

    KING PRESIDENT

    BLAKE MANAGER...

    TURNER SALESMAN 0

    ...

    14 rows selected.

    Null Values in ArithmeticNull Values in ArithmeticExpressions

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    74/411

    Copyright 2004, Oracle. All rights reserved.

    ExpressionsExpressionsy Arithmetic expressions that contain a null value

    evaluate to null.

    y Arithmetic expressions that contain a null value

    evaluate to null.

    SQL> SELECT ename NAME, 12*sal+comm

    2 FROM emp;

    NAME 12*SAL+COMM---------- -----------

    KING

    BLAKE

    CLARK

    JONES

    MARTIN 16400

    ...

    14 rows selected.

    Using the NVL FunctionUsing the NVL Function

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    75/411

    Copyright 2004, Oracle. All rights reserved.

    y Use the NVL function to force a value where a null

    would otherwise appear: NVL can be used with date, character, and number

    data types.

    Data types must match. For example:

    y NVL(comm,0)

    y NVL(hiredate,'01-JAN-97')

    y NVL(job,'no job yet')

    y Use the NVL function to force a value where a null

    would otherwise appear: NVL can be used with date, character, and number

    data types.

    Data types must match. For example:

    y NVL(comm,0)

    y NVL(hiredate,'01-JAN-97')

    y NVL(job,'no job yet''no job yet')

    NVL (expr1, expr2)

    Using the NVL Function to HandleUsing the NVL Function to HandleNull Values

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    76/411

    Copyright 2004, Oracle. All rights reserved.

    Null ValuesNull Values

    SQL> SELECT ename, job, sal * 12 + NVL(comm,0)

    2 FROM emp;

    ENAME JOB SAL*12+NVL(COMM,0)

    ---------- --------- ------------------

    KING PRESIDENT 60000

    BLAKE MANAGER 34200CLARK MANAGER 29400

    JONES MANAGER 35700

    MARTIN SALESMAN 16400

    ALLEN SALESMAN 19500TURNER SALESMAN 18000

    ...

    14 rows selected.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    77/411

    Copyright 2004, Oracle. All rights reserved.

    Single-Row Date and ConversionFunctionsSingle-Row Date and ConversionFunctions

    Single-Row FunctionsSingle-Row Functions

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    78/411

    Copyright 2004, Oracle. All rights reserved.

    ConversionConversion DateDate

    SingleSingle--rowrow

    functionsfunctions

    CharacterCharacter NumberNumber

    Working with DatesWorking with Dates

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    79/411

    Copyright 2004, Oracle. All rights reserved.

    Oracle stores dates in an internal 7 byte numeric format:

    century, year, month, day, hours, minutes, seconds.

    The default date format is DD-MON-YY.

    Oracle stores dates in an internal 7 byte numeric format:

    century, year, month, day, hours, minutes, seconds.

    The default date format is DD-MON-YY.

    SYSDATESYSDATE

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    80/411

    Copyright 2004, Oracle. All rights reserved.

    Use SYSDATE to display the current date and time.

    DUAL is a one-column, one-row table that is used as a

    dummy table.

    Use SYSDATE to display the current date and time.

    DUAL is a one-column, one-row table that is used as a

    dummy table.

    SQL> SELECT SYSDATE2 FROM DUAL;

    SYSDATE

    ---------26-JAN-98

    Default Date FormatsDefault Date Formats

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    81/411

    Copyright 2004, Oracle. All rights reserved.

    Columns that are defined as DATE are

    displayed as DD-MON-YY by default.

    Columns that are defined as DATE are

    displayed as DD-MON-YY by default.

    SQL> SELECT ename, hiredate

    2 FROM emp

    3 WHERE ename='SMITH';

    ENAME HIREDATE

    ---------- ---------

    SMITH 17-DEC-80

    Arithmetic with DatesArithmetic with Dates

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    82/411

    Copyright 2004, Oracle. All rights reserved.

    Add or subtract a number to or from a date to obtain a datevalue

    Subtract two dates to find the numberof days between

    those dates

    Add or subtract a number to or from a date to obtain a datevalue

    Subtract two dates to find the numberof days between

    those dates

    Using Arithmetic Operatorswith DatesUsing Arithmetic Operatorswith Dates

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    83/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT ename, hiredate, hiredate+30 "NEW DATE"

    2 FROM emp

    3 WHERE ename='SMITH';

    ENAME HIREDATE NEW DATE

    ---------- --------- ---------SMITH 17-DEC-80 16-JAN-81

    Using SYSDATE in CalculationsUsing SYSDATE in Calculations

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    84/411

    Copyright 2004, Oracle. All rights reserved.

    y Determine for how many weeks employees have

    worked

    y Determine for how many weeks employees have

    worked

    SQL> SELECT ename, (SYSDATE-hiredate)/7

    2 "WEEKS AT WORK"

    3 FROM emp

    4 WHERE deptno=10;

    ENAME WEEKS AT WORK

    ---------- -------------

    KING 844.94617CLARK 867.94617

    MILLER 835.37474

    Explicit Data Type ConversionExplicit Data Type Conversion

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    85/411

    Copyright 2004, Oracle. All rights reserved.

    NUMBERNUMBER CHARACTERCHARACTER

    TO_CHARTO_CHAR TO_CHARTO_CHAR

    TO_NUMBERTO_NUMBER

    DATEDATE

    TO_DATETO_DATE

    Modifying the Display Format ofDatesModifying the Display Format ofDates

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    86/411

    Copyright 2004, Oracle. All rights reserved.

    2727--JANJAN--9898

    Tuesday the 27th of January, 1998Tuesday the 27th of January, 1998

    January 27, 1998January 27, 1998

    01/27/9801/27/98

    TO_CHAR Function with DatesTO_CHAR Function with Dates

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    87/411

    Copyright 2004, Oracle. All rights reserved.

    y The format model:

    Is case sensitive and must be enclosed in single

    quotation marks

    Can include any valid date format element

    Has an fmelement to remove padded blanks orsuppress leading zeros

    Is separated from the date value by a comma

    y The format model:

    Is case sensitive and must be enclosed in singlequotation marks

    Can include any valid date format element

    Has an fmelement to remove padded blanks orsuppress leading zeros

    Is separated from the date value by a comma

    TO_CHAR(date, 'fmfmt')

    Date Format Model ElementsDate Format Model Elements

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    88/411

    Copyright 2004, Oracle. All rights reserved.

    YYYY

    YEAR

    MM

    MONTH

    DY

    DAY

    Full year in numbers

    Year spelled out

    2-digit value for month

    3-letter abbreviation of the day

    of the weekFull name of the day

    Full name of the month

    Using the TO_CHAR Function withDatesUsing the TO_CHAR Function withDates

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    89/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT ename, TO_CHAR(hiredate, 'Month DDth, YYYY')

    2 AS HIREDATE

    3 FROM emp

    4 WHERE job='MANAGER';

    ENAME HIREDATE---------- --------------------

    BLAKE May 01st, 1981

    CLARK June 09th, 1981

    JONES April 02nd, 1981

    Using the TO_CHAR Function withDatesUsing the TO_CHAR Function withDates

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    90/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT empno, TO_CHAR(hiredate, 'MM/YY') AS MONTH

    2 FROM emp

    3 WHERE ename='BLAKE';

    EMPNO MONTH

    --------- -----7698 05/81

    Using the TO_CHAR Function withDatesUsing the TO_CHAR Function withDates

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    91/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT ename,

    2 TO_CHAR(hiredate, 'fmDD Month YYYY') AS HIREDATE

    3 FROM emp;

    ENAME HIREDATE---------- -----------------

    KING 17 November 1981BLAKE 1 May 1981CLARK 9 June 1981JONES 2 April 1981MARTIN 28 September 1981ALLEN 20 February 1981...14 rows selected.

    Using the TO_CHAR Function withDatesUsing the TO_CHAR Function withDates

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    92/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT ename, mgr, sal,TO_CHAR(hiredate,'YYYY-MON-DD')

    2 AS HIREDATE

    3 FROM emp4 WHERE sal

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    93/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT empno,ename,deptno,TO_CHAR(hiredate,'MM-DD-YYYY')

    2 AS HIREDATE

    3 FROM emp4 WHERE hiredate NOT LIKE '%81';

    EMPNO ENAME DEPTNO HIREDATE

    -------- ---------- --------- -----------

    7369 SMITH 20 12-17-1980

    7788 SCOTT 20 12-09-1982

    7876 ADAMS 20 01-12-19837934 MILLER 10 01-23-1982

    Using the TO_CHAR Function withDatesUsing the TO_CHAR Function withDates

    SQL> SELECT j b d t

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    94/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT ename, job, deptno,

    2 TO_CHAR(hiredate,'DD-MON-YYYY') AS HIRE_DATE

    3 FROM emp

    4 ORDER BY hiredate DESC;

    ENAME JOB DEPTNO HIRE_DATE

    ---------- --------- --------- -----------

    ADAMS CLERK 20 12-JAN-1983

    SCOTT ANALYST 20 09-DEC-1982MILLER CLERK 10 23-JAN-1982

    JAMES CLERK 30 03-DEC-1981

    FORD ANALYST 20 03-DEC-1981

    KING PRESIDENT 10 17-NOV-1981MARTIN SALESMAN 30 28-SEP-1981

    ...

    14 rows selected.

    Date Format Model ElementsDate Format Model Elements

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    95/411

    Copyright 2004, Oracle. All rights reserved.

    Time elements format the time portion of the date. Time elements format the time portion of the date.

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

    DD "of" MONTH 12 of OCTOBER

    ddspth fourteenth

    Using Format Models to Display TimeUsing Format Models to Display Time

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    96/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT TO_CHAR(SYSDATE,'HH24:MI:SS') TIME

    2 FROM DUAL;

    TIME

    --------

    13:55:46

    TO_CHAR Function with NumbersTO_CHAR Function with Numbers

    y Use these formats with the TO CHAR function toy Use these formats with the TO CHAR function to

    TO CHAR(n,'fmt')

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    97/411

    Copyright 2004, Oracle. All rights reserved.

    y Use these formats with the TO_CHAR function to

    display a number value as a character:

    Use these formats with the TO_CHAR function todisplay a number value as a character:

    TO_CHAR( , )

    9

    0

    $

    L

    .

    ,

    Represents a number

    Forces a zero to be displayed

    Places a floating dollar sign

    Uses the floating local currency symbol

    Prints a decimal point

    Places a thousand indicator

    Using the TO_CHAR Function withNumbersUsing the TO_CHAR Function withNumbers

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    98/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT TO_CHAR(sal,'$99,999') SALARY2 FROM emp

    3 WHERE ename = 'SCOTT';

    SALARY--------$3,000

    Dollar signDollar signThousand indicatorThousand indicator

    Using the TO_NUMBER andTO_DATE FunctionsUsing the TO_NUMBER andTO_DATE Functions

    Convert a character string to a number data type using the Convert a character string to a number data type using the

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    99/411

    Copyright 2004, Oracle. All rights reserved.

    Convert a character string to a number data type using the

    TO_NUMBER function

    Convert a character string to a number data type using theTO_NUMBER function

    TO_NUMBER(char)

    Convert a character string to a date datatype using the TO_DATE function

    Convert a character string to a date datatype using the TO_DATE function

    TO_DATE(char[, 'fmt'])

    Using the TO_NUMBER FunctionUsing the TO_NUMBER Function

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    100/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT TO_NUMBER('1000')+sal AS NEW_SALARY2 FROM emp

    3 WHERE ename = 'SCOTT';

    NEW_SALARY----------

    4000

    Date FunctionsDate Functions

    FUNCTION DESCRIPTION

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    101/411

    Copyright 2004, Oracle. All rights reserved.

    Number of monthsbetween two dates

    MONTHS_BETWEEN

    ADD_MONTHS

    NEXT_DAY

    LAST_DAY

    ROUND

    TRUNC

    Adds calendar months todate

    Next day following the datespecified

    Last day of the month

    Round off date

    Truncate date

    Using Date FunctionsUsing Date Functions

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    102/411

    Copyright 2004, Oracle. All rights reserved.

    y Use the ADD_MONTHS function to add months to

    a date.

    y Use the ADD_MONTHS function to add months to

    a date.

    SQL> SELECT ename, hiredate, ADD_MONTHS(hiredate, 6)2 AS "+6 MONTHS"

    3 FROM emp

    4 WHERE ename='BLAKE';

    ENAME HIREDATE +6 MONTHS

    ---------- --------- ---------

    BLAKE 01-MAY-81 01-NOV-81

    Nesting FunctionsNesting Functions

    Single-row functions can be nested to any level. Single-row functions can be nested to any level.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    103/411

    Copyright 2004, Oracle. All rights reserved.

    Nested functions are evaluated from the innermost level to

    the outermost level.

    Nested functions are evaluated from the innermost level to

    the outermost level.

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

    Step 1 = Result 1

    Step 2 = Result 2

    Step 3 = Result 3

    Nesting FunctionsNesting Functions

    Result 2

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    104/411

    Copyright 2004, Oracle. All rights reserved.

    Result 1Result 2

    SQL> SELECT ename,

    2 NVL(TO_CHAR(mgr),'No Manager')

    3 FROM emp4 WHERE mgr IS NULL;

    ME NVL(TO_CHAR(MGR),'NOMANAGER')------- -----------------------------

    KING No Manager

    ENA---

    Nesting FunctionsNesting Functions

    SQL> SELECT MONTHS_BETWEEN2 (TO DATE('02-02-1995','MM-DD-YYYY'),

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    105/411

    Copyright 2004, Oracle. All rights reserved.

    2 (TO_DATE( 02 02 1995 , MM DD YYYY ),

    3 TO_DATE('01-01-1995','MM-DD-YYYY'))

    4 "Months"

    5 FROM DUAL;

    Months----------

    1.03225806

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    106/411

    Copyright 2004, Oracle. All rights reserved.

    Displaying Datafrom Multiple TablesDisplaying Datafrom Multiple Tables

    Obtaining Data from Multiple TablesObtaining Data from Multiple Tables

    EMPEMPEMPNO ENAME ... DEPTNO DEPTNO DNAME LOC

    DEPTDEPT

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    107/411

    Copyright 2004, Oracle. All rights reserved.

    EMPNO ENAME ... DEPTNO

    ------ ----- ... ------

    7839 KING ... 10

    7698 BLAKE ... 30

    ...7934 MILLER ... 10

    DEPTNO DNAME LOC

    ------ ---------- --------

    10 ACCOUNTING NEW YORK

    20 RESEARCH DALLAS

    30 SALES CHICAGO

    40 OPERATIONS BOSTON

    EMPNO-----783976987782756676547499

    DEPTNO-------

    103010203030

    LOC--------NEW YORKCHICAGO

    NEW YORKDALLASCHICAGOCHICAGO

    Joining TablesJoining Tables

    y Use a join to query data from more than one table:y Use a join to query data from more than one table:

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    108/411

    Copyright 2004, Oracle. All rights reserved.

    Write the join condition in the WHERE clause.

    Prefix the column name with the table name when the

    same column name appears in more than one table.

    Write the join condition in the WHERE clause.

    Prefix the column name with the table name when the

    same column name appears in more than one table.

    SELECT table1.column1, table2.column2FROM table1, table2

    WHERE table1.column1 = table2.column2;

    Types of JoinsTypes of Joins

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    109/411

    Copyright 2004, Oracle. All rights reserved.

    EquijoinEquijoin NonequijoinNonequijoin Self joinSelf join

    What Is an Equijoin?What Is an Equijoin?

    EMPNO ENAME DEPTNOEMPEMP

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    110/411

    Copyright 2004, Oracle. All rights reserved.

    ------ ------- -------

    ...

    7782 CLARK 10DEPTNO DNAME LOC------- ---------- --------

    ...

    10 ACCOUNTING NEW YORK

    ...

    DEPTDEPT

    Links rows that satisfy a specified conditionLinks rows that satisfy a specified condition

    WHEREWHERE empemp..deptnodeptno=dept.=dept.deptnodeptno

    EquijoinEquijoin

    EMPNO ENAME DEPTNO DEPTNO DNAME LOCEMPEMP DEPTDEPT

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    111/411

    Copyright 2004, Oracle. All rights reserved.

    ------ ------- -------

    7839 KING 10

    7698 BLAKE 30

    7782 CLARK 10

    7566 JONES 20

    7654 MARTIN 307499 ALLEN 30

    7844 TURNER 307900 JAMES 30

    7521 WARD 30

    7902 FORD 20

    7369 SMITH 20

    ...14 rows selected.

    ------- ---------- --------

    10 ACCOUNTING NEW YORK

    30 SALES CHICAGO

    10 ACCOUNTING NEW YORK

    20 RESEARCH DALLAS

    30 SALES CHICAGO

    30 SALES CHICAGO

    30 SALES CHICAGO30 SALES CHICAGO

    30 SALES CHICAGO

    20 RESEARCH DALLAS

    20 RESEARCH DALLAS

    ...14 rows selected.

    Primary keyPrimary keyForeign keyForeign key

    Retrieving Recordswith an EquijoinRetrieving Recordswith an Equijoin

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    112/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT emp.empno, emp.ename, emp.deptno,

    2 dept.deptno, dept.loc

    3 FROM emp, dept

    4 WHERE emp.deptno=dept.deptno;

    EMP

    ---78

    76

    77

    75...

    NO ENAME DEPTNO DEPTNO LOC

    -- ------ ------ ------ ---------39 KING 10 10 NEW YORK

    98 BLAKE 30 30 CHICAGO

    82 CLARK 10 10 NEW YORK

    66 JONES 20 20 DALLAS

    14 rows selected.

    Qualifying AmbiguousColumn NamesQualifying AmbiguousColumn Names

    Use table prefixes to qualify column names that are inmultiple tables

    Use table prefixes to qualify column names that are inmultiple tables

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    113/411

    Copyright 2004, Oracle. All rights reserved.

    multiple tables.

    Use table prefixes to improve performance.

    multiple tables.

    Use table prefixes to improve performance.

    Additional Search ConditionsUsing the AND OperatorAdditional Search ConditionsUsing the AND Operator

    EMPEMP DEPTDEPT

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    114/411

    Copyright 2004, Oracle. All rights reserved.

    EMPEMP DEPTDEPT

    EMPNO ENAME DEPTNO

    ------ ------- -------

    7839 KING 107698 BLAKE 30

    7782 CLARK 10

    7566 JONES 20

    7654 MARTIN 30

    7499 ALLEN 30

    7844 TURNER 307900 JAMES 30

    ...

    14 rows selected.

    DEPTNO D

    ------

    10 A30

    10 A

    20 R

    30 SA

    30 SA

    30 SA30 SA

    ...

    14 rows se

    NAME LOC

    --------- --------

    CCOUNTING NEW YORKSALES CHICAGO

    CCOUNTING NEW YORK

    ESEARCH DALLAS

    LES CHICAGO

    LES CHICAGO

    LES CHICAGOLES CHICAGO

    lected.

    WHEREWHERE empemp..deptnodeptno=dept.=dept.deptnodeptno ANDAND enameename=='KINGKING'

    Using Additional Search Conditionswith a JoinUsing Additional Search Conditionswith a Join

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    115/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT emp.empno, emp.ename, emp.deptno, dept.loc

    2 FROM emp, dept;

    3 WHERE emp.deptno = dept.deptno4 AND emp.ename = 'KING';

    EMPNO ENAME DEPTNO LOC

    --------- ---------- --------- -------------

    7839 KING 10 NEW YORK

    Using Additional Search Conditionswith a JoinUsing Additional Search Conditionswith a Join

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    116/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT emp.ename, emp.job, dept.deptno, dept.dname2 FROM emp, dept

    3 WHERE emp.deptno=dept.deptno

    4 AND emp.job IN ('MANAGER','PRESIDENT');

    ENAME JOB DEPTNO DNAME

    ---------- --------- --------- --------------KING PRESIDENT 10 ACCOUNTING

    BLAKE MANAGER 30 SALES

    CLARK MANAGER 10 ACCOUNTING

    JONES MANAGER 20 RESEARCH

    Table AliasesTable Aliases

    Si lif i b i t bl liy Simplify queries by using table aliases

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    117/411

    Copyright 2004, Oracle. All rights reserved.

    y Simplify queries by using table aliases.

    y

    can be written as ...

    y Simplify queries by using table aliases.

    y

    can be written as ...

    SQL> SELECT emp.empno, emp.ename, emp.deptno,

    2 dept.deptno, dept.loc

    3 FROM emp, dept

    4 WHERE emp.deptno=dept.deptno;

    SQL> SELECT e.empno, e.ename, e.deptno,

    2 d.deptno, d.loc

    3 FROM emp e, dept d

    4 WHERE e.deptno=d.deptno;

    Using Table AliasesUsing Table Aliases

    SQL> SELECT e.empno, e.ename, e.deptno,

    2 d.deptno, d.loc

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    118/411

    Copyright 2004, Oracle. All rights reserved.

    p ,

    3 FROM emp e, dept d

    4 WHERE e.deptno=d.deptno;

    EMPNO ENAME DEPTNO DEPTNO LOC

    --------- ---------- --------- --------- -----------

    7839 KING 10 10 NEW YORK

    7698 BLAKE 30 30 CHICAGO7782 CLARK 10 10 NEW YORK

    7566 JONES 20 20 DALLAS

    7654 MARTIN 30 30 CHICAGO

    7499 ALLEN 30 30 CHICAGO

    ...

    14 rows selected.

    NonequijoinsNonequijoins

    EMPNO ENAME SAL GRADE LOSAL HISALEMPEMP SALGRADESALGRADE

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    119/411

    Copyright 2004, Oracle. All rights reserved.

    Salary in the EMPSalary in the EMP

    table is betweentable is between

    low salary and highlow salary and highsalary in the SALGRADEsalary in the SALGRADE

    table.table.

    ------ ------- ------

    7839 KING 5000

    7698 BLAKE 28507782 CLARK 2450

    7566 JONES 2975

    7654 MARTIN 1250

    7499 ALLEN 1600

    7844 TURNER 15007900 JAMES 950

    ...

    14 rows selected.

    ----- ----- ------

    1 700 1200

    2 1201 14003 1401 2000

    4 2001 3000

    5 3001 9999

    Retrieving Recordswith NonequijoinsRetrieving Recordswith Nonequijoins

    SQL> SELECT s l s d

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    120/411

    Copyright 2004, Oracle. All rights reserved.

    ME SAL GRADE------- --------- ---------

    ES 950 1

    TH 800 1

    MS 1100 1

    14 rows selected.

    SQL> SELECT e.ename, e.sal, s.grade

    2 FROM emp e, salgrade s

    3 WHERE e.sal4 BETWEEN s.losal AND s.hisal;

    ENA---

    JAM

    SMI

    ADA...

    Joining More Than Two TablesJoining More Than Two Tables

    DEPTNO DNAMEME SAL DEPTNO

    ------- --------- ---------

    EMPEMP DEPTDEPTENA

    ---

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    121/411

    Copyright 2004, Oracle. All rights reserved.

    SALGRADESALGRADE

    WHEREWHERE

    empemp

    .

    .salsal

    BETWEENBETWEEN

    salgradesalgrade..losallosal ANDANDsalgradesalgrade..hisalhisal

    ANDAND empemp..deptnodeptno = dept.= dept.deptnodeptno

    --------- ----------

    10 ACCOUNTING

    20 RESEARCH

    30 SALES40 OPERATIONS

    LOSAL HISAL GRADE

    --------- --------- ---------

    700 1200 1

    1201 1400 21401 2000 32001 3000 4

    3001 9999 5

    ------- --------- ---------

    ES 950 30

    TH 800 20

    MS 1100 20TIN 1250 30

    D 1250 30

    LER 1300 10

    14 rows selected.

    ---

    JAM

    SMI

    ADAMAR

    WAR

    MIL

    Using Multiple JoinsUsing Multiple Joins

    SQL> SELECT e.ename, e.deptno, d.dname, e.sal, s.grade

    2 FROM emp e, dept d, salgrade s

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    122/411

    Copyright 2004, Oracle. All rights reserved.

    e p e, dept d, sa g ade s

    3 WHERE e.deptno=d.deptno

    4 AND e.sal BETWEEN s.losal and s.hisal;

    ENAME DEPTNO DNAME SAL GRADE

    ---------- --------- -------------- --------- ---------

    JAMES 30 SALES 950 1

    SMITH 20 RESEARCH 800 1ADAMS 20 RESEARCH 1100 1

    MARTIN 30 SALES 1250 2

    WARD 30 SALES 1250 2

    MILLER 10 ACCOUNTING 1300 2

    ALLEN 30 SALES 1600 3

    ...

    14 rows selected.

    SelfjoinsSelfjoins

    NO ENAME MGR EMPNO ENAME

    EMP (WORKER)EMP (WORKER) EMP (MANAGER)EMP (MANAGER)EMP

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    123/411

    Copyright 2004, Oracle. All rights reserved.

    MGR in the WORKER table is equal to EMPNO in theMGR in the WORKER table is equal to EMPNO in theMANAGER table.MANAGER table.

    -- ------ ----

    39 KING

    98 BLAKE 783982 CLARK 7839

    66 JONES 7839

    54 MARTIN 7698

    7499 ALLEN 7698

    ----- --------

    7839 KING7839 KING

    7839 KING

    7698 BLAKE

    7698 BLAKE

    ---

    78

    7677

    75

    76

    Joining a Table to Itself

    SQL> SELECT worker.ename||' works for '||manager.ename

    2 AS WHO WORKS FOR WHOM

    Joining a Table to Itself

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    124/411

    Copyright 2004, Oracle. All rights reserved.

    _ _ _

    3 FROM emp worker, emp manager

    4 WHERE worker.mgr = manager.empno;

    WHO_WORKS_FOR_WHOM

    -------------------------------

    BLAKE works for KING

    CLARK works for KING

    JONES works for KING

    MARTIN works for BLAKE

    ...

    13 rows selected.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    125/411

    Copyright 2004, Oracle. All rights reserved.

    Aggregating Databy Using Group FunctionsAggregating Databy Using Group Functions

    What Are Group Functions?What Are Group Functions?y Group functions operate on sets of rows to give one result

    per group.

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

    per group.

    EMPEMP

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    126/411

    Copyright 2004, Oracle. All rights reserved.

    maximummaximumsalary insalary in

    the EMP tablethe EMP table

    DEPTNO SAL--------- ---------

    10 245010 500010 130020 80020 1100

    20 300020 300020 297530 160030 285030 125030 95030 150030 1250

    MAX(SAL)---------

    5000

    Types of Group FunctionsTypes of Group Functions

    AVG AVG

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    127/411

    Copyright 2004, Oracle. All rights reserved.

    COUNT

    MAX MIN

    SUM

    COUNT

    MAX MIN

    SUM

    Guidelines for Using GroupFunctionsGuidelines for Using GroupFunctions

    Many aggregate functions accept theseMany aggregate functions accept these

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    128/411

    Copyright 2004, Oracle. All rights reserved.

    options:

    DISTINCT ALL

    NVL

    options:

    DISTINCT ALL

    NVL

    Using the AVG and SUM FunctionsUsing the AVG and SUM Functions

    y You can use AVG and SUM for numeric data.y You can use AVG and SUM for numeric data.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    129/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT AVG(sal), SUM(sal)

    2 FROM emp

    3 WHERE job LIKE 'SALES%';

    AVG(SAL) SUM(SAL)

    -------- ---------1400 5600

    Using the MIN and MAX FunctionsUsing the MIN and MAX Functions

    y You can use MIN and MAX for any data type.y You can use MIN and MAX for any data type.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    130/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT TO_CHAR(MIN(hiredate),'DD-MON-YYYY'),

    2 TO_CHAR(MAX(hiredate),'DD-MON-YYYY')

    3 FROM emp;

    T0_CHAR(MIN TO_CHAR(MAX

    --------- ---------

    17-DEC-1980 12-JAN-1983

    Using the MIN and MAX FunctionsUsing the MIN and MAX Functions

    y You can use MIN and MAX for any data type.y You can use MIN and MAX for any data type.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    131/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT MIN(sal) AS "Lowest Salary",

    2 MAX(sal) AS "Highest Salary"

    3 FROM emp;

    Lowest Salary Highest Salary

    ------------- --------------

    800 5000

    Using the COUNT FunctionUsing the COUNT Function

    y COUNT(*) returns the number of rows in a query.y COUNT(*) returns the number of rows in a query.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    132/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT COUNT(*)

    2 FROM emp

    3 WHERE deptno = 30;

    COUNT(*)

    ---------

    6

    Using the COUNT FunctionUsing the COUNT Function

    y COUNT(expr) returns the number of nonnull rows.y COUNT(expr) returns the number of nonnull rows.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    133/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT COUNT(comm)

    2 FROM emp

    3 WHERE deptno = 30;

    COUNT(COMM)

    -----------

    4

    Group Functions and Null ValuesGroup Functions and Null Values

    y Group functions ignore null values in the column.y Group functions ignore null values in the column.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    134/411

    Copyright 2004, Oracle. All rights reserved.

    > SELECT AVG(comm)

    2 FROM emp;

    SQL

    AVG(COMM)

    ---------

    550

    Using the NVL Functionwith Group FunctionsUsing the NVL Functionwith Group Functionsy The NVL function forces group functions to include

    null values.y The NVL function forces group functions to include

    null values.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    135/411

    Copyright 2004, Oracle. All rights reserved.

    > SELECT AVG(NVL(comm,0))

    2 FROM emp;

    SQL

    AVG(NVL(COMM,0))

    ----------------

    157.14286

    Using the NVL Functionwith Group FunctionsUsing the NVL Functionwith Group Functionsy Average commission forallpeople hired in 1981y Average commission forallpeople hired in 1981

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    136/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT AVG(NVL(comm,0))

    2 FROM emp

    3 WHERE hiredate

    4 BETWEEN TO_DATE('01-JAN-1981','DD-MON-YYYY')

    5 AND TO_DATE('31-DEC-1981','DD-MON-YYYY');

    AVG(NVL(COMM,0))

    ----------------

    220

    Creating Groups of DataCreating Groups of Data

    DEPTNO SAL

    EMPEMP

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    137/411

    Copyright 2004, Oracle. All rights reserved.

    averageaverage

    salarysalary

    in EMPin EMP

    tabletablefor eachfor each

    departmentdepartment

    2916.6667

    2175

    1566.6667

    --------- ---------10 2450

    10 500010 130020 80020 110020 3000

    20 300020 297530 160030 285030 125030 95030 150030 1250

    DEPTNO AVG(SAL)

    ------- ---------

    10 2916.666720 2175

    30 1566.6667

    Creating Groups of Data:GROUP BY ClauseCreating Groups of Data:GROUP BY Clausey Use the GROUP BY clause to divide rows in a table

    into smaller groups.y Use the GROUP BY clause to divide rows in a table

    into smaller groups.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    138/411

    Copyright 2004, Oracle. All rights reserved.

    SELECT column, group_function

    M table

    ERE condition]

    [GROUP BY group_by_expression]

    [ORDER BY column];

    FRO

    [WH

    Using the GROUP BY ClauseUsing the GROUP BY Clause

    y All columns in the SELECT list that are not in groupfunctions must be in the GROUP BY clause.

    y All columns in the SELECT list that are not in groupfunctions must be in the GROUP BY clause.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    139/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT deptno, AVG(sal)

    2 FROM emp

    3 GROUP BY deptno;

    DEPTNO AVG(SAL)

    --------- ---------10 2916.6667

    20 2175

    30 1566.6667

    Using the GROUP BY ClauseUsing the GROUP BY Clause

    y The GROUP BY column does not have to be in theSELECT list.

    y The GROUP BY column does not have to be in theSELECT list.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    140/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT AVG(sal)

    2 FROM emp

    3 GROUP BY deptno;

    AVG(SAL)

    ---------

    2916.6667

    21751566.6667

    Using the GROUP BY ClauseUsing the GROUP BY Clause

    y Display the number of people in each department.y Display the number of people in each department.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    141/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT deptno, COUNT(*) AS "Dept Employees"

    2 FROM emp

    3 GROUP BY deptno;

    DEPTNO Dept Employees

    --------- --------------

    10 3

    20 530 6

    Using a Group Function in theORDER BY ClauseUsing a Group Function in theORDER BY Clause

    SQL> SELECT deptno, AVG(sal)

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    142/411

    Copyright 2004, Oracle. All rights reserved.

    2 FROM emp

    3 GROUP BY deptno4 ORDER BY AVG(sal);

    DEPTNO AVG(SAL)

    ---------- ------------30 1566.6667

    20 2175

    10 2916.6667

    Illegal QueriesUsing Group FunctionsIllegal QueriesUsing Group Functions

    y Any column or expression in the SELECT list that is

    not an aggregate function must be in the GROUP BY

    y Any column or expression in the SELECT list that is

    not an aggregate function must be in the GROUP BY

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    143/411

    Copyright 2004, Oracle. All rights reserved.

    not an aggregate function must be in the GROUP BY

    clause. aus

    enot an aggregate function must be in the GROUP BY

    clause.

    SQL> SELECT deptno, COUNT(ename)

    2 FROM emp;

    SQL> SELECT deptno, COUNT(ename)

    2 FROM emp; eGR

    OUP

    eGR

    OUP

    eGR

    OUPB

    Ycl

    SELECT deptno, COUNT(ename)

    *

    ERROR at line 1:

    ORA-00937: not a single-group group function

    SELECT deptno, COUNT(ename)

    *

    ERROR at line 1:ORA-00937: not a single-group group function

    Colum

    nmissin

    u

    gint

    h

    Colm

    nmis

    singint

    h

    BYclau

    se

    Colum

    nmissing

    inth

    BY

    clause

    Using Set Operators

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    144/411

    Copyright 2004, Oracle. All rights reserved.

    Using Set OperatorsUsing Set Operators

    The Set OperatorsThe Set Operators

    IntersectIntersect

    AA BB

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    145/411

    Copyright 2004, Oracle. All rights reserved.

    UnionUnion / Union All/ Union All

    MinusMinus

    AA BB AA BB

    AA BB

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    146/411

    UNIONUNION

    AA BB

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    147/411

    Copyright 2004, Oracle. All rights reserved.

    Using the UNION OperatorUsing the UNION Operator

    y

    Display the name, employee number, and job title ofall employees. Display each employee only once.

    y Display the name, employee number, and job title of

    all employees. Display each employee only once.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    148/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT ename, empno, job

    2 FROM emp

    3 UNION

    4 SELECT name, empid, title

    5 FROM emp_history;

    ENAME EMPNO JOB

    ---------- --------- ---------

    ADAMS 7876 CLERK

    ALLEN 7499 SALESMANBALFORD 6235 CLERK

    ...

    20 rows selected.

    Using the UNION OperatorUsing the UNION Operator

    y

    Display the name, job title, and salary of allemployees.

    y Display the name, job title, and salary of all

    employees.

    SQL> SELECT ename, job, sal

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    149/411

    Copyright 2004, Oracle. All rights reserved.

    ENAME JOB SAL---------- --------- ---------

    ADAMS CLERK 1100

    ALLEN SALESMAN 0

    ALLEN SALESMAN 1600BALFORD CLERK 0

    ...

    23 rows selected.

    2 FROM emp

    3 UNION

    4 SELECT name, title, 0

    5 FROM emp_history;

    UNION ALLUNION ALL

    AA BB

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    150/411

    Copyright 2004, Oracle. All rights reserved.

    Using the UNION ALL OperatorUsing the UNION ALL Operator

    y

    Display the names, employee numbers, and jobtitles of all employees.

    y Display the names, employee numbers, and job

    titles of all employees.

    SQL> SELECT ename, empno, job

    2 FROM

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    151/411

    Copyright 2004, Oracle. All rights reserved.

    2 FROM emp

    3 UNION ALL4 SELECT name, empid, title

    5 FROM emp_history;

    ENAME EMPNO JOB---------- --------- ---------

    KING 7839 PRESIDENT

    BLAKE 7698 MANAGER

    CLARK 7782 MANAGERCLARK 7782 MANAGER

    ...

    23 rows selected.

    INTERSECTINTERSECT

    AA BB

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    152/411

    Copyright 2004, Oracle. All rights reserved.

    Using the INTERSECT OperatorUsing the INTERSECT Operator

    y Display the distinct names, employee numbers, andjob titles of employees found in both the EMP and

    EMP_HISTORY tables.

    yDisplay the distinct names, employee numbers, andjob titles of employees found in both the EMP and

    EMP_HISTORY tables.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    153/411

    Copyright 2004, Oracle. All rights reserved.

    SQL> SELECT ename, empno, job

    2 FROM emp

    3 INTERSECT

    4 SELECT name, empid, title

    5 FROM emp_history;

    ENAME EMPNO JOB

    ---------- --------- ---------

    ALLEN 7499 SALESMAN

    CLARK 7782 MANAGER

    SCOTT 7788 ANALYST

    ENAME EMPNO JOB

    ---------- --------- ---------

    ALLEN 7499 SALESMANCLARK 7782 MANAGER

    SCOTT 7788 ANALYST

    MINUSMINUS

    AA BB

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    154/411

    Copyright 2004, Oracle. All rights reserved.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    155/411

    SET Operator RulesSET Operator Rules

    The expressions in the SELECT lists must match in

    number and datatype.

    Duplicate rows are automatically eliminated except in

    UNION ALL.

    The expressions in the SELECT lists must match in

    number and datatype.

    Duplicate rows are automatically eliminated except in

    UNION ALL.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    156/411

    Copyright 2004, Oracle. All rights reserved.

    Column names from the first query appear in the result. The output is sorted in ascending order by default

    except in UNION ALL.

    Parentheses can be used to alter the sequence of

    execution.

    Column names from the first query appear in the result. The output is sorted in ascending order by default

    except in UNION ALL.

    Parentheses can be used to alter the sequence of

    execution.

    Matching the SELECTStatementMatching the SELECTStatement

    Display the department numbers,Display the department numbers,Display the department numbers,

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    157/411

    Copyright 2004, Oracle. All rights reserved.

    Display the department numbers,locations, and hiredates for all employees.

    Display the department numbers,sp ay t e depa t e t u be s,

    locations, andlocations, and hiredateshiredates for all employees.for all employees.

    SQL> SELECT deptno, null location, hiredate

    2 FROM emp

    3 UNION

    4 SELECT deptno, loc, TO_DATE(null)

    5 FROM dept;

    Controlling the Order of RowsControlling the Order of Rows

    Produce an English sentence using two

    UNION operators.

    Produce an English sentence using twoProduce an English sentence using two

    UNION operators.UNION operators.

    SQL> COLUMN a_dummy NOPRINT

    SQL> SELECT 'sing' "My dream", 3 a_dummy

    2 FROM d al

    SQL> COLUMN a_dummy NOPRINT

    SQL> SELECT 'sing' "My dream", 3 a_dummy

    2 FROM dual

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    158/411

    Copyright 2004, Oracle. All rights reserved.

    My dream

    -------------------------I'd like to teachthe world tosing

    My dream

    -------------------------I'd like to teachthe world tosing

    2 FROM dual

    3 UNION

    4 SELECT 'I''d like to teach', 1

    5 FROM dual

    6 UNION

    7 SELECT 'the world to', 28 FROM dual

    9 ORDER BY 2;

    2 FROM dual

    3 UNION4 SELECT 'I''d like to teach', 1

    5 FROM dual

    6 UNION

    7 SELECT 'the world to', 28 FROM dual

    9 ORDER BY 2;

    Writing SubqueriesWriting Subqueries

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    159/411

    Copyright 2004, Oracle. All rights reserved.

    Writing Subqueriesg q

    Using a Subqueryto Solve a ProblemUsing a Subqueryto Solve a Problem

    yWho has a salary greater than Joness?yWho has a salary greater than Joness?

    Main Query

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    160/411

    Copyright 2004, Oracle. All rights reserved.

    Which employees have a salary greaterthan Joness salary?

    Main Query

    What is Joness salary?

    Subquery

    ??

    ??

    SubqueriesSubqueries

    SELECT select_list

    FROM table

    WHERE expr operator

    (SELECT select_list

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    161/411

    Copyright 2004, Oracle. All rights reserved.

    FROM table);

    The subquery (inner query) executes once before the main

    query. The result of the subquery is used by the main query (outer

    query).

    The subquery (inner query) executes once before the main

    query. The result of the subquery is used by the main query (outer

    query).

    Using a SubqueryUsing a Subquery

    Who has a salary greater than JonesWho has a salary greater than Jones??

    SQL> SELECT ename

    2 FROM emp 2975

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    162/411

    Copyright 2004, Oracle. All rights reserved.

    3 WHERE sal >4 (SELECT sal

    5 FROM emp

    6 WHERE ename='JONES');

    ENAME

    ----------

    KING

    FORDSCOTT

    Guidelines for Using SubqueriesGuidelines for Using Subqueries

    Enclose subqueries in parentheses.

    Place subqueries on the right side of the comparison

    operator.

    Enclose subqueries in parentheses.

    Place subqueries on the right side of the comparison

    operator.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    163/411

    Copyright 2004, Oracle. All rights reserved.

    operator.

    Do not add an ORDER BY clause to a subquery.

    Use single-row operators with single-row subqueries.

    p

    Do not add an ORDER BY clause to a subquery.

    Use single-row operators with single-row subqueries.

    Types of SubqueriesTypes of Subqueries

    Single-row subquery Single-row subquery

    Main query

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    164/411

    Copyright 2004, Oracle. All rights reserved.

    Multiple-row subquery Multiple-row subquerySubquery returnsreturns CLERKCLERK

    CLERKCLERK

    MANAGERMANAGER

    Main query

    Subqueryreturnsreturns

    Single-Row SubqueriesSingle-Row Subqueries

    Return only one row Use single-row comparison operators

    Return only one row

    Use single-row comparison operators

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    165/411

    Copyright 2004, Oracle. All rights reserved.

    Operator

    =

    >

    >=

    SELECT ename, mgr

    2 FROM emp 7839

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    167/411

    Copyright 2004, Oracle. All rights reserved.

    3 WHERE mgr =4 (SELECT mgr

    5 FROM emp

    6 WHERE ename='BLAKE');

    ENAME MGR

    ---------- ---------

    BLAKE 7839

    CLARK 7839JONES 7839

    Executing Single-Row SubqueriesExecuting Single-Row Subqueries

    Who has the same job as employee 7369Who has the same job as employee 7369 andand

    earns a higher salary than employee 7876?earns a higher salary than employee 7876?

    CLERK

    SQL> SELECT ename, job

    2 FROM emp

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    168/411

    Copyright 2004, Oracle. All rights reserved.

    1100

    3 WHERE job =4 (SELECT job

    5 FROM emp

    6 WHERE empno = 7369)

    7 AND sal >

    8 (SELECT sal9 FROM emp

    10 WHERE empno = 7876);

    ENAME JOB---------- ---------

    MILLER CLERK

    Using Group Functionsin a SubqueryUsing Group Functionsin a Subquery

    Display all employees who earn the minimum salary.Display all employees who earn the minimum salary.

    800SQL> SELECT ename, job, sal

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    169/411

    Copyright 2004, Oracle. All rights reserved.

    2 FROM emp3 WHERE sal =

    4 (SELECT MIN(sal)

    5 FROM emp);

    ENAME JOB SAL

    ---------- --------- ---------

    SMITH CLERK 800

    What Is Wrongwith This Statement?What Is Wrongwith This Statement?

    SQL> SELECT empno, ename

    2 FROM emp

    3 WHERE sal =row

    row

    subq

    subque

    ry

    uery

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    170/411

    Copyright 2004, Oracle. All rights reserved.

    4 (SELECT MIN(sal)5 FROM emp

    6 GROUP BY deptno);

    ithmultiple

    ithmultiple--

    ERROR:

    ORA-01427: single-row subquery returns more than

    one row

    no rows selected

    ra

    Single

    Single-

    -row

    ope

    torw

    row

    ope

    ratorw

    Will This Statement Work?Will This Statement Work?

    SQL> SELECT ename, job

    2 FROM emp

    3 WHERE job =

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    171/411

    Copyright 2004, Oracle. All rights reserved.

    4 (SELECT job

    5 FROM emp

    6 WHERE ename='SMYTHE');no

    values

    novalues

    no rows selectedreturn

    return

    Subqu

    ery

    Subqu

    ery

    ss

    Multiple-Row SubqueriesMultiple-Row Subqueries

    Return more than one row

    Use the IN multiple-row comparison operator to

    compare an expression to any member in the list that a

    b t

    Return more than one row

    Use the IN multiple-row comparison operator to

    compare an expression to any member in the list that a

    b t

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    172/411

    Copyright 2004, Oracle. All rights reserved.

    subquery returnssubquery returns

    Using Group Functionsin a Multiple-Row SubqueryUsing Group Functionsin a Multiple-Row Subquery

    Display all employees who earn the same salary asDisplay all employees who earn the same salary asthe minimum salary for each department.the minimum salary for each department.

    SQL> SELECT ename, sal, deptno

    2 FROM 800 950 1300

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    173/411

    Copyright 2004, Oracle. All rights reserved.

    2 FROM emp3 WHERE sal

    4 (SELECT MIN(sal)

    5 FROM emp

    6 GROUP BY deptno);

    800, 950, 1300IN

    ENAME SAL DEPTNO

    ---------- --------- ---------

    SMITH 800 20

    JAMES 950 30

    MILLER 1300 10

    Using Group Functionsin a Multiple-Row SubqueryUsing Group Functionsin a Multiple-Row Subquery

    SQL> SELECT ename, sal, deptno,

    2 TO CHAR(hi d t 'DD MON YYYY')HIREDATE

    Display the employees who were hired on the sameDisplay the employees who were hired on the samedate as the longest serving employee in anydate as the longest serving employee in anydepartment.department.

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    174/411

    Copyright 2004, Oracle. All rights reserved.

    2 TO_CHAR(hiredate,'DD-MON-YYYY')HIREDATE3 FROM emp

    4 WHERE hiredate

    5 (SELECT MIN(hiredate)

    6 FROM emp

    7 GROUP BY deptno);

    IN

    ENAME SAL DEPTNO HIREDATE

    ---------- --------- --------- -----------

    SMITH 800 20 17-DEC-1980ALLEN 1600 30 20-FEB-1981

    CLARK 2450 10 09-JUN-1981

    Controlling TransactionsControlling Transactions

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    175/411

    Copyright 2004, Oracle. All rights reserved.

    Data Manipulation LanguageData Manipulation Language

    A DML statement is executed when you:

    y Add new rows to a table (INSERT)

    y Modify existing rows in a table (UPDATE)

    y Remove existing rows from a table (DELETE)

    A DML statement is executed when you:

    y Add new rows to a table (INSERT)

    y Modify existing rows in a table (UPDATE)

    y Remove existing rows from a table (DELETE)

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    176/411

    Copyright 2004, Oracle. All rights reserved.

    y Remove existing rows from a table (DELETE)

    A transaction consists of a collection of DML statements

    that form a logical unit of work.

    y Remove existing rows from a table (DELETE)

    A transaction consists of a collection of DML statements

    that form a logical unit of work.

    Database TransactionsDatabase Transactions

    yDatabase transactions can consist of: DML statements that make up one consistent change to the

    data

    Example: UPDATE

    yDatabase transactions can consist of: DML statements that make up one consistent change to the

    data

    Example: UPDATE

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    177/411

    Copyright 2004, Oracle. All rights reserved.

    Example: UPDATE One DDL statement

    Example: CREATE

    One DCL statement

    Example: GRANT and REVOKE

    One DDL statement

    Example: CREATE

    One DCL statement

    Example: GRANT and REVOKE

    Database TransactionsDatabase Transactions

    Begin when the first executable SQL statement is

    executed

    End with one of the following events:

    y COMMIT or ROLLBACK

    Begin when the first executable SQL statement is

    executed

    End with one of the following events:

    y COMMIT or ROLLBACK

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    178/411

    Copyright 2004, Oracle. All rights reserved.

    y COMMIT or ROLLBACK

    y DDL or DCL statement executes (automatic commit)

    y User exits

    y

    System crashes

    COMMIT or ROLLBACK

    y DDL or DCL statement executes (automatic commit)

    y User exits

    y System crashes

    Advantages of COMMITand ROLLBACKAdvantages of COMMITand ROLLBACK

    COMMIT and ROLLBACK ensure data consistency.

    Users can preview data changes before making

    COMMIT and ROLLBACK ensure data consistency.

    Users can preview data changes before making

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    179/411

    Copyright 2004, Oracle. All rights reserved.

    Users can preview data changes before makingchanges permanent.

    Users can group logically related operations.

    Users can preview data changes before makingchanges permanent.

    Users can group logically related operations.

    Controlling TransactionsControlling Transactions

    DELETEDELETE

    DELETEDELETEINSERTINSERTUPDATEUPDATE

    INSERTINSERTUPDATEUPDATEINSERTINSERT

    INSERTINSERT

    y Transactiony Transaction

  • 7/30/2019 ALLSLIDE SQL PLSQL-412

    180/411

    Copyright 2004, Oracle. All rights reserved.

    SavepointSavepoint AA

    ROLLBACK toROLLBACK to SavepointSavepoint BB

    SavepointSavepoint BBCOMMITCOMMIT

    ROLLBACK toROLLBACK to SavepointSavepoint AA

    ROLLBACKROLLBACK

    Implicit Transaction ProcessingImplicit Transaction Processing

    An automatic commit occurs under the following

    circumstances:y A DDL statement is issued, such as CREATE

    y A DCL statement is issued, such as GRANT

    y A normal exit from SQL*Plus occurs without an explicitly

    issued COMMIT or ROLLBACK statementAn automatic rollback occurs under an abnormal

    An automatic commit occurs under the following

    circumstances:y A DDL statement is issued, such as CREATE

    y A DCL statement is issued, such as GRANT

    y A normal exit from SQL*Plus occurs without an explicitlyissued COMMIT or ROLLBACK statement

    An automatic rollback occurs under an abnormal

  • 7/30/2019