SQL Ref Manual

download SQL Ref Manual

of 55

Transcript of SQL Ref Manual

  • 8/14/2019 SQL Ref Manual

    1/55

    AN INTRODUCTION TO ORACLE AND SQL

    1. INTRODUCTION

    ORACLE is a Relational Database Management System (RDBMS). As such, the only data

    structure that it supports is the TABLE. A Table is simply a two-dimensional matrix with

    horizontal ROWS and vertical COLUMNS. Readers may be interested to note that a RDBMS is

    an implementation of Codds Relational Data Model and that in the literature on relational

    topics certain items are often slightly different. In particular, our Tables are called RELATIONS,

    our rows are called TUPLES and our columns are called ATTRIBUTES.

    ORACLE has one language to handle both definition and manipulation of the data.

    Furthermore, this same language also deals with Security aspects.

    This language is called SQL ( Often referred to as SeQueL or Structured Query Language).

    Although the trend is to provide the user of ORACLE applications with higher level user-

    interfaces (e.g. Forms based application screens) where no knowledge of SQL is necessary, it is

    essential that anyone involved in the development of ORACLE applications has a thorough

    grounding in SQL.

    People registered as ORACLE users will obviously wish to create and manipulate their own

    Tables. However, the approach taken by this introductory text will be to concentrate initially

    on the retrieval aspects of SQL. In particular, we will consider retrieval operations on some

    sample tables to which all users have been granted read-only access. The sample tables are

    EMP, DEPT, SALGRADE are described in Appendix 1.

    Readers wishing to define and manipulate their own tables are advised to read Chapters 7 and

    8.

    This introductory text should be used as a manual and therefore you should not attempt towork through it in sequence. An initial read through is recommended so that you get an idea

    of the range of features available, after that use the manual for reference purposes only.

    1

  • 8/14/2019 SQL Ref Manual

    2/55

    2. GETTING STARTED WITH SQLPLUS

    2.1 SQLPLUS

    ORACLE RDBMS has a number of component software parts. The component that we shall

    use to familiarise ourselves with SQL is called SQLPLUS.

    SQLPLUS consists of the usual SQL data manipulation, definition and access statements, plus

    a number of extra statements for formatting, report-writing and file-handling.

    SQLPLUS statements are held in an SQL buffer. The current line operated on by the keyboard

    is known as the Command Line, but an SQL statement may spread over several lines.

    2.2 Using SQLPLUS Graphical User Interface

    To start the graphical user interface:

    Choose Start> Programs > Oracle for Windows NT > SQL Plus 8.0The Log On dialog box appears:

    2

  • 8/14/2019 SQL Ref Manual

    3/55

    1. Enter your user name and password (given to you in class). In the Host string part enter

    eden01.

    2. Click OK.

    The Oracle SQLPLUS application window is displayed.

    3

  • 8/14/2019 SQL Ref Manual

    4/55

    2.2.1 Using the SQLPLUS Application Window

    SQLPLUS displays the SQL command prompt in the application window. To enter SQLPLUS

    commands, type each command at the SQL prompt and press Enter.

    You can use the mouse buttons to copy previously entered SQL commands to the current SQL

    prompt.

    To copy a command, highlight the intended command with the left mouse button. While still

    holding down the left mouse button, click the right mouse button. SQLPLUS copies the text to

    the SQL prompt.

    2.2.2 Using the SQLPLUS Menus

    This section describes the menus in the GUI version of SQLPLUS.

    File Menu

    The File Menu contains the following commands:

    Open The Open command retrieves a previously stored command file.

    By default, SQLPLUS looks for a command file with the .SQL extension.

    Save The Save command contains three subcommands:

    Save Create, Save Replace and Save Append.

    Save Create saves the contents of the SQLPLUS buffer in a command file.

    Save Replace replaces the contents of an existing file with the contents of the

    SQLPLUS buffer. If the file does not exist, SQLPLUS creates the file.

    Save Append adds the contents of the SQLPLUS buffer to the end of the file

    you specify.

    After you save a command file, you can do the following:

    Retrieve the file with the Open command from the File menu.

    Edit the file with the Editor command from the Edit menu.

    4

  • 8/14/2019 SQL Ref Manual

    5/55

  • 8/14/2019 SQL Ref Manual

    6/55

  • 8/14/2019 SQL Ref Manual

    7/55

  • 8/14/2019 SQL Ref Manual

    8/55

    WHERE JOB MANAGER;

    e.g. SELECT * selects ALL rows from the EMP table where the

    FROM EMP job is MANAGER or CLERK.

    WHERE JOB = MANAGER

    OR JOB = CLERK;

    e.g. SELECT * selects ALL rows from the EMP table where the

    FROM EMP job is not MANAGER or CLERK.

    WHERE NOT (JOB = MANAGER

    OR JOB = CLERK);

    Note that the WHERE clause causes a Horizontal 'slicing' of a Table.

    3.3 Boolean Operator definition and Precedence

    Operator Meaning

    = equal to

    (or !=) not equal to

    > greater than

    >= greater than or equal to

    < less than

  • 8/14/2019 SQL Ref Manual

    9/55

    a) AND - OR precedence

    WHERE SAL> 1500 AND JOB = MANAGER OR SAL > 1200 AND JOB = SALESMAN

    ^ ^ ^ ^

    condition 1 condition 2 condition 3 condition 4

    The expression will be carried out as follows:-

    1. Each of the 4 conditions are evaluated to be true or false

    2. Condition 1 and Condition 2 are ANDed to produce TRUE if both are true and FALSE

    otherwise

    3. Condition 3 and Condition 4 are ANDed to produce TRUE if both are true and FALSEotherwise

    4. The results for 2. and 3. are ORed together to produce a final result of TRUE if either is true

    and FALSE otherwise.

    b) BETWEEN

    SELECT * This is equivalent to WHERE SAL >= 1200

    FROM EMP AND SAL 1400

    WHERE SAL NOT BETWEEN 1200 AND 1400;

    c) IN

    SELECT *

    FROM EMP

    WHERE JOB IN (CLERK, ANALYST, SALESMAN);

    Selects rows where the JOB is CLERK, ANALYST or SALESMAN

    SELECT *

    FROM EMP

    WHERE JOB NOT IN (CLERK, ANALYST, SALESMAN);

    9

  • 8/14/2019 SQL Ref Manual

    10/55

    Selects rows where the JOB is not CLERK, ANALYST or SALESMAN

    d) LIKE

    LIKE is used to match character patterns, and in order to do this, recognises two special

    characters in a character value:

    % represents any sequence of zero or more characters

    _ represents any single character

    SELECT *

    FROM EMP

    WHERE ENAME LIKE M%;

    Selects rows where the ENAME column begins with M.

    SELECT *

    FROM EMP

    WHERE ENAME LIKE ALL_N;

    Selects rows where the ENAME column consists of ALL (any character) N

    e.g. ENAME has the value ALLAN, ALLEN, ALLZN

    The characters % and _ can be used in any combination in a character pattern.

    e) IS NULL

    Sometimes, values for a column are not known, or are inappropriate. In a case like this, the

    existence of a NULL value can be entered. Note that NULL is not the same as zero.

    SELECT *FROM EMP

    WHERE COMM IS NULL;

    Selects rows where the commission field has no entered value, except for the value NULL.

    3.4 Ordering Rows

    When rows are selected from a table or tables, the order of their display is undefined. In fact,

    the order may be different for the same query at a different time. If a particular order is

    10

  • 8/14/2019 SQL Ref Manual

    11/55

    required, then an ORDER phrase must be added to the query. The ORDER appears after any

    WHERE phrase.

    e.g. SELECT *

    FROM EMPORDER BY EMPNO;

    Orders all the rows of the EMP in ascending order of EMPNO. Ascending order is the default.

    e.g. SELECT *

    FROM EMP

    WHERE DEPTNO = 30

    ORDER BY SAL DESC;

    Selects all rows where the DEPTNO is 30 and orders the output in descending order of SAL.

    e.g. SELECT *

    FROM EMP

    ORDER BY JOB, SAL DESC;

    Orders the EMP table firstly in alphabetic order of JOB and then for each JOB by descending

    order of SAL.

    Note that if there are NULL values in an ORDER BY column, then they will appear first,

    regardless of whether the required order is ascending or descending.

    3.5 Selecting Columns

    As well as making horizontal operations on a table through selection of rows, it is possible to

    make vertical operations on a table by selecting some subset of the Columns or even by

    embellishing the table with extra columns produced by Functions acting on existing columns.

    e.g. SELECT EMPNO, ENAME, SAL

    FROM EMP;

    Selects only the EMPNO, ENAME and SAL columns;

    e.g. SELECT EMPNO, ENAME, SAL

    FROM EMP

    WHERE DEPTNO = 30;

    11

  • 8/14/2019 SQL Ref Manual

    12/55

    Selects only the EMPNO, ENAME and SAL columns from those rows where the DEPTNO is

    30.

    3.5.1 Eliminating Column Duplicates

    Sometimes when certain columns are selected, Duplicate values appear:

    SELECT JOBFROM EMP;

    If it is required that duplicates are not to be repeated, then the DISTINCT option will eliminate

    them.

    e.g. SELECT DISTINCT JOB

    FROM EMP;

    3.5.2 Creating Column Aliases

    When queries are displayed, ORACLE normally uses the column names that have been defined

    in the table. However, it is possible to rename the column if desired.

    e.g. SELECT EMPNO, ENAME EMPLOYEE_NAME,

    SAL SALARYFROM EMP;

    12

  • 8/14/2019 SQL Ref Manual

    13/55

    This leaves EMPNO with the same name but renames ENAME as EMPLOYEE_NAME and

    SAL as SALARY.

    Note that column names can be specified in any order - even an order different to the definedorder in the table. Displayed results will be in the order defined in the QUERY.

    4. JOINING TABLES

    4.1 Introduction

    In the Relational approach to data, rows in different tables are related by having identical

    values in certain columns of the tables. For example, rows in the EMP table with DEPTNO =

    30 are related to the row in the DEPTNO table with DEPTNO = 30. The technique of relating

    different tables is called JOINING.

    e.g. SELECT *

    FROM EMP, DEPT

    WHERE EMP.DEPTNO = DEPT.DEPTNO;

    The WHERE clause is responsible for the JOIN. The result is a table with all the columns of

    both original tables.

    Note that in order to avoid confusion between the DEPTNO column of the EMP table and the

    DEPTNO column of the DEPT table we qualify the appropriate DEPTNO by putting the name

    of the owning table and a full-stop (.) at the front. e.g., EMP.DEPTNO.

    e.g. SELECT *

    FROM EMP, DEPT

    WHERE SAL > 1000

    AND EMP.DEPTNO = DEPT.DEPTNO;

    This joins the EMP and DEPT tables as before, but also selects only the rows where the SAL

    value is greater than 1000. Note that the order of the two WHERE conditions is irrelevant.

    e.g. SELECT ENAME, DNAME

    FROM EMP, DEPT

    WHERE SAL > 1000

    AND EMP.DEPTNO = DEPT.DEPTNO;

    13

  • 8/14/2019 SQL Ref Manual

    14/55

    This is the same as the previous query except that only the ENAME and DNAME columns are

    chosen.e.g. SELECT ENAME, DNAME

    FROM EMP, DEPT

    WHERE SAL > 1000AND EMP.DEPTNO = DEPT.DEPTNO

    ORDER BY ENAME;

    This query is the same as the previous one except that the rows are displayed in ascending

    order of ENAME.

    4.2 Types of Join

    All the examples of the previous section are of the join type known as the EQUI-JOIN. This isbecause the connecting of the tables is based on values in the tables being EQUAL. However,

    other types of join exist which connect tables on the basis of values in the tables having

    relationships other than equality.

    e.g. SELECT X.ENAME, X.SAL, X.JOB, Y.ENAME, Y.SAL, Y.JOB

    FROM EMP X, EMP Y

    WHERE X.SAL > Y.SAL

    AND Y.ENAME = JONES;

    This query is designed to find the salaries and jobs of employees who earn more than JONES.

    It is quite complex and invokes a number of new concepts. Its main point is to define a

    sensible query involving a join which is not an Equi-join. In this case we have a GREATER-

    THAN join (i.e. X.SAL > Y.SAL).

    Another idea here is the concept of joining a table with itself - i.e. the EMP table with itself.

    The way that is done is to form two distinct copies of EMP which are called X and Y in thisexample. The definition of the copies is achieved via the FROM EMP X, EMP Y statement.

    Note that we can qualify the column names in the SELECT phrase, i.e. X.ENAME, X.SAL,

    Y.ENAME. Joins can be defined for other operators, e.g. =,!= etc.

    Outer Joins

    14

  • 8/14/2019 SQL Ref Manual

    15/55

    The above examples are of the type known as INNER-JOINS. In an inner-join, if a row in one

    of the joining tables does not satisfy the condition, it will not appear in the result. e.g., in the

    EMP table there is no employee with a DEPTNO of 40. This means that the result of

    SELECT DEPT.DEPTNO, DNAME, JOB, ENAMEFROM DEPT,EMP

    WHERE DEPT.DEPTNO=EMP.DEPTNO

    AND (DEPT.DEPTNO = 30 OR DEPT.DEPTNO = 40);

    would only contain a row with DEPTNO = 30. We might, however, want to record the fact that

    DEPTNO = 40 is the number of the OPERATIONS department. In order to include a row with

    DEPTNO = 40 we must use an outer join. This is denoted by the (+) symbol. The query then

    becomes:

    SELECT DEPT.DEPTNO, DNAME, JOB, ENAMEFROM DEPT,EMP

    WHERE DEPT.DEPTNO=EMP.DEPTNO (+)

    AND (DEPT.DEPTNO = 30 OR DEPT.DEPTNO = 40);

    Note that the EMP.DEPTNO is the term with the (+) sign. This indicates that the EMP table is

    the one that might not have a DEPTNO value.

    5. HANDLING DATA TYPES

    ORACLE supports Number, Character, Date and Null data types. The following sections

    describe how the data types are handled.

    5.1 Handling Numbers

    5.1.1 Displaying Numbers

    Number values are normally displayed with as many digits as necessary for accuracy up to thestandard width of 10 digits. The standard format can be altered by use of a FORMAT model in

    a COLUMN command. The structure of a COLUMN command is:

    COLUMN column-name FORMAT format-model;

    Some format-models are:-

    FORMAT VALUE DISPLAYS AS EXPLANATION

    15

  • 8/14/2019 SQL Ref Manual

    16/55

  • 8/14/2019 SQL Ref Manual

    17/55

    You may use arithmetic expressions in the condition of a WHERE clause.

    e.g. SELECT ENAME, SAL, COMM

    FROM EMP

    WHERE COMM > 0.25 * SAL;

    Lists employees whose Commission is greater than 25% of their Salary.

    You may use arithmetic expressions in ORDER BY clauses.

    e.g. SELECT ENAME, SAL, COMM, SAL+COMM

    FROM EMP

    ORDER BY SAL+COMM DESC;

    Arithmetic expressions can be complex, i.e. with several operators.

    5.1.3 Special Arithmetic Expressions

    SQL has a number of special arithmetic expressions.

    FUNCTION EXAMPLE RESULT

    ABS ABS(BALANCE) Absolute value of BALANCEGREATEST GREATEST(SAL,COMM) Largest value of SAL and COMM

    LEAST LEAST(SAL,COMM) Smallest value of SAL and COMM

    ROUND ROUND(SAL,2) SAL rounded to 2 digits after

    decimal point

    TO_NUMBER TO_NUMBER(GRADEPT) Converts a CHAR value

    containing a number to a number

    value

    TRUNC TRUNC(SAL,2) SAL truncated to 2 digits after

    the decimal point

    Some examples are now shown which illustrate the use of some of the above functions.

    e.g. SELECT ENAME, GREATEST (SAL,COMM)

    FROM EMP;

    For each employee, the name and value of Salary or Commission, whichever is the greater, is

    displayed.

    e.g. SELECT ENAME, SAL, SAL/22, TRUNC(SAL/22,0), TRUNC(SAL/22,2)FROM EMP

    17

  • 8/14/2019 SQL Ref Manual

    18/55

    WHERE DEPTNO = 30;

    For the Department with DEPTNO = 30 the employee name and various truncated displays of

    the Salary are shown. The division by 22 is because the daily salary is being calculated and it

    is assumed that there are 22 working days in the month.

    e.g. SELECT ENAME, SAL, SAL/22, ROUND (SAL/22,0), ROUND(SAL/22,2)

    FROM EMP

    WHERE DEPTNO = 30;

    This is the same as the previous query, except that some Rounded display formats are shown.

    5.1.4 Group Functions

    The Arithmetic Functions of the previous section are operating on EACH row of a query.

    However, sometimes we might want to obtain information about GROUPS of rows. e.g.,

    maximum salary for each JOB or the average COMMISSION of SALESMEN. In order to

    achieve this, SQL provides GROUP functions

    FUNCTION EXAMPLE RESULT

    AVG AVG(SAL) Average value of SAL

    COUNT COUNT(COMM) Number of non NULL values in

    the COMM column

    MAX MAX(SAL) Highest value of SAL

    MIN MIN(SAL) Lowest value of SAL

    SUM SUM(COMM) Sum of values of COMM

    e.g. SELECT SUM(SAL),SUM (COMM)FROM EMP

    WHERE JOB=SALESMAN;

    Finds the total salary and total commission of salespeople.

    e.g. SELECT 12* AVG(SAL+COMM)

    FROM EMP

    WHERE JOB=SALESMAN;

    18

  • 8/14/2019 SQL Ref Manual

    19/55

    Finds the average Annual salary, plus commission of all salespeople.

    e.g. SELECT MAX(SAL),MIN(SAL),MAX(SAL)-MIN(SAL)

    FROM EMP;

    Finds the highest and lowest salaries (of all employees) and the difference between them.

    e.g. SELECT COUNT(COMM)

    FROM EMP;

    Finds the number of non-null commissions.

    e.g. SELECT COUNT(DISTINCT JOB)

    FROM EMP

    WHERE DEPTNO = 30;

    Finds the number of DIFFERENT jobs held by the employees of department 30. The

    DISTINCT phrase eliminates duplicates before the count is made.

    e.g. SELECT COUNT(*)

    FROM EMP

    WHERE DEPTNO = 30;

    Counts the number of employees in department 30. Count(*) counts all the rows satisfying the

    WHERE clause.e.g. SELECT ENAME, JOB, SAL

    FROM EMP

    WHERE SAL =

    (SELECT MAX(SAL)

    FROM EMP);

    This is a special type of query. The SELECT clause in the brackets is a SUBQUERY. Subqueries

    will be dealt with in more detail in Chapter 6. The subquery SELECT returns a single value,

    namely the largest value in the SAL column of EMP. The query them becomes find the name,

    job and salary of the employee(s) whose salary is equal to the largest salary.

    5.1.5 The GROUP BY phrase

    Sometimes we might want to find out information about several groups within a table. e.g., we

    might want to find the average salary for each job. This could be achieved by:

    19

  • 8/14/2019 SQL Ref Manual

    20/55

  • 8/14/2019 SQL Ref Manual

    21/55

    e.g. SELECT DEPTNO

    FROM EMP

    WHERE JOB = CLERK

    GROUP BY DEPTNOHAVING COUNT(*) >= 2;

    Lists all the departments with at least two clerks.

    If you want to give a computed column a label other than the original expression, it can be

    done in the same way as for uncomputed columns.

    e.g. SELECT JOB, AVG(SAL) AVERAGE_SALARY

    FROM EMP

    GROUP BY JOB;

    Renames the AVG(SAL) as AVERAGE_SALARY. If two separate words are required then

    replace the AVERAGE_SALARY with AVERAGE SALARY. The quotes ensure that the two

    words are displayed together.

    5.2 Handling CHAR values

    Columns of the Character data type can be redefined using the COLUMN statement, which, as

    before, has the structure:

    COLUMN FORMAT format-model;

    The format model this time is merely A followed by the number of characters, e.g. A25.

    Once set, a column format will stay in effect until you redefine it or exit from SQLPLUS.

    A column format can be reset by using COLUMN column-name CLEAR.

    5.2.1 Concatenation

    The only operation that can be carried out on char fields is CONCATENATION. This is where

    two or more fields are joined together. The CONCATENATION operator is | |.

    e.g. SELECT DNAME | | - | | LOC DEPARTMENTS

    21

  • 8/14/2019 SQL Ref Manual

    22/55

    FROM DEPT;

    This results in:

    DEPARTMENTSACCOUNTING - NEW YORK

    RESEARCH - DALLAS

    SALES - CHICAGO

    OPERATIONS - BOSTON

    i.e., the value in the DNAME field is concatenated to blank space, minus sign, blank space

    concatenated to the value in the LOC field and the new column thus formed is called

    DEPARTMENTS.

    5.2.2 An Apostrophe in a char constant

    Since an apostrophe is used to denote a char constant, e.g. fred, if you want to denote an

    apostrophe in the middle of a char constant, you must in fact use two apostrophes. e.g. in

    order to denote freds, you must use freds.

    5.2.3 Char Functions

    Some common char functions are:-FUNCTION EXAMPLE RESULT

    DECODE DECODE(GRADE, A,4,B,3, Translates letter grades in

    C,2,D,1,0) the GRADE column into

    grade points

    INITCAP INITCAP(ENAME) Capitalises the first letter

    of each word

    INSTR INSTR(LOC, ) Returns the position of

    the first blank space in

    the location

    LENGTH LENGTH(ENAME) Length of the employees

    name in characters

    LOWER LOWER(ENAME) Converts an employees

    name to lowercase

    22

  • 8/14/2019 SQL Ref Manual

    23/55

  • 8/14/2019 SQL Ref Manual

    24/55

    Displays the word EMPLOYEE as the first column of each row. The column has no heading.

    5.3 Handling Date Values

    5.3.1 Standard and Alternate Date Formats

    The default or Standard date format is like 12-JAN-85. This format is written:

    DD-MON-YY.

    You can convert the date to a different format using the TO_CHAR function. The structure of

    the function is:

    TO-CHAR(date-value, format-model)

    Thus, to convert from 12-JAN-85 to 01/12/83 you would use the function

    TO_CHAR(HIREDATE,MM/DD/YY) where it is assumed that the original date is held in

    HIREDATE.

    There are other possible date formats, as follows:

    DD.MM.YYYYMONTH DD,YYYY

    DY DD MON YY

    Some common formats are:

    ELEMENT MEANING

    YYYY or SYYYY YEAR; S prefixes BC date with sign (-)

    YYY YY or Y Last 3,2 or1 digits ofYEAR

    SYEAR or YEAR YEAR, spelled out;S prefixes BC date with (-)

    BC or AD BC/AD indicator

    B.C. or A.D. BC/AD indicator with full stops

    Q Quarter of year

    MM Month

    MONTH or MON Name of month or three letter abbreviation

    DDD DD OR D Day of year, month or week

    DAY or DY Name of day or three letter abbreviation

    AM or PM Meridian indicator

    A.M. or P.M. Meridian indicator with full stops

    24

  • 8/14/2019 SQL Ref Manual

    25/55

    HH or HH12 Hour of day (1-12)

    HH24 Hour of day (0-23)

    MI Minute

    SS Second

    / . , etc Punctuation is reproduced in the result

    ... Quoted string is reproduced in the result

    The suffixes below may be added to the codes above

    TH Ordinal number, (e.g. DDTH for 4th)

    SP Spelled out number, (eg DDSP for FOUR)

    SPTH to THSP Spelled out ordinal number, (e.g. DDSPTH for FOURTH)

    Capitalisation in a spelled out word follows capitalisation in the corresponding format

    element.

    e.g. DAY produces output, such: MONDAY, Day produces Monday, day produces monday etc.

    5.3.2 Times of Day

    Oracle Dates also include the time of day. In order to display the time, merely include it in the

    format model

    e.g. COLUMN HIRE_DATE FORMAT A30;

    SELECT ENAME,

    TO_CHAR(HIREDATE,MONTH DD,YYYY HH:MIPM) HIRE_DATE

    FROM EMP

    WHERE DEPTNO = 20;

    Try it and see! Note that if in a date value, no time is specified then the default value given is

    12:00 AM.

    5.3.3 Date Arithmetic

    The arithmetic operations allowed on date fields are:

    date+number adds a number of days to a date, producing a date

    date-number subtracts a number of days from a fate, producing a date

    date-date subtracts one date from another, giving a number of days

    25

  • 8/14/2019 SQL Ref Manual

    26/55

    e.g. SELECT ENAME, HIREDATE, HIREDATE+365 REVIEWDATE

    FROM EMP

    WHERE DEPTNO = 20;

    Displays the Reviewdate which is defined as 365 days after the Hiredate

    5.3.4 SYSDATE

    There is a special column called SYSDATE, which returns the value of the current date and

    time. It is NOT an actual column in a Table and is thus a pseudo-column.

    e.g. SELECT ENAME, SYSDATE TODAYFROM EMP;

    Displays the current date for each employee.

    5.3.5 Date Functions

    There are a number of built-in functions involving Dates. Some of them are:

    FUNCTION EXAMPLE RESULT

    ADD_MONTHS ADD_MONTHS(d,n) date d plus n months

    GREATEST GREATEST (D1,D2) later of D1 and D2

    LEAST LEAST (D1, D2) earlier of D1 and D2

    LAST-DAY LAST_DAY(HIREDATE) last day of month containing

    HIREDATE

    MONTHS_BETWEEN MONTHS_BETWEEN(SYSDATE,HIREDATE)

    months between HIREDATE and

    today

    NEXT_DAY NEXT_DAY(HIREDATE,FRIDAY)

    date of first Friday after HIREDATE

    ROUND ROUND(HIREDATE) rounds HIREDATE to the nearest

    whole day

    TO_CHAR TO_CHAR(HIREDATE,MM/DD/YY)

    converts a date value to a char

    value. The format of the char

    value is determined by the

    specified format

    model. Default format used if 2nd

    argument absent

    26

  • 8/14/2019 SQL Ref Manual

    27/55

    TO_DATE TO_DATE(CHARDATE,MM/DD/YY)

    converts a char value containing

    a date to a date value. The char

    value is interpreted according

    to the specified format.

    Some Examples of Using Dates

    1) Find the review dates of employees hired in the last year for Dept 20, assuming that the

    reviewdate is a year after the hiredate.

    e.g. COLUMN HIREDATE A9

    COLUMN TODAY A9

    COLUMN REVIEWDATE A10

    SELECT ENAME, HIREDATE, SYSDATE TODAY, HIREDATE+365,

    REVIEWDATE

    FROM EMP

    WHERE HIREDATE + 365 > SYSDATE

    AND DEPTNO = 20;

    This gives:

    ENAME HIREDATE TODAY REVIEWDATE

    SCOTT 15-MAY-85 10-DEC-85 15-MAY-86ADAMS 18-JUN-85 10-DEC-85 18-JUN-86

    Assume that today is 10th Dec 1985.

    2) Calculate the number of days until the review

    e.g. COLUMN DAYS_TO_REVIEW A14

    SELECT ENAME, HIREDATE, SYSDATE TODAY,

    HIREDATE+365 - SYSDATE DAYS_TO_REVIEW,

    HIREDATE+365 REVIEWDATE

    FROM EMP

    WHERE HIREDATE+365 > SYSDATE

    AND DEPTNO=20;

    This gives:

    ENAME HIREDATE TODAY DAYS_TO_REVIEW REVIEWDATE

    SCOTT 15-MAY-85 10-DEC-85 155.985995370370 15-MAY-86

    3703703703703703

    27

  • 8/14/2019 SQL Ref Manual

    28/55

    ADAMS 18-JUN-85 10-DEC-85 189.986030092592 16-JUN-86

    9259259259259259

    Note that the examples work if there are 365 days in a year. The decimal fraction forDAYS_TO_REVIEW is unreadable. These points can be corrected by:

    e.g. SELECT ENAME, HIREDATE, SYSDATE TODAY,

    ROUND(ADD_MONTHS(HIREDATE,12)-SYSDATE) DAYS_TO_REVIEW

    ADD_MONTHS(HIREDATE,12) REVIEWDATE

    FROM EMP

    WHERE ADD_MONTHS (HIREDATE,12)> SYSDATE

    AND DEPTNO=20;

    3) Suppose reviews are not exactly one year after the hiredate. Suppose that reviews are onthe first Friday after the employee has been working for a year and that rises are given on the

    last day of the month of the review. NEXT_DAY and LAST_DAY can be used to calculate both

    of these dates.

    e.g. COLUMN RAISEDATE FORMAT A9;

    SELECT ENAME, HIREDATE,

    NEXT_DAY(ADD_MONTHS(HIREDATE,12),FRIDAY) REVIEWDATE,

    LAST_DAY(NEXT_DAY(ADD_MONTHS(HIREDATE,12),FRIDAY) )

    RAISEDATEFROM EMP

    WHERE ADD_MONTHS (HIREDATE,12)>SYSDATE

    AND DEPTNO = 20;

    This gives:

    ENAME HIREDATE REVIEWDATE RAISEDATE

    SCOTT 15-MAY-85 16-MAY-86 31-MAY-86

    ADAMS 18-JUN-85 20-JUN-86 30-JUN-86

    Using dates in SQL commands

    As well as in the SELECT clause you may use dates in other parts of SQL statements. in fact,

    you can use a date value anywhere that you use a number or a char value, i.e. in WHERE,

    ORDER BY and GROUP BY clauses. This is demonstrated through the following examples.

    1) SELECT ENAME, HIREDATE

    FROM EMP

    28

  • 8/14/2019 SQL Ref Manual

    29/55

    WHERE HIREDATE BETWEEN 4-JAN-84 AND 15-APR-84

    ORDER BY HIREDATE;

    2) SELECT TO_CHAR (HIREDATE,Q-Q YYYY) HIRE_DATE, COUNT(*)

    FROM EMP

    GROUP BY TO_CHAR (HIREDATE,YYYY Q-Q);

    Note that this example counts the employees hired in each quarter of each year.

    5.4 Handling Null Values

    A Null value is different from zero or blank. It is used to illustrate that a particular data field

    has not got a value in it yet, or that a value in that field would be inappropriate. e.g., in the

    EMP table, only Salesmen have values in the Commission field as only salesmen getcommission. The empty commission field entries have Null values in them.

    Null Conditions

    Comparisons can be made with Null fields by using IS NULL, IS NOT NULL

    e.g. Find the names of employees who are NOT entitled to commission.SELECT ENAME

    FROM EMPWHERE COMM IS NULL;

    e.g. Find the names of employees who are entitled to commission.SELECT ENAME

    FROM EMP

    WHERE COMM IS NOT NULL;

    ORDER BY with NULL values

    If the column involved in the ORDER BY has Null values then the tuples with the Null values

    will appear first, whether the order is to be Ascending or Descending

    Null values in Expressions and Functions

    If a function or expression involves a column that contains a Null value, then the result is also

    Null.

    29

  • 8/14/2019 SQL Ref Manual

    30/55

    e.g. If we wanted to form a column SAL+COMM then those tuples with Null values for COMM

    will cause a value of Null for SAL+COMM

    e.g. If we applied COUNT(COMM) then the COUNT function would return the number of non

    Null values.

    The Null Value function NVL

    The form of the NVL function is

    NVL(EXPRESSION, NON-NULL VALUE)

    e.g. NVL(COMM,0)

    would replace each null value of COMM with the value 0

    e.g. NVL(HIREDATE,31-DEC-86)

    would replace each null value of HIREDATE with the value 31-DEC-86

    This is a useful feature, enabling us to include null-valued entries in our queries.

    e.g. SELECT AVG(COMM), AVG(SAL+NVL(COMM,0))

    FROM EMP

    WHERE DEPTNO = 30;

    30

  • 8/14/2019 SQL Ref Manual

    31/55

    6. SUBQUERIES

    A subquery is a query contained in a WHERE clause. It provides you with results that are

    needed to complete the main query. Subqueries are useful when you want to select rows from

    a table with a condition that depends upon data in the table itself.

    e.g. SELECT ENAME, JOB

    FROM EMP

    WHERE JOB=

    (SELECT JOB

    FROM EMP

    WHERE ENAME=JONES);

    The subquery is contained in brackets. This subquery returns a single value, in this case

    MANAGER.

    The main query now becomes:

    e.g. SELECT ENAME, JOB

    FROM EMP

    WHERE JOB=MANAGER;

    If the subquery had returned no values or more than one value, then an error message would

    have been displayed.

    Using ANY and ALL

    Sometimes we want to use subqueries which return more than one value. In this situation we

    use the ANY or ALL options.

    e.g. SELECT DISTINCT SAL, JOB, ENAME, DEPTNO

    FROM EMP

    WHERE SAL > ANY

    (SELECT SAL

    FROM EMP

    WHERE DEPTNO = 30);

    Again, the subquery is contained in brackets. This query returns a set of all SAL values foremployees in Dept 30.

    31

  • 8/14/2019 SQL Ref Manual

    32/55

    The main query is now about looking at the EMP table for rows where the SAL value is greater

    than ANY of the subquery set. That is any row where the SAL value is greater than the

    smallest value of the subquery set.

    The DISTINCT clause is necessary in order to avoid rows being chosen many times. e.g., the

    PRESIDENT KING has a salary of $5000. Without the DISTINCT clause, the PRESIDENT row

    would be returned every time that it was compared with the subquery set, since the

    Presidents Sal is greater than ALL the subquery SAL values.

    e.g. SELECT SAL, JOB, ENAME, DEPTNO

    FROM EMP

    WHERE SAL> ALL

    (SELECT SAL

    FROM EMP

    WHERE DEPTNO=30);

    The subquery is as before and returns the same set of SAL values. This time, however, the

    main query returns those rows with SAL value greater than ALL the subquery set. Note that

    there is no need for the DISTINCT clause this time.

    ANY and ALL can be used with the operators ( =, , >, >=,

  • 8/14/2019 SQL Ref Manual

    33/55

    (SELECT JOB

    FROM EMP

    WHERE DEPTNO = 30);

    This lists the name and job of anybody in DEPT 10 with a job not done by anybody in DEPT 30.

    Subqueries that return more than one column

    So far, subqueries have returned a set of values based on one column only. However,

    sometimes it would be useful to return groups of values, i.e. values for more than one column.

    e.g. List employees with same job and salary as FORD.

    e.g. SELECT ENAME, JOB, SALFROM EMP

    WHERE (JOB,SAL)=

    (SELECT JOB, SAL

    FROM EMP

    WHERE ENAME = FORD);

    Multiple Subqueries

    It is possible to have combinations of subqueries separated by AND or OR.

    e.g. SELECT ENAME, JOB, DEPTNO, SAL

    FROM EMP

    WHERE JOB IN

    (SELECT JOB

    FROM EMP

    WHERE ENAME = JONES)

    OR SAL >=

    (SELECT SAL

    FROM EMPWHERE ENAME = FORD)

    ORDER BY JOB, SAL;

    This lists employees with either the same job as Jones or a salary greater than or equal to Fords

    salary, in order of job and salary.

    You can also put subqueries within subqueries with up to 16 levels.

    e.g.SELECT ENAME, JOB

    FROM EMP

    33

  • 8/14/2019 SQL Ref Manual

    34/55

    WHERE DEPTNO = 10

    AND JOB IN

    (SELECT JOB

    FROM EMP

    WHERE DEPTNO IN

    (SELECT DEPTNO

    FROM DEPT

    WHERE DNAME = SALES));

    This lists employees in Dept 10 with the same job as anyone in the Sales dept.

    Note

    A query or subquery may be composed of two or more queries with the operators UNION,

    INTERSECT and MINUS.

    UNION -- returns all distinct rows returned by EITHER of the queries it applies to.

    INTERSECT -- returns all rows returned by BOTH of the queries it applies to.

    MINUS -- returns all rows returned by the PRECEDING query but NOT by the FOLLOWING

    query.

    e.g. SELECT ENAME, JOB, SALFROM EMP

    WHERE SAL IN

    (SELECT SAL

    FROM EMP

    WHERE ENAME = SCOTT

    UNION

    SELECT SAL

    FROM EMP

    WHERE ENAME = WARD);

    This lists employees whose salary is equal to that of Scott or Ward.

    When applying the operators UNION, INTERSECT and MINUS for queries on different tables,

    the results of these queries must be union-compatible. In the context of SQL, this means that

    corresponding columns from the different results must match in both number of columns and

    type of column. Type does not imply that they must be of the same length, and you cannot use

    columns of type LONG.

    34

  • 8/14/2019 SQL Ref Manual

    35/55

    You can also use ORDER BY in the overall query. The ORDER BY must occur once only at the

    end. Since corresponding columns in different tables might have different names, the ORDER

    BY refers to the appropriate column by its order in the column list.

    e.g. Consider two similar tables, PROJ_A, PROJ_B with appropriate columns.

    e.g. SELECT ENAME, EMPNO, DEPT

    FROM PROJ_A

    UNION

    SELECT EMPNAME, EMPNUM, DEPT

    FROM PROJ_B

    ORDER BY 2;

    This lists employee details of employees who are in PROJ_A or PROJ_B, or both. The list isordered by column 2 (i.e. the employee number column).

    Subqueries can refer to more than one table.

    e.g. SELECT ENAME, LOC, JOB

    FROM EMP, DEPT

    WHERE LOC = CHICAGO

    AND EMP.DEPTNO = DEPT.DEPTNO

    AND JOB IN

    (SELECT JOB

    FROM EMP

    WHERE ENAME = ALLEN)

    ORDER BY ENAME;

    This lists the employees located in Chicago with the same job as ALLEN, in ENAME order.

    Correlated Subqueries

    In previous examples each subquery was carried out once for the whole query. However, it ispossible to construct a query where the subquery is carried out once for each row of the main

    query.e.g. SELECT DEPTNO, ENAME, SAL

    FROM EMP X

    WHERE SAL >

    (SELECT AVG(SAL)

    FROM EMP

    WHERE X.DEPTNO = DEPTNO)

    ORDER BY DEPTNO;

    35

  • 8/14/2019 SQL Ref Manual

    36/55

    This lists all employees who earn more than the average salary of employees in their own

    departments (in dept order).

    Note the ALIAS table name X for EMP. This means that X is a copy of the table EMP for use in

    the main query. There is another table EMP for the subquery. What happens here is that table

    X is scanned. The condition applied to each tuple of X is to check the SAL to see if it is greater

    than the average SAL calculated on the EMP table of the subquery. The average is taken for

    those rows where the DEPTNO is equal to current the DEPTNO value of the main query. This

    means that the subquery is carried out once for each row of the X table.

    EXISTS

    A conditional expression EXISTS (subquery) can be written which returns 'true' if the

    subquery returns at least one row and 'false' if there are no rows returned.

    e.g. SELECT JOB, ENAME, DEPTNO

    FROM EMP X

    WHERE EXISTS

    (SELECT *

    FROM EMP

    WHERE X.EMPNO = MGR);

    This lists information about employees who have at least one other employee reporting to

    them.

    NOT EXISTS

    A conditional expression NOT EXISTS (subquery) can be written which returns 'false' if the

    subquery returns at least one row and 'true' if there are no rows returned.

    e.g. SELECT JOB, ENAME, DEPTNO

    FROM EMP X

    WHERE NOT EXISTS

    (SELECT *

    FROM EMP

    WHERE X.EMPNO = MGR);

    This lists information about employees who do not have any employees reporting to them.

    36

  • 8/14/2019 SQL Ref Manual

    37/55

    7. CREATING, DROPPING and RENAMING TABLES

    Previous chapters have dealt with Data Manipulation in the form of retrieval operations. This

    chapter considers Data Definition. Since the only data structure is the table, data definition

    involves the definition of tables.

    The SQL statement which does this is the CREATE TABLE statement. The format of the

    CREATE TABLE statement is

    CREATE TABLE table-name

    (column-definition, column-definition, ...... column-definition);

    where column-definition = column-name column-format [NOT NULL].

    e.g. CREATE TABLE DOCTOR

    (DOCTOR_NO CHAR(4) NOT NULL,

    DOCTOR_NAME CHAR(20),

    DATE_OF_BIRTH DATE,

    FEE_RATE NUMBER(6,2));

    This creates a table with 4 columns. The DOCTOR_NO column is made up of at most 4

    characters and NULL values are not allowed in this column. The column for DOCTOR_NAME

    is up to 20 characters. The DATE_OF_BIRTH is of data type Date and the FEE_RATE column

    has at most 6 numeric digits of which 2 are after a decimal point.

    Specifying primary and foreign keys

    At the time a table is created it is possible to define both primary and foreign keys. Let us

    assume that two tables are to be created (TEMP1 and TEMP2) which participate in a foreign

    key relationship. The CREATE TABLE command could be used in the following way:

    CREATE TABLE TEMP1

    (COL1 CHAR(5),

    COL2 NUMBER(4),

    COL3 CHAR(10),

    CONSTRAINT PK_FIRSTCOL PRIMARY KEY (COL1),

    CONSTRAINT FK_COL FOREIGN KEY (COL3) REFERENCES TEMP2(COL1));

    37

  • 8/14/2019 SQL Ref Manual

    38/55

    CREATE TABLE TEMP2

    (COL1 CHAR(10),

    COL2 DATE,

    CONSTRAINT PK_TEMP2 PRIMARY KEY (COL1));

    It is also possible to set up both priamry and foriegn keys that are made up of more than just

    one column.

    7.1 Data types

    The data types supported for columns are:-Data Type May contain

    CHAR(w) This is a fixed length data type where char values consisting

    of upper and lower case letters numbers and special characters

    (+, -, %, $, &, etc.). w is the width which is the maximum length

    in characters. w must not exceed 240.

    VARCHAR2(w) This is a variable length data type where char values consisting

    of upper and lower case letters numbers and special characters

    (+, -, %, $, &, etc.). w is the width which is the maximum length

    in characters. w must not exceed 480. Here varying sizes of data

    can be stored and only the necessary amount of storage is allocated.

    NUMBER number values consisting of the digits 0-9 with an optional sign

    (+ or -) and a decimal point. Values may be 40 digits wide.

    NUMBER(w) numbers up to w digits wide. w may not exceed 105. Thenumber of significant digits may not exceed 40

    even if w is greater than 40.

    NUMBER(w,d) d of the digits are to the right of the decimal point.

    DATE date values from Jan 1, 4712 BC to Dec 31, 4712 AD.

    LONG similar to CHAR but values may be up to 65,535 characters

    long. No more than one LONG column can be defined fora table.

    38

  • 8/14/2019 SQL Ref Manual

    39/55

  • 8/14/2019 SQL Ref Manual

    40/55

    VALUES (list of data values)

    e.g. INSERT INTO EMP

    VALUES (7954, 'CARTER', 'CLERK', 7698, '7-APR-93', 1000, NULL, 30);

    ...... adds a new row into EMP.

    e.g. INSERT INTO EMP (EMPNO, ENAME, HIREDATE, DEPTNO, SAL)

    VALUES (7655, 'WILSON', '22-APR-93', 30, 1500);

    ...... adds values into the chosen columns only. Any columns not listed will have NULL values

    added. An attempt to put NULL into a NOT NULL field will cause an error.

    8.1.1 Inserting Date Values

    Date formats

    When a value is added into a date column it must be in standard date format, i.e. DD-MON-YY

    (01-JAN-93). A function (TO_DATE) is available to convert any date in another format to

    standard format. TO_DATE has two arguments: the first is the date value that you wish to add

    and the second is the format of that date value.

    e.g. INSERT INTO EMP

    VALUES (7657, 'MASON', 'ANALYST', 7566,

    TO_DATE('4/24/93', 'MM/DD/YY), 3400, NULL, 20);

    ....... takes a date in the form 4/24/93 and converts it to the standard form before insertion.

    Time of Day

    If you want to put in a time of day as well as a date then use:-

    e.g. INSERT INTO EMP

    VALUES (7658, 'CHAN', 'ANALYST', 7566,

    TO_DATE('3-MAY-93 9:30', 'DD-MON-YY HH:MI'), 3000, NULL, 20);

    8.1.2 Copying rows between tables.

    40

  • 8/14/2019 SQL Ref Manual

    41/55

    It is possible to copy rows between tables (i.e. from one table to another) by using a subquery

    in the INSERT statement.

    e.g. INSERT INTO BONUS (ENAME, JOB, SAL, COMM)SELECT ENAME, JOB, SAL, COMM

    FROM EMP

    WHERE JOB = 'MANAGER'

    OR COMM > 0.25 * SAL;

    ...... copies rows into the BONUS table where the employee is a Manager or the commission is

    more than a quarter of the salary.

    You can create and insert at the same time by using:-

    e.g. CREATE TABLE BONUS (ENAME, JOB, SAL, COMM)

    AS (SELECT ENAME, JOB, SAL, COMM

    FROM EMP

    WHERE JOB = 'MANAGER'

    OR COMM > 0.25 * SAL);

    Note that BONUS must not already exist as either a table or a synonym.

    8.1.3 Multiple Insertion

    When more than one row is to be inserted, the symbol & may be used before each attribute in

    the VALUES clause to obviate repeating the INSERT

    e.g. INSERT INTO EMP VALUES (&EMPNO, '&ENAME', '&HIREDATE',

    &DEPTNO, &SAL);

    When the INSERT is run, enter the data for the first row at the prompt. Then use the run

    symbol '/' to repeat the process for each successive row.

    8.2 UPDATE

    41

  • 8/14/2019 SQL Ref Manual

    42/55

    Updating values in a table is achieved using the UPDATE statement. The format of the

    UPDATE command is:-

    UPDATE table-name

    SET field = value, field = value, ......WHERE condition;

    e.g. UPDATE EMP

    SET JOB = 'SALESMAN', HIREDATE = SYSDATE, SAL = 1.1 * SAL

    WHERE ENAME = WILSON;

    ....... assigns Wilson to the sales staff and gives him/her a 10% rise in salary.

    Updating can be carried on several rows at a time:-

    e.g. UPDATE EMP

    SET SAL = SAL * 1.15

    WHERE (JOB = 'ANALYST' OR JOB = 'CLERK')

    AND DEPTNO = 20;

    ....... gives a 15% rise to all Analysts and Clerks in department 20.

    UPDATE statements can also include subqueries:-

    e.g. UPDATE EMP

    SET SAL = SAL * 1.05

    WHERE ENAME IN

    (SELECT ENAME

    FROM BONUS);

    ....... gives a 5% rise to anybody entitled to a bonus.

    e.g. UPDATE EMPSET SAL =

    (SELECT 1.1 * AVG(SAL)

    FROM EMP

    WHERE JOB = 'SALESMAN')

    WHERE JOB = 'SALESMAN';

    ....... sets all salesmen's salaries to 110% of the average salesman salary.

    42

  • 8/14/2019 SQL Ref Manual

    43/55

    8.3 DELETE

    Deleting information from tables is achieved using the DELETE statement. The format of the

    DELETE statement is:-

    DELETE FROM table-name

    WHERE condition;

    e.g. DELETE FROM BONUS

    WHERE ENAME = 'WARD';

    ....... deletes Ward from the bonus table.

    Several rows may be deleted at once by a suitable WHERE clause which may include a

    subquery if necessary.

    e.g. DELETE FROM BONUS

    WHERE JOB IN

    (SELECT JOB

    FROM EMP

    WHERE ENAME = 'JONES');

    ....... deletes all employees from the BONUS table with the name job as Jones.

    8.4 Committing database changes

    When changes are made to the database tables they may or may not be made permanent. The

    action of making changes permanent is known as COMMITTING. The default upon entering

    SQLPLUS is that changes will not normally be made permanent until you exit from SQLPLUS

    or you issue certain statements. (i.e. ALTER, AUDIT, CREATE, DISCONNECT, DROP, EXIT,

    GRANT, NOAUDIT, QUIT, or REVOKE)

    43

  • 8/14/2019 SQL Ref Manual

    44/55

    Thus in a normal situation when updates are deletes or inserts are made they will be visible if

    you inspect the tables but can be 'undone' by the issue of a ROLLBACK statement. If you wish

    to make changes permanent enter COMMIT.

    It is possible to arrange things such that changes are committed as soon as they are carried out.This can be achieved using the AUTOCOMMIT facility. The options are:-

    SQL> SET AUTOCOMMIT IMMEDIATE - turns the autocommit on

    SQL >SET AUTOCOMMIT ON - turns the autocommit on

    SQL> SET AUTOCOMMIT OFF - turns autocommit off (default)

    Note that after insertion of values into a table, the new records are not always committed. Be

    safe by issuing a commit at the prompt.

    9. MODIFYING A TABLE

    Sometimes the definition of a table might become inappropriate. We look here at the way we

    can make two changes to a table: enlarge a column, and add a column.

    Enlarging a column

    The format is

    ALTER TABLE table-name

    MODIFY (new column-definition);

    e.g. ALTER TABLE PROJ

    MODIFY (BUDGET NUMBER(9,2));

    ...... changes the budget column to 9 digits with 2 decimal places.

    You can change a format from NOT NULL to NULL but you can only change a column format

    from NULL to NOT NULL if there are no null values in the appropriate column.

    Adding a column

    The format is

    44

  • 8/14/2019 SQL Ref Manual

    45/55

    ALTER TABLE table-name

    ADD (column-definition);

    e.g. ALTER TABLE EMP

    ADD (PROJNO NUMBER);

    The new column will appear to the right of existing columns and will initially have all of it's

    values as NULL.

    10. VIEWS

    One of the most important facilities of a DBMS is the provision of user views. That is, the

    provision of mechanisms that allow the 'subsetting' of the centralised data resource in order to

    reflect individual perceptions of users.

    The view facility provides a level of security against inadvertent or deliberate inspection of

    sensitive data. Views can also help with complex query processing in that SQL statements canbe directed against views as opposed to the original tables.

    10.1 Creating a view

    The format for the view statement is:-

    CREATE VIEW view-name

    AS query;

    45

  • 8/14/2019 SQL Ref Manual

    46/55

    e.g. CREATE VIEW EMP10

    AS SELECT EMPNO, ENAME, JOB

    FROM EMP

    WHERE DEPTNO = 10;

    This defines a view of department 10 of the EMP table.

    Note that. the query in the CREATE VIEW may be any valid query but MUST NOT contain an

    ORDER BY clause. Any ordering must be carried out when the view is queried.

    You may create views from already defined views.

    View tables do not actually exist in the database. They are 'virtual tables'.

    10.2 Querying a view

    e.g. SELECT *

    FROM EMP10;

    ........ displays the contents of the view EMP10.

    e.g. SELECT ENAME, JOB

    FROM EMP10WHERE EMPNO > 7800;

    ....... picks rows from the view.

    When you change data in a base table the views which involve the updated rows/columns

    reflect the changes made.

    e.g. UPDATE EMP

    SET JOB = 'ANALYST'WHERE ENAME = 'MILLER';

    ....... changes Miller's job to analyst. If we now look at the view EMP10 we would see the

    change of Miller's job to analyst.

    10.3 Updating a view

    46

  • 8/14/2019 SQL Ref Manual

    47/55

    It may or may not be possible to carry out update operations directly on a view. For a view to

    be updatable the query in the CREATE VIEW statement must obey the following rules:-

    a) It must refer to only one table.

    b) It does not contain a GROUP BY clause, a DISTINCT clause, a group function, or a reference

    to the pseudo column ROWNUM.

    You may delete rows from a view if a) and b) occur. You may insert (add) rows into a view if a)

    and b) are satisfied and:-

    c) It contains no columns defined by expressions.

    Thus in order to change Miller's job to clerk, we can use:-

    e.g. UPDATE EMP10

    SET JOB = 'CLERK'

    WHERE ENAME = 'MILLER';

    10.4 Views of more than one table

    A view which contains data from more than table can be created by using joins to connect the

    tables,e.g. CREATE VIEW PROJSTAFF (EMPLOYEE, PROJECT, PROJECT_NUMBER)

    AS SELECT ENAME, PNAME, EMP.PROJNO

    FROM EMP, PROJ

    WHERE EMP.PROJNO = PROJ.PROJNO;

    This creates a view called PROJSTAFF with the columns renamed as EMPLOYEE(was

    ENAME), PROJECT(was PNAME) and PROJECT_NUMBER(was EMP.PROJNO).

    e.g. SELECT EMPLOYEE, PROJECT

    FROM PROJSTAFF

    WHERE PROJECT_NUMBER = 101;

    10.5 Using expressions and functions in views

    In the creation of a view the query that defines it may contain derived columns obtained from

    expressions on columns in the underlying tables.

    47

  • 8/14/2019 SQL Ref Manual

    48/55

  • 8/14/2019 SQL Ref Manual

    49/55

    11. REPORTING COMMANDS

    ORACLE provides facilities to improve the appearance of information displayed by a query.

    11.1 Page formatting

    The word page refers to a screenful of information on your display, or a page of a spooled

    report.

    The following commands can be issued at the SQL prompt to reformat the page:

    SET LINESIZE nn defines width of page (default is 80, maximum is 132).

    SET PAGESIZE nn defines length of page (default is 19).

    SET SPACE nn defines number of horizontal spaces between columns.

    SET NEWPAGE nn defines number of blank lines at end of page.

    SET PAUSE stops screen from scrolling.

    11.2 Report titles

    49

  • 8/14/2019 SQL Ref Manual

    50/55

    It is possible to define titles which can appear at the top or the bottom of each page of a report.

    TTITLE defines a title that appears at the top of each page.

    BTITLE defines a title that appears at the bottom of each page.

    Both these title commands can take various clauses:

    LEFT places the values at the beginning of the line.

    RIGHT places the values at the end of the line.

    CENTER places the values at the center of the line (based on LINESIZE).

    SKIP n begin a new line or begin n new lines.

    | stack the title.

    - continuation character.

    Example:

    TTITLE CENTER Company Confidential Report SKIP 1

    LEFT Sales for first Quarter RIGHT Computing Department SKIP 2;

    Would display the following heading at the top of every page of output:

    Company Confidential Report

    Sales for first Quarter Computing Department

    Example:

    BTITLE CENTER Draft submission

    Would display the following at the bottom of each page of output:

    Draft submission

    50

  • 8/14/2019 SQL Ref Manual

    51/55

    11.3 Formatting columns

    Columns of a table can be given new headings and new formats for the duration of the query.

    A more meaningful column heading can be displayed with the use of the COLUMN command:

    COLUMN HEADING

    Note that '|' can be used in to stack the heading.

    Example:

    COLUMN ENAME HEADING Employee| Name;

    You can change the displayed width of a column by:

    COLUMN FORMAT

    The is defined so that 'A' is used for character columns and '9' is used for numericcolumns.

    Example:

    COLUMN SAL HEADING Salary FORMAT 99,999;

    Or

    COLUMN ENAME FORMAT A10;

    The COLUMN command can also be used to suppress the display of a named column:

    COLUMN NOPRINT

    51

  • 8/14/2019 SQL Ref Manual

    52/55

    11.4 Structuring a report

    Control breaks can be used to structure a report into groups by the value of a column. All rows

    with the same value in that column are organised into a group.

    The BREAK command is used to organise the rows into groups.

    BREAK ON *must also use the SELECT's ORDER BY clause.

    Other breaks:

    BREAK ON ROW whenever a row is retrieved.

    BREAK ON PAGE at the end of a page.

    BREAK ON REPORT at the end of a report.

    Various types of action can be taken at breaks, e.g. an empty line can be displayed (SKIP) or a

    new page can be started (PAGE).

    After organising rows into groups with the BREAK, you can make the query perform

    computations on rows in the group. For example you can make a query compute subtotals on a

    specified column for the rows in each group as follows:

    COMPUTE SUM OF ON

    Any GROUP BY function can be used with COMPUTE, for example MAX, AVG and COUNT.

    Example:

    BREAK ON DEPTNO;

    COMPUTE SUM OF SAL ON DEPTNO;

    52

  • 8/14/2019 SQL Ref Manual

    53/55

    11.5 Displaying variable information in titles

    To display the page number in the title:

    TTITLE RIGHT 'Page' SQL.PNO;

    To display column values and special values such as SYSDATE in the title, use has to be made

    of a variable which can then be referenced by the TTITLE (or BTITLE) command.

    The sequence of commands is:

    COLUMN TODAY NEW_VALUE DATEVAR;

    This creates a variable DATEVAR to hold the value of the current date.

    TTITLE LEFT DATEVAR;

    Now that variable can be referenced in the TTITLE command.

    COLUMN TODAY NOPRINT;

    Usually if you print the value of a variable in the title, you do not want it to appear again in the

    body of the report.

    Now add SYSDATE to the SELECT command:

    SELECT TO_CHAR(SYSDATE, 'DD/MM/YY') TODAY .......;

    The same sequence can be followed for any column in a table.

    11.6 Saving reporting commands

    53

  • 8/14/2019 SQL Ref Manual

    54/55

    Normally, when SQLPLUS is entered, the input from the keyboard is taken into the default

    SQL buffer. However, when we enter formatting statements, for example, which change the

    current definitions of Column Formats, these are not taken into this normal buffer.

    Any attempt to SAVE the current work as afiedt.buf, for instance, will cause only the SQLstatement to be saved in the file. The formatting statements will not be saved. In order to

    SAVE the formatting statements as well, we must use the save as option to create a new file.

    Remember to give this file a new name with the usual .sql extension.

    When you are ready to run the file with the formatting commands in it simply use the

    following:

    @filename.sql

    Note that the @ symbol means run the contents of the file.

    54

  • 8/14/2019 SQL Ref Manual

    55/55

    APPENDIX 1 The Sample Tables

    Note: These are the sample tables which ORACLE comes with - there may be differences in

    the some of the data values.

    EMP

    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTN

    7369

    7499

    7521

    7566

    76547698

    7782

    7788

    7839

    7844

    7876

    7900

    7902

    7934

    SMITH

    ALLEN

    WARD

    JONES

    MARTINBLAKE

    CLARK

    SCOTT

    KING

    TURNER

    ADAMS

    JAMES

    FORD

    MILLER

    CLERK

    SALESMAN

    SALESMAN

    MANAGER

    SALESMAN

    MANAGER

    MANAGER

    ANALYST

    PRESIDENT

    SALESMAN

    CLERK

    CLERK

    ANALYST

    CLERK

    7902

    7698

    7698

    7839

    7698

    7839

    7839

    7566

    7698

    7788

    7698

    7566

    7782

    17-DEC-80

    20-FEB-81

    22-FEB-81

    02-APR-81

    28-SEP-81

    01-MAY-81

    09-JUN-81

    09-DEC-82

    17-NOV-81

    08-SEP-81

    12-JAN-83

    03-DEC-81

    03-DEC-81

    23-JAN-82

    800.00

    1,600.00

    1,250.00

    2,975.00

    1,250.00

    2,850.00

    2,450.00

    3,000.00

    5,000.00

    1,500.00

    1,100.00

    950.00

    3,000.00

    1,300.00

    300.00

    500.00

    1,400.00

    0.00

    20

    30

    30

    20

    30

    30

    10

    20

    10

    30

    20

    30

    20

    10

    DEPT

    DEPTNO DNAME LOC

    10

    20

    30

    40

    ACCOUNTING

    RESEARCH

    SALES

    OPERATIONS

    NEW YORK

    DALLAS

    CHICAGO

    BOSTON

    SALGRADE

    GRADE LOSAL HISAL

    1

    2

    3

    4

    5

    70 0

    1201

    1401

    2001

    3001

    1200

    1400

    2000

    3000

    9999