Intro Palco
Intro Palco
ORACLE7 SQL
By : Ammar Sajdi
Palestine Engineering Co
POBOX 17187
Amman – Jordan
E-mail: : [email protected]
Phone :+962-6-5826602/01
1
Palestine Engineering CO
ORACLE7 SQL
1. SQLPLUS .
Enter your user name and [Return]
SQL * Plus will display the prompt “ Enter Password :”.
Enter your password and press [ Return] again.
For your protection, your password will not appear on the screen.
SQL >
2. SQLPLUS username
You will be logged on the SQL* Plus. In this case the password will be
displayed.
For Windows Users; Find Oracle group icon and double click the SQL*Plus icon.
Oracle is shipped with a built-in user for the tutorial. The usename for that purpose is
SCOTT and the Password is TIGER
2
Palestine Engineering CO
ORACLE7 SQL
Any one of the following statements is valid :
SQL>SELECT
*
FROM
EMP
;
SQL>SELECT *
FROM EMP;
SQL * Plus commands are entered at the SQL > prompt on one line, they
do not open up a buffer.
Command Description
SPOOL OFF | OUT OFF closes spool file and OUT turns off
spooling and sends spool file to printer.
3
Palestine Engineering CO
ORACLE7 SQL
DESC[RIBE] displays any database table structure.
Using Files
Spool Files
The screen display produced by SQL*Plus can be captured permanently with the
SPOOL command. This will copy everything that appears on the screen to an
operating system file.
Spooling will continue until one of the other SPOOL commands is used.
SPOOL OUT will automatically direct the closed spool file to the system printer
( when connected ).
When you finish an SQL*Plus session and you have not closed the spool files all open
spool files are automatically closed.
4
Palestine Engineering CO
ORACLE7 SQL
- Tables can be created at any time, even with the users still on - line
using
the database.
Creating a Table
The name you choose for a table must follow the standard rules for naming an
ORACLE database object.
2. It may contain letters, numerals, and the special character - ( underscore ). The
characters $ and # are also legal, but their use is discouraged.
3. The name is the same whether upper or lower case letters are used e,g, EMP,
emp, and eMP are all the same table.
5. The name must not duplicate the name of another table or view in your
account.
NAME VALID
EMP96 YES
96EMP No; Does not begin with a character
AMMAR_SAJDI Yes
AMMAR SAJDI No; Contains a blank space
INSERT No; Reserved Word
Column Types
When you create a table, you need to specify the column’s data type. The table
5
Palestine Engineering CO
ORACLE7 SQL
below shows the most important data types.
The data type may be followed by one or more numbers in parentheses which give
information about the column’s width. The column’s width determines the
maximum width that values in the column may have . CHAR columns must have a
width specification; NUMBER columns may have a width specification, but need not.
Creating a Table
6
Palestine Engineering CO
ORACLE7 SQL
MGR NUMBER (4) ,
HIREDATE DATE,
SAL NUMBER (7 , 2 ) ,
COMM NUMBER (7 , 2 ) ,
DEPTNO NUMBER (2) NOT NULL ) ;
Table created
DESCRIBE EMP ;
- SAL and COMM have data type NUMBER (7,2). Total of 7 digits, two
of which are after decimal point ie. 12666.54, 37997,99.
7
Palestine Engineering CO
ORACLE7 SQL
- The table will be created with specified columns and the rows retrieved
by the SELECT statement inserted into it.
- If all the columns in the SELECT statement have well- defined names,
(i.e. no expressions, etc. ) , the column specifications may be omitted.
Table created.
Altering a Table
Table altered.
8
Palestine Engineering CO
ORACLE7 SQL
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NOT NULL NUMBER(2)
NATIONALITY VARCHAR2(20)
Table altered.
1. You may not change a column containing nulls from NULL to NOT NULL
2. You may not add a new column that is NOT NULL. Make it null, fill it
completely and then change it to NOT NULL.
3. You may not decrease the size of a column or change its data type, unless it
contains no data.
IF the structure of a table or view is unknown to the user, the DESCRIBE command
can be used as was demonstrated several times earlier. The Describe command is
SQL*PLUS command and is not part of the standard SQL LANGUAGE. It is a
command that only exists in SQL*Plus environment
The RENAME command is a handy command that can be used by the creator of a
TABLE (and other objects to be discussed later like VIEWS and SYNONYMS) to
change the name of the database object
9
Palestine Engineering CO
ORACLE7 SQL
to rename the DEPT table to DEPARTMENT, enter
Dropping a Table
To remove the definition of an ORACLE table use the DROP TABLE command
(Note: Advanced usage of the Drop table is : DROP TABLE XXX CASCADE
CONSTRAINTS. More information can be found in Topics concerning Constraints).
-Dropping a table loses all the data in it and all the indexes.
Note: In a later section we will study the subject of Constraints and Referential
Integrity. Constraint are implemented using the CREATE TABLE and ALTER
TABLE SQL Commands.
10
Palestine Engineering CO
ORACLE7 SQL
It is possible to insert a new row with values in each column, in which case the
column list is not required. It is recommended that the COLUMN LIST is ALWAYS
specified. If the list is not specified the software will require modification whenever
the table definition is altered .
Note that this command adds only one row at a time to a table .
To enter a new department omitting department name, the column list must be
specified :
When the command is run, values are prompted for every time.
11
Palestine Engineering CO
ORACLE7 SQL
When inserting a DATE value, the format DD-MON-YY is usually used. With this
format the century defaults to the 20th Century (19nn). The date also contains time
information, which if not specified defaults to midnight
This form of the insert statement allows you to insert several rows into a table where
the values are derived from the contents of existing tables in the database .
Updating Rows
For example;
If the WHERE clause is omitted, all rows in the table will be updated.
12
Palestine Engineering CO
ORACLE7 SQL
Suppose you had a table of new commission figures for certain employees.
For example, the COMMISSION table below is to be used to update certain rows of
the EMP table.
COMMISSION EMP
The changes listed in the COMMISSION table can be applied to the EMP table using
a correlated subquery and a nested subquery as show below
Example 1:
UPDATE EMP
SET COMM= (SELECT COMM FROM COMMISSION C
WHERE C.EMPNO = EMP.EMPNO)
WHERE EMPNO IN (SELECT EMPNO FROM COMMISSION);
The COMMISSION table might contain more than one entry for a given employee as
illustrated below:
EMPNO COMM
7499 1100
7654 500
7844 3500
7844 2000
7844 1500
You want to REPLACE the commission values on the EMP table with the TOTAL
commission for each employee listed in the COMMISSION table.
UPDATE EMP
SET COMM = (SELECT SUM(COMM) FROM COMMISSION C
WHERE C.EMPNO = EMP.EMPNO)
WHERE EMPNO IN (SELECT EMPNO FROM COMMISSION);
13
Palestine Engineering CO
ORACLE7 SQL
The EMP table now reflects the changed commissions:
EMP
EMPNO COMM
7499 1100
7654 650
7844 7000
The DELETE command allows you to remove one or more rows from a table.
Transaction Processing
There are two classes of transactions. DML transactions which can consist of any
number of DML statements and which ORACLE treats as a single entity or logical
unit of work, and DDL transactions which can only consist of one DDL statement.
There can be no ` half-way` situation during the execution of the transaction, where
some changes specified within the transaction are made to the database and others are
not made. For every transaction either all the changes made to the database are made
permanent, or none of the changes are carried out ( they are all discarded ).
- COMMIT / ROLLBACK
14
Palestine Engineering CO
ORACLE7 SQL
- Logoff
- Machine failure
In order for changes to become permanent, they must be committed to the database.
The COMMIT command makes database changes permanent; ROLLBACK allows
us to discard or abandon changes. The change, or changes, made to the database
between two commit commands therefore make up a transaction.
When a transaction is interrupted by a serious error, for example a system failure, the
entire transaction is automatically rolled back. This prevents the error from causing
unwanted changes to your data, and returns your tables to their status at the time of
the last commit. In this way SQL* Plus protects the integrity of your tables.
A new transaction is started following a commit or rollback - that is when the first
executable DML or DDL statement is encountered.
AUTOCOMMIT
Command Description
15
Palestine Engineering CO
ORACLE7 SQL
issued if <control> Z is pressed, when a
DROP, ALTER or CREATE command is
issued, or if you exit from SQL*Plus
ROLLBACK can be issued explicitly by
the user, to reinstate the database.
Read Consistency
The database reader and writer must be guaranteed a consistent view of the data.
Readers must not view data which is in the process of being changed. Writers also
need to be sure that changes to the database are done in a consistent way : That the
changes made by one writer do not disrupt or conflict with changes another writer is
making .
The purpose of read consistency is to ensure that each user sees data as it existed at
the last commit, before a DML operation has started .
When an insert, update, or delete operation is made to the database, ORACLE will
take a copy of the data before it is changed and write it to the Rollback Segment.
All readers, except those who issued the changes, still see the database as it existed
before the changes started - they view the Rollback Segment `snapshot` of the data.
However, before changes are committed to the database, only the user who is
modifying the data sees the database with the alterations incorporated.
Everyone else sees the rollback segment. This guarantees that readers of the data read
consistent data that is not currently undergoing change.
When a DML command is committed, the change made to the database becomes
visible to anyone executing a SELECT statement . The modifications are made
`universal ` and all users now see the database with the changes incorporated.
The space occupied by the `old` data in the rollback segment is freed for re-use .
- the original data in the Rollback are copied back to the database.
- all users see the database as it existed before the transaction began .
16
Palestine Engineering CO
ORACLE7 SQL
What is a lock ?
ORACLE allows any number of readers to access the same data at the same time,
because reading does not change the data. However, ORACLE permits only one
writer to a record of a table at a time.
When a user ,for example, updates a record, ORACLE will automatically lock this
record and will prevent other users from accessing this for all kind of writing
operations (Update, Delete). When the operation is committed or rolled back, the
lock is automatically released.
17
Palestine Engineering CO
ORACLE7 SQL
To list all department numbers, employee names and manager numbers in the EMP
table you enter the following :
It is possible to select all columns from the table , by specifying an * after the
SELECT command word.
- Arithmetic Expressions
- Column Aliases
18
Palestine Engineering CO
ORACLE7 SQL
- Concatenated Columns
- Literal
- Functions
All of these options allow the user to query data and manipulate it for query purposes;
for example, performing calculations, joining columns together, or displaying literal
text strings.
Arithmetic Expressions
Arithmetic Expressions may contain column names, constant numeric values and
the arithmetic operators :
Operators Description
+ add
- subtract
* multiply
/ divide
The priority is * , / first, then +, - second ( left to right if there are several operators
with the same priority ).
Parentheses may be used to specify the order in which operators are executed, if for
example, addition is required before multiplication .
ENAME SAL*12
---------- ----------
SMITH 9600
ALLEN 19200
WARD 15000
JONES 35700
MARTIN 15000
BLAKE 34200
CLARK 29400
SCOTT 36000
KING 60000
TURNER 18000
ADAMS 13200
JAMES 11400
FORD 36000
MILLER 15600
Column Aliases
19
Palestine Engineering CO
ORACLE7 SQL
When displaying the result of a query, SQL*Plus normally uses the selected
column’s name as the heading . In many cases it may be fairly cryptic or
meaningless. You can change a column’s heading by using an Alias.
To display the column heading ANNSAL for annual salary instead of SAL*12 user
the alias:
14 rows selected.
To combine EMPNO and ENAME and give the expression the alias EMPLOYEE,
enter:
EMPLOYEE
------------------------------------------------
7369SMITH
7499ALLEN
7521WARD
7566JONES
7654MARTIN
7698BLAKE
7782CLARK
7788SCOTT
7839KING
7844TURNER
7876ADAMS
7900JAMES
7902FORD
20
Palestine Engineering CO
ORACLE7 SQL
7934MILLER
Literals
A literal is any character, expression, number included on the SELECT list which is
not a column name or a column alias.
A literal in the SELECT list is output for each row returned. Literal strings of free
format text can be included in the query result, and are treated like a column in the
select list.
Date and character literals must be included in single quotes (‘); number literal do not
need single quotes. The following statement contains literals selected with
concatenation and a column alias:
Functions
21
Palestine Engineering CO
ORACLE7 SQL
If any column values in an expression are null, the result is null. In the following
statement, only Salesmen have a remuneration result:
ENAME ANNUAL_SAL
-------------------- --------------------
SMITH
ALLEN 19500
WARD 15500
JONES
MARTIN 16400
BLAKE
CLARK
SCOTT
KING
TURNER 18000
ADAMS
JAMES
FORD
MILLER
14 rows selected.
In order to achieve a result for all employees, it is necessary to convert the null value
to a number. We use the NVL function to convert a null value to a non-null value.
ENAME ANNUAL_SAL
------------------------- --------------------
SMITH 9600
ALLEN 19500
WARD 15500
JONES 35700
MARTIN 16400
BLAKE 34200
CLARK 29400
SCOTT 36000
KING 60000
TURNER 18000
ADAMS 13200
JAMES 11400
FORD 36000
MILLER 15600
14 rows selected.
22
Palestine Engineering CO
ORACLE7 SQL
1. an expression
2. a non-null value.
Note that you can use the NVL function to convert a null number, date or even
character string to another number, date or character string, as long as the data types
match.
NVL(DATACOLUMN,’01-JAN-88’);
NVL(NUMBERCOLUMN,9)
To eliminate duplicate values in the result, include the DISTINCT clause in the
SELECT command :
DEPTNO
---------
10
20
30
Multiple columns may be specified in the DISTINCT clause and the DISTINCT
works on all selected columns.
DEPTNO JOB
--------- ---------
10 CLERK
10 MANAGER
10 PRESIDENT
20 ANALYST
20 CLERK
20 MANAGER
30 CLERK
30 MANAGER
30 SALESMAN
9 rows selected.
Note that the DISTINCT command word can only be referred to once and must
immediately follow the SELECT command word.
Normally the order of rows returned in a query result is undefined. The ORDER BY
23
Palestine Engineering CO
ORACLE7 SQL
clause may be used to sort the rows. If used, ORDER BY must always be the last
clause in the SELECT statement .
ENAME SAL
---------------- ---------
ADAMS 1100
ALLEN 1600
BLAKE 2850
CLARK 2450
FORD 3000
JAMES 950
JONES 2975
KING 5000
MARTIN 1250
MILLER 1300
SCOTT 3000
SMITH 800
TURNER 1500
WARD 1250
14 rows selected.
To reverse this order, the command word DESC is specified after the column name in
the ORDER BY clause.
To reverse the order of the HIREDATE column, so that the latest dates are displayed
first, enter:
ENAME HIREDATE
------------------------- --------------
ADAMS 12-JAN-83
SCOTT 09-DEC-82
MILLER 23-JAN-82
24
Palestine Engineering CO
ORACLE7 SQL
JAMES 03-DEC-81
FORD 03-DEC-81
KING 17-NOV-81
MARTIN 28-SEP-81
TURNER 08-SEP-81
CLARK 09-JUN-81
BLAKE 01-MAY-81
JONES 02-APR-81
WARD 22-FEB-81
ALLEN 20-FEB-81
SMITH 17-DEC-80
14 rows selected.
It is possible to ORDER BY more than one column. The limit is in fact the number of
columns on the table. In the ORDER BY clause specify the columns to order by,
separated by commas. If any or all are be reversed specify DESC after any or each
column.
14 rows selected.
Note: To order by a column, it is not necessary for that column to be in the SELECT
list as the above example indicates.
25
Palestine Engineering CO
ORACLE7 SQL
The WHERE clause may compare values in columns, literal values, arithmetic
expressions or functions. The WHERE clause expects 3 elements :
1. A column name
2. A comparison operator
Logical Operators
Operator Meaning
= equal to
To list the names, number, jobs and departments of all clerks, enter :
26
Palestine Engineering CO
ORACLE7 SQL
KING PRESIDENT 17-NOV-81 10
FORD ANALYST 03-DEC-81 20
6 rows selected.
You can compare a column with another column in the same row, as well as with a
constant value.
For example, suppose you want to find those employees whose commission is greater
than their salary, enter:
SQL Operators
There are four SQL operators which operate with all data types :
SQL Operators
Operator Meaning
Tests for values between, and inclusive of, low and high range.
Suppose we want to see those employees whose salary is between 1000 and
2000:
ENAME SAL
------------------------- ---------
ALLEN 1600
WARD 1250
27
Palestine Engineering CO
ORACLE7 SQL
MARTIN 1250
TURNER 1500
ADAMS 1100
MILLER 1300
6 rows selected.
Note that values specified are inclusive, and the lower limit must be specified first.
The IN Operator
EMPNO ENAME
--------- -------------------------
7788 SCOTT
7902 FORD
7499 ALLEN
Sometimes you may not know the exact value to search for . Using the LIKE
operator it is possible to select rows that match a character pattern, The character
pattern matching operation may be referred to as a `wild-card` search. Two
symbols can be used to construct the search string .
Symbol Represents
ENAME
-------------------------
SMITH
SCOTT
28
Palestine Engineering CO
ORACLE7 SQL
3 WHERE ENAME LIKE '_ _ _ _';
ENAME
-------------------------
WARD
KING
FORD
IS NULL Operator
The IS NULL operator specifically tests for values that are NULL.
So to find all employees who have no manager, you are testing for a NULL value:
ENAME MGR
------------------------- ---------
KING
Operator Description
ENAME SAL
------------------------- ---------
SMITH 800
JONES 2975
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
JAMES 950
FORD 3000
8 rows selected.
29
Palestine Engineering CO
ORACLE7 SQL
The AND and OR operators may be used to make compound logical expression
To find all employees who are either clerks and/or all employees who earn between
1000 and 2000, enter:
8 rows selected.
Operator Precedence
3. AND
4. OR
SELECT Summary
So far the following clauses have been covered in the SELECT command:
30
Palestine Engineering CO
ORACLE7 SQL
The following statement prompts the user for a department number at run time.
ENAME SAL
------------------------- ---------
CLARK 2450
KING 5000
MILLER 1300
Note how &dept_no in the old clause was substituted with 10 in the new clause.
With the single ampersand the user is prompted every time the command is
executed, because the variable is not defined and consequently the value entered is
not saved.
It is possible to prompt for a column name or even a table name at run time
ENAME JOB
------------------------- --------------
KING PRESIDENT
31
Palestine Engineering CO
ORACLE7 SQL
If the variable is prefixed with a double ampersand (&&), SQL*Plus will only
prompt for the value once. The variable prompted for is defined system level and
used again whenever the SQL statement is run.
ENAME JOB
------------------------- ---------
CLARK MANAGER
KING PRESIDENT
MILLER CLERK
Use the DEFINE command and you will find that DEPT_NO is defined for the
session
SQL> DEFINE
DEFINE DEPT_NO = "10" (CHAR)
You can use the SQL*Plus DEFINE command to determine if a variable is already
defined. If the variable is defined, it displays the assigned value.
A value may be assigned to a variable using the SQL*Plus command DEFINE. The
value defined may be referenced in a SELECT statement or command file by
prefixing the variable name with an ampersand (&). The variables may be emptied by
using the UNDEFINE command.
Example
ENAME SAL
------------------------- ---------
ALLEN 1600
WARD 1250
MARTIN 1250
BLAKE 2850
TURNER 1500
32
Palestine Engineering CO
ORACLE7 SQL
JAMES 950
6 rows selected.
The ACCEPT command allows a variable to be created and a value, which is entered
at runtime, stored in it. This variable can then be referenced in a SQL statement.
ACCEPT is often used in a command file. There are benefits in using ACCEPT to
define substitution variables:
Example
ENAME SAL
------------------------- ---------
ALLEN 1600
WARD 1250
MARTIN 1250
TURNER 1500
33
Palestine Engineering CO
ORACLE7 SQL
FUNCTIONS
Introduction to Functions
Functions are used to manipulate data items. They accept one or more arguments
and return one value. An argument is a user-supplied constant, variable or column
reference. The format for a function is as follows:
- CHARACTER
- NUMBER
- DATE
- CONVERSION
- GROUP
34
Palestine Engineering CO
ORACLE7 SQL
The following table explains the notations that will be used while describing functions
Explanation of Notation
Notation Meaning
Col Any named database columns
Value Any literal value (character/date/number)
n A number
‘string’ character string
chars a number of specified characters
date date column, or date value
Character Functions
Single row character functions accept character data as input and can return both
character and number values.
Enter:
LOWER(ENAME) LOWER('AN
------------------------- ---------
allen any value
ward any value
martin any value
blake any value
turner any value
james any value
6 rows selected.
INITCAP (col|values) Forces the first letter of each word of the string to be
capitalized
35
Palestine Engineering CO
ORACLE7 SQL
INITCAP(DNAME) INITCAP(LOC)
-------------- -------------
Accounting New York
Research Dallas
Sales Chicago
Operations Boston
ENAME LPAD(SAL,15,'.'
------------------------- ---------------
SMITH ............800
WARD ...........1250
MARTIN ...........1250
ADAMS ...........1100
JAMES ............950
MILLER ...........1300
SAL GRAPH
--------- --------------------------------------------------
800 *******
1600 ***************
1250 ************
2975 *****************************
1250 ************
2850 ****************************
2450 ************************
3000 *****************************
5000 *************************************************
1500 **************
1100 **********
950 *********
3000 *****************************
1300 ************
14 rows selected.
RPAD (col|value,n,’string”) The total length is n and the trailing spaces are
filled with ‘string’.
36
Palestine Engineering CO
ORACLE7 SQL
- Two characters from the literal AMMAR starting at the second positions
- Contents of DNAME beginning with the third character till the end.
SU SUBSTR(DNAME
------ ------------
MM COUNTING
MM SEARCH
MM LES
MM ERATIONS
6 rows selected.
DNAME INSTR(DNAME,'C',1,2)
-------------- ------------------------------
ACCOUNTING 3
RESEARCH 0
SALES 0
OPERATIONS 0
Another Example:
Assume that you have a table containing the following field which contains the year
in the last two digits (95)
123/AB/95
87G12/33AC/95
and you want to extract the year from the string. Note that the position of the year
is not fixed
.
37
Palestine Engineering CO
ORACLE7 SQL
The following SQL will get the correct answer.
SQL> SELECT SUBSTR('&&X',INSTR('&X','/',1,2)+1,2) FROM DUAL
2 ;
Enter value for x: 123/AB/95
old 1: SELECT SUBSTR('&&X',INSTR('&X','/',1,2)+1,2) FROM DUAL
new 1: SELECT SUBSTR('123/AB/95',INSTR('123/AB/95','/',1,2)+1,2) FROM DUAL
SU
----
95
SQL> UNDEF X
SU
----
95
ENAME LTRIM(ENAME,'S')
------------------------- -------------------------
SMITH MITH -- NOTE THAT LEADING S WAS REMOVED
WARD WARD
MARTIN MARTIN
ADAMS ADAMS
JAMES JAMES
MILLER MILLER
6 rows selected.
RTRIM has the same function of LTRIM but the chars are removed from right instead
of left. This function can be particularly helpful in removing extraneous blanks from
the end of data in a column.
Example
UPDATE EMP
SET ENAME = RTRIM(ENAME)
38
Palestine Engineering CO
ORACLE7 SQL
SOUNDEX(col|value) Returns a character string representing the sound
of word(s) for each column or literal value.
ENAME SAL
------------------------- ---------
MILLER 1300
TRANS TRANS
--------- ---------
AXXAR MAJDI
Note that each occurrence of the letter ‘M’ was translated to letter ‘X’. Practical
usage of this function can be Code Page translation and Encryption
39
Palestine Engineering CO
ORACLE7 SQL
EXAMPLE:
Changes
-------------
OMAR and OMAN
EXAMPLE:
SQL>SELECT ASCII('A') FROM DUAL
ASCII('A')
---------------
65
EXAMPLE:
Character
---------
K
Number Functions
Number functions accept numeric input and return numeric values. Most of these
functions return values that are accurate to 38 decimal digits.
40
Palestine Engineering CO
ORACLE7 SQL
5 FROM EMP WHERE DEPTNO =20;
TRUNC(99.99) TRUNC(99.99,-1)
--------------- ----------------------
99 90
6 rows selected.
MOD(3,2)
-------------
1
41
Palestine Engineering CO
ORACLE7 SQL
CEIL(99.1) CEIL(-11.3)
-------------- ----------------
100 -11
FLOOR(99.1) FLOOR(-11.3)
----------- ------------
99 -12
Sign
----
-1
The following mathematical functions are available with ORACLE7 and are accurate
to 36 decimal digits.
COS( ), COSH( ),EXP( ), LN( ), LOG( ), SIN( ), SINH( ), TAN( ), TANH( ), SQRT(
), POWER()
EXAMPLE
Nested functions
Single row functions can be nested to any depth. If functions are nested, they are
evaluated from the inner to the outer functions(s).
42
Palestine Engineering CO
ORACLE7 SQL
Suppose that you want to find out the number of times a specified character occurs in
a string. How would you achieve this?
You can nest the LENGTH and TRANSLATE functions to achieve the required
result. The following example allows you to count the number of S’s in a string
DNAME LENGTH(DNAME)-LENGTH(TRANSLATE(DNAME,'AS','A'))
-------------- -------------------------------------------------------------------------
ACCOUNTING 0
RESEARCH 1
SALES 2
OPERATIONS 1
-Now, subtract the length of the string - from which we have eliminated all
S’s, from the length of the original string (string with S’s included).
Date Functions
- Century
- Year
- Month
43
Palestine Engineering CO
ORACLE7 SQL
- Day
- Hours
- Minutes
- Seconds
The default display / input format for any date is DD- MON- YY. Oracle dates can
rang between 1 st Jan 4712 BC and 31 st Dec 4712 AD.
SYSDATE is a pseudo-column that returns the current date and time. You can use
SYSDATE just as you would use any other column name. For example, you can
display the current date by selecting SYSDATE from a table. It is customary to select
SYSDATE from a dummy table called DUAL. The DUAL table is owned by the
SYSTEM and may be accessed by all users. It contains one column, and one row with
a value `X`. The DUAL table is useful when you want to return a value once only- for
instance, the value of a constant, pseudo_column or expression that is not derived
from a table with `user` data.
You could have easily SELECTed SYSDATE FROM EMP, but 14 rows of the same
SYSDATE would have been returned, one for every row of the EMP table. DUAL is
preferred because it conveniently returns one row only.
Due to the fact that the date is stored as a number, it is possible to perform
calculations with dates using arithmetic operators such as addition and subtraction.
You can add and subtract number constants as well as other dates from dates.
44
Palestine Engineering CO
ORACLE7 SQL
Subtracting SYSDATE from the HIREDATE column of the EMP table returns the
number of days since each employees was hired.
MONTHS_BETWEEN(SYSDATE,HIREDATE) MONTHS_BETWEEN('20-AUG-96','1-JAN-96')
--------------------------------------------------------- ----------------------------------------------------------
184.27024 7.6129032
182.10895 7.6129032
174.9154 7.6129032
159.43153 7.6129032
172.72186 7.6129032
171.07669 7.6129032
6 rows selected.
ADD_MONTH
------------------
20-APR-96
HIREDATE NEXT_DAY(
--------------- ---------------
17-DEC-80 19-DEC-80
02-APR-81 03-APR-81
09-DEC-82 10-DEC-82
12-JAN-83 14-JAN-83
03-DEC-81 04-DEC-81
LAST_DAY(date1) Finds the date of the last day of the month that contains
date1
SQL>SELECT LAST_DAY(SYSDATE),LAST_DAY('12-FEB-96')
FROM DUAL
LAST_DAY(SYSDATE) LAST_DAY
------------------------------ ---------------
45
Palestine Engineering CO
ORACLE7 SQL
30-APR-96 29-FEB-96
ROUND(date1,’YEAR’) Return the first day of the year containing date1 if date1
is in the first half of the month; otherwise returns the
first day of the following year.
SYSDATE ROUND(SYS
------------- ----------------
25-APR-96 01-MAY-96
Conversion Functions
The 'nlsparams' specifies these characters that are returned by number format
elements:
* decimal character
* group separator
* local currency symbol
* international currency symbol
'NLS_NUMERIC_CHARACTERS = ''dg''
NLS_CURRENCY = ''text''
46
Palestine Engineering CO
ORACLE7 SQL
NLS_ISO_CURRENCY = ''text'' '
The characters d and g represent the decimal character and group separator,
respectively. They must be different single-byte characters. Note that within the
quoted string, you must use two single-quotes to represent one around the
parameter values.
If you omit 'nlsparams' or any one of the parameters, this function uses the default
parameter values for your session.
EXAMPLE:
Char
--------------
JD 017,145
'NLS_DATE_LANGUAGE = language'
If you omit nlsparams, this function uses the default date language for your
session.
EXAMPLES:
SYSDATE TO_CHAR(SYSDATE,'MONTH,MON,DY')
-------------- ----------------------------------------------------------------------
27-APR-96 APRIL , Apr, Sat
Note that the pictures MONTH, DAY in the output are automatically padded with
blanks to a length of 9. To remove the blank padding use the FM (Fill Mode) prefix
47
Palestine Engineering CO
ORACLE7 SQL
SYSDATE TO_CHAR(SYSDATE,'FMMONTH,YYYY')
--------------- ---------------------------------------------------------------
27-APR-96 APRIL, 1996
The TO_CHAR can also be used to extract the time of day and display it is specific
format:
SQL> SELECT TO_CHAR(SYSDATE, 'HH24:MI:SS') FROM DUAL;
TO_CHAR(SYSDATE,'HH24:MI:SS')
------------------------------------------------------------
19:54:06
PICTURE MEANING
YYYY Year
SYYYY Prefix “BC” date with “-”
YEAR Year spelled out as in nineteen ninety-six
MONTH Name of month, padded with blanks to length of 9
MON Name of month, 3 letter abbreviation as in APR
WW Week of Year
DDD Day of year
HH Hours of day (1-12)
HH24 Hours of day (0-23)
SSSSS Seconds Past mid night (0-863999).
Note. The codes are case sensitive add will affect display of date elements
DAY SUNDAY
Day Sunday
day Sunday
MONTH MAY
MON MAY
Mon May
mon may
etc..
TO_NUMBER(char|varchar)
Converts char,varchar2, which contains a number to a NUMBER
48
Palestine Engineering CO
ORACLE7 SQL
SQL> SELECT EMPNO, ENAME FROM EMP
WHERE SAL < TO_NUMBER('1500')
EMPNO ENAME
--------- -------------------------
7369 SMITH
7521 WARD
7654 MARTIN
7876 ADAMS
7900 JAMES
7934 MILLER
6 rows selected.
TO_DATE (‘char’,’fmt’)
To show all employees hired on June 4, 1984m we can use the TO_DATE function
SQL> SELECT EMPNO , ENAME , HIREDATE
FROM EMP
WHERE HIREDATE = TO_DATE('JANUARY 12, 1983','MONTH DD,YYYY');
Miscellaneous Functions
DECODE
49
Palestine Engineering CO
ORACLE7 SQL
The decode function evaluate the expression (in this case DEPTNO). If it is equal to
10 then it is decoded to EXCELLENT, else if it is equal to 20 then it is decoded to
VERY GOOD. For all other values it is decoded to OK.
The decode is a very powerful function and it has many practical uses.
6 rows selected.
Note that SAL+COMM evaluates to NULL if COMM is NULL. This because A+B
is equal to NULL if either A or B or Both are NULL. The NVL(COMM,0) converts
any COMM whose value is NULL to 0.
50
Palestine Engineering CO
ORACLE7 SQL
WARD 4 22-FEB-81 7
MARTIN 6 28-SEP-81 7
ADAMS 5 12-JAN-83 7
JAMES 5 03-DEC-81 7
51
Palestine Engineering CO
ORACLE7 SQL
GROUP FUNCTION
Group functions operate on sets of rows. They return results based on groups of
rows, rather than one result per row as returned by single row functions.
By default all the rows in a table are treated as one group. The GROUP BY clause
of the SELECT statement is used to divide rows into smaller groups.
The group functions are listed below. All group functions except COUNT (*) ignore
null values.
All of the above functions operate on a number of rows (for example, a whole table )
and are therefore known as GROUP (or AGGREGATE) functions.
AVG(SAL)
---------
2073.2143
Note that the rows in the EMP table are treated as one group.
MIN(SAL)
---------
2450
COUNT(*)
---------------
3
The Group By clause, can be used to divide the rows in a table into smaller groups,
Group functions may be used to return summary information for each group.
52
Palestine Engineering CO
ORACLE7 SQL
JOB AVG(SAL)
--------- ---------
ANALYST 3000
CLERK 1037.5
MANAGER 2758.3333
PRESIDENT 5000
SALESMAN 1400
JOB AVG(SAL)
--------- ---------
MANAGER 2758.3333
SALESMAN 1400
We can also use the GROUP BY clause to provide result for groups within groups.
To display the average monthly salary bill for each . job type within a department
enter.
SQL> SELECT DEPTNO, JOB,AVG(SAL) FROM EMP
2 GROUP BY DEPTNO, JOB;
9 rows selected.
The following SQL Statement returns the maximum salary for each job group.
However, the result is not very meaningful because JOB is not displayed in the
result.
53
Palestine Engineering CO
ORACLE7 SQL
GROUP BY JOB;
MAX(SAL)
---------------
3000
1300
2975
5000
1600
It is optional to display JOB, However, the values displayed will have more meaning
if they are related to a job group
MAX(SAL) JOB
-------------- ---------
3000 ANALYST
1300 CLERK
2975 MANAGER
5000 PRESIDENT
1600 SALESMAN
NOTE: Group functions cannot be retrieved with individual items that are not
included in the GROUP BY clause.
For example:
The command in invalid because DEPTNO has a value for each row in the table,
while MIN(SAL) has a single value for the whole table.
DEPTNO MIN(SAL)
--------------- ---------
10 1300
20 800
30 950
Use the HAVING clause if you wish to specify which groups are to be displayed,
54
Palestine Engineering CO
ORACLE7 SQL
i.e. restrict the groups that you return.
To show the average salary for all departments employing more than three people,
enter.
DEPTNO AVG(SAL)
----------- -------------
20 2175
30 1566.6667
Note that the HAVING clause may precede the GROUP BY clause, but it is
recommended that GROUP BY is listed first because it is more logical to do so.
Groups are formed and group functions are calculated before the HAVING clause
is
applied to select groups for output.
The WHERE clause may still be used to exclude rows form consideration. The order
of the clauses is then:
SELECT column(s)
FROM table(s)
WHERE row condition(s)
GROUP BY column(s)
HAVING group of rows condition(s)
ORDER BY column(s)
55
Palestine Engineering CO
ORACLE7 SQL
Some of the general features possible in a SQL*Plus report are illustrated next:
SET Commands
EXAMPLES
SQL> SELECT ENAME, SAL FROM EMP WHERE SAL < 2000;
ENAME SAL
------------------------- ---------
SMITH 800
ALLEN 1600
WARD 1250
MARTIN 1250
TURNER 1500
ADAMS 1100
JAMES 950
MILLER 1300
8 rows selected. -- This line is the feedback line, when feedback is set
to off, it will no longer appear.
56
Palestine Engineering CO
ORACLE7 SQL
SQL> SELECT ENAME, SAL FROM EMP WHERE DEPTNO = 20;
SMITH 800
JONES 2975
SCOTT 3000
ADAMS 1100
FORD 3000
SET PAUSE ON
This is a useful command which makes SQL*Plus waits for you to press {Return]
before displaying a new page of output. One could also specify Text which SQL*Plus
should display before waiting
SQL>SET PAUSE ON
SQL> SET PAUSE 'PLEASE PRESS RETURN TO CONT'
SQL> SET HEADING ON
SQL> SELECT ENAME, SAL FROM EMP WHERE DEPTNO = 20;
PLEASE PRESS RETURN TO CONT -- SQL*Plus waits for you to press Enter
ENAME SAL
------------------------- ---------
SMITH 800
JONES 2975
SCOTT 3000
ADAMS 1100
FORD 3000
SET NUMWIDHT n
When SQL*Plus displays numeric data items, it uses a default width of 9 digits.
Some times this is too long for your data a consumes a lot of space. You can modify
this width using SET NUMWIDTH
57
Palestine Engineering CO
ORACLE7 SQL
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
SET LINESIZE n
Sets the number of characters that SQL*Plus will display on a line before the
beginning a new line. The default value is 80 and the Max value is 500.
SET NEWPAGE n
Sets the number of blank lines to be printed between the bottom title of each page and
the top title of the next page. The default is 1. A value of 0 makes SQL*Plus send a
form feed between pages. This clears the screen on most terminals.
SET PAGESIZE n
Sets the number of lines per page. The default is 24; properly fit for a screen page
and not A4 printer page. For reports printed on A4 paper, a value of 54 (Plus a
NEWPAGE value of 6) is ideal
SET TIMING ON
ENAME SAL
------------------------- ----
CLARK 2450
KING 5000
MILLER 1300
SET TIME ON
58
Palestine Engineering CO
ORACLE7 SQL
Not to be confused with SET TIMING. This command will give you the current time
with the SQL prompt
DNAME
--------------
ACCOUNTING
RESEARCH
SALES
OPERATIONS
real: 1540
08:34:09 SQL>
To Disable:
If you are using SQL*Plus under windows you can click on the Options Menu and
invoke the Set Options submenu. You can then set and reset all SET commands
graphically using the mouse.
SET SPACE n
This command sets the spaces between column headings when displayed on the
screen. The default is 1.
59
Palestine Engineering CO
ORACLE7 SQL
This set command allows you to change the underline character of the column header.
The default is underscore ‘-’
DEPTNODNAME LOC
====================================
10ACCOUNTING NEW YORK
20RESEARCH DALLAS
30SALES CHICAGO
40OPERATIONS BOSTON
12
There are more SET commands than the ones described in this training course
literature. However, the one mentioned here are the most important.
When you exit the SQL*Plus session all SETTING that you made in this session are
erased. When you log on again the default settings will prevail.
If you want to create environment of your own setting, you must create a file called
LOGIN.SQL in your current directory. Include the SET COMMAND you want in
this file. You would write the SET command is exactly the same way you would if
you were entering them interactively in an SQL*Plus session. SQL*Plus will read this
file every time a new SQL*Plus is session is invokes.
LOGIN.SQL
SET TIME ON
SET PAUSE ‘RETURN’
SET PAUSE ON
COLUMN Options
The COLUMN command let you control who a particular column will appear when
displayed on the SQL*Plus screen. It affects its picture, width and other options. It
does not affect how the column is stored in the database.
60
Palestine Engineering CO
ORACLE7 SQL
1. The column name must refer to a column alias if a column alias is used on the
SELECT clause.
The FORMAT option changed the picture of the DNAME column to A50 meaning
Alphanumeric of with 50 characters and
the HEADING option changed the heading of the column.
EMPNO SAL
========= ==========
7369 $800.00
7499 $1600.00
7521 $1250.00
7566 $2975.00
7654 $1250.00
7698 $2850.00
7782 $2450.00
7788 $3000.00
The Picture of SAL is changed to 4 numeric digits and 2 decimals preceded with $
61
Palestine Engineering CO
ORACLE7 SQL
Element Example(s) Description
------------------------------ ------------------------------------------------------
9 9999 Determines the display width by the number of
digits entered. Does not display leading zeroes.
There are many COLUMN options; only the important ones are going to be explained
here.
WRAP
TRUNC
Allows you to inform SQL*Plus that whenever the actual contents of a column
exceeds the width specified, that the additional information is WRAPped round onto
the next line or TRUNCated. WRAP is the default.
62
Palestine Engineering CO
ORACLE7 SQL
WORD_WRAPPED
Moves an entire word to the next line rather than split it between two lines
CLEAR
Removes the previous column formatting commands for that column
SQL> COLUMN SAL -- Will display the current format of SAL
column sal ON
format $99999.99
justify left
SQL> COLUMN SAL CLEAR
JUSTIFY
Your options are LEFT, CENTER and RIGHT. This options allows to specify
justification of the column heading. By default CHAR/DATE are displayed
JUSTIFY LEFT and NUMBER headings are JUSTIFY RIGHT. It is important to
stress the this options affects the HEADING rather than the actual column values
alignment
NULL string
Sets any NULL in the column to the specified string.
PRINT, NOPRINT
Causes the column to be displayed/not displayed on the output list
TEMP
specifies that the format for this column is applied for one SQL query only.
SQL> COLUMN DEPTNO NOPRINT TEMP
SQL> SELECT * FROM DEPT;
DNAME LOC
========== === =============
ACCOUNTING NEW YORK
RESEARCH DALLAS
SALES CHICAGO
OPERATIONS BOSTON
63
Palestine Engineering CO
ORACLE7 SQL
SQL> COLUMN REM FORMAT 999,999.99 HEADING TOTAL
SQL> SELECT DEPTNO,JOB,EMPNO,SAL*12+NVL(COMM,0) REM
2 FROM EMP WHERE DEPTNO=30;
EMP
DEPT. JOB NO TOTAL
===== ========= ===== ===========
030 SALESMAN 7499 19,500.00
030 SALESMAN 7521 15,500.00
030 SALESMAN 7654 16,400.00
030 MANAGER 7698 34,200.00
030 SALESMAN 7844 18,000.00
030 CLERK 7900 11,400.00
6 rows selected.
This query result displays characteristics of the COLUMN Formatting options. One
of the headings was split over two lines using one vertical bar (|). Notice that the JOB
header is right aligned while the JOB values are left aligned
EMP
DEPT. JOB NO TOTAL COMM
===== ========= ===== ======= =====
030 SALESMAN 7499 19,500.00 300
030 SALESMAN 7521 15,500.00 500
030 SALESMAN 7654 16,400.00 1400
030 MANAGER 7698 34,200.00 NO COMM
030 SALESMAN 7844 18,000.00 0
030 CLERK 7900 11,400.00 NO COMM
Notice that the NULL option has been used to force a character string to be displayed
where a null would normally appear.
SQL>TTITLE
SQL> BTITLE --displays the current TTITLE or BTITILE
EXAMPLE
64
Palestine Engineering CO
ORACLE7 SQL
EMP
DEPT. JOB NO TOTAL COMM
===== ========= ===== ======= =====
030 SALESMAN 7499 19,500.00 300
030 SALESMAN 7521 15,500.00 500
030 SALESMAN 7654 16,400.00 1400
030 MANAGER 7698 34,200.00 NO COMM
030 SALESMAN 7844 18,000.00 0
030 CLERK 7900 11,400.00 NO COMM
COMPANY CONFIDENTIAL
6 rows selected.
The TTITLE and BTITLE commands can include a number of clauses enabling the
appearance of the title to be specified in more detail.
TTITLE clause
Clause can be
SKIP n
Skips to the start of a new line n times. If n is omitted, skips one line; if n is 0,
backward to the start of the current line.
TAB n
Skips forward n print positions (back if n is negative)
SQL.PNO
The system variable for the current page number.
SQL.LNO
65
Palestine Engineering CO
ORACLE7 SQL
The system variable for the current Line n umber
SQL.USER
The system variable for the username
EXAMPLE
SQL> TTITLE LEFT 'PAGE : 'SQL.PNO RIGHT 'PRODUCED BY ACCOUNTING DEPT' SKIP 2 -
> CENTER 'CONFIDENTIAL SALES REPORT' SKIP 2 CENTER '----------------------------------'
SQL> BTITLE CENTER 'END OF REPORT' SKIP CENTER '-------------------------------'
SQL> SELECT ENAME, SAL FROM EMP
WHERE COMM IS NULL;
END OF REPORT
--------------------------
10 rows selected.
66
Palestine Engineering CO
ORACLE7 SQL
This file is like a batch file. It can contain SET commands, COLUMN, TTITLE,
BTITLE and STANDARD SELECT statement. It is a file that usually has SQL
extension (x.sql). It can be run from within SQL*Plus by using the START command
EXAMPLE
Create the following file using your editor and call test.sql:-
SQL>START test.sql
67
Palestine Engineering CO
ORACLE7 SQL
The rows of a report may be broken up into sections by using the BREAK command,
By BREAKing on a column, the display of duplicate values in the column is
suppressed. You may also leave blank lines or start a new page between section.
Since a break will occur each time the column value changes, you should remember
to ORDER BY the column in the SELECT statement or your report will be split into
meaningless sections.
There can only be one BREAK command active at any one time; therefore, if you
require multiple breaks they should all be specified as one BREAK command. You
should list the break columns in order of importance, i.e. major breaks first
Break Options
Breaks can be active on:
- Column
- Row
- Page
- Report
A BREAK on REPORT will allow final summary calculations. At any break, the
following options may be specified
Options Description
PAGE Throws a page when value in column
changes.
68
Palestine Engineering CO
ORACLE7 SQL
20 CLERK SMITH
CLERK ADAMS
ANALYST FORD
ANALYST SCOTT
MANAGER JONES
30 SALESMAN ALLEN
MANAGER BLAKE
SALESMAN MARTIN
CLERK JAMES
SALESMAN TURNER
SALESMAN WARD
14 rows selected.
Summary Calculation
where clause is
AVG, COUNT, MAX,MIN,NUMBER,STD,SUM,VAR
There may be many COMPUTE commands, although it is often easier to specify all
computes required in one command.
For example:
69
Palestine Engineering CO
ORACLE7 SQL
MANAGER JONES 2975
********* ---------
avg 2175
sum 10875
14 rows selected.
ADVANCED EXAMPLE
CONFIDENTIAL
1) Divide the SAL column into 3 separate departments using DECODE function
SQL> SELECT JOB,
2 DECODE (DEPTNO,10,SAL,0) D10,
3 DECODE (DEPTNO,20,SAL,0) D20,
4 DECODE (DEPTNO,30,SAL,0) D30
5 FROM EMP;
70
Palestine Engineering CO
ORACLE7 SQL
MANAGER 0 0 2850
MANAGER 2450 0 0
ANALYST 0 3000 0
PRESIDENT 5000 0 0
SALESMAN 0 0 1500
CLERK 0 1100 0
CLERK 0 0 950
ANALYST 0 3000 0
CLERK 1300 0 0
14 rows selected.
3- Add a dummy column in order to compute the total for each department,or
alternatively BREAK ON REPORT and compute at the break level
4- Finally format the report with COLUMN command and any other SQL*Plus commands required
71
Palestine Engineering CO
ORACLE7 SQL
SQL> COMPUTE SUM OF D10 D20 D30 TOTAL ON DUMMY
SQL> TTITLE 'COMPANY REPORT'
SQL> BTITLE 'CONFIDENTIAL'
SQL>SELECT JOB,
SUM(DECODE (DEPTNO,10,SAL,0)) D10,
SUM(DECODE (DEPTNO,20,SAL,0)) D20,
SUM(DECODE (DEPTNO,30,SAL,0)) D30,
SUM(SAL) TOTAL ,
SUM(0) DUMMY
FROM EMP
GROUP BY JOB;
CONFIDENTIAL
72
Palestine Engineering CO
ORACLE7 SQL
Table names can also be very tedious when typing in repeatedly. Temporary labels
( or aliases ) can be used in the FROM clause. These temporary names are valid
only
for the current select statement. Table aliases should also be specified in the
SELECT clause. This effectively `speeds` up the query, in that the statement
contains very specific information.
Equi -Join
73
Palestine Engineering CO
ORACLE7 SQL
SCOTT ANALYST RESEARCH 20
KING PRESIDENT ACCOUNTING 10
TURNER SALESMAN SALES 30
ADAMS CLERK RESEARCH 20
JAMES CLERK SALES 30
FORD ANALYST RESEARCH 20
MILLER CLERK ACCOUNTING 10
14 rows selected.
You will see that every employee now has his respective department name displayed.
Notice that join condition specifies table names prior to the column name. This is a
requirement when column names are the same in both tables. It is necessary to `tell`
ORACLE exactly which column you are referring to.
This requirement is also essential when referring to those columns which may be
ambiguous in a SELECT or ORDER BY clause. Anyhow it is a good practice to
to always specify table names prior to the column name.
Products
74
Palestine Engineering CO
ORACLE7 SQL
JAMES 950 30 SALES
JAMES 950 30 OPERATIONS
JAMES 950 30
25 rows selected.
Therefore in the absence of a WHERE condition, each row in EMP is linked in turn to
each row in DEPT.
Non-Equi-Join.
The relationship between the EMP and SALGRADE table is a non-equi-join, in that
no column in EMP corresponds directly to a column in SALGRADE. The
relationship
is obtained using an operator other than equal (=). To evaluate an employee’s grade,
his/her salary must be between any one of the low and high salary ranges.
Other operators such as <= and >= could be used, however between is the simplest.
Remember the low value first, high value last when using BETWEEN . Again table
aliases have been specified, not because of possible ambiguity, but for performance
reasons. In order to join together all three tables, it is necessary to construct two join
conditions. To join four tables a minimum of three joins would be required.
A simple rule is :
This rule may not apply if your table has a concatenated primary key that uniquely
identifies each row ( primary keys are covered later in the manual ).
Outer Joins
75
Palestine Engineering CO
ORACLE7 SQL
If a row does not satisfy a join condition, then the row will not appear in the query
result. In fact, in the equi-join condition of EMP and DEPT, department 40 does
not
appear. This is because three are no employees in department 40.
The row(s) can be returned if an outer join operator is used in the join condition .
The operator is a plus sign enclosed in parenthesis (+), and is placed in the `side`
of
the join (table) which is deficient is information . The operator has the effect one or
more NULL rows, to which one or more rows from the non-deficient table can be
joined. One NULL row is created for every additional row in the non-deficient
table.
16 rows selected.
It is possible using table labels (aliases) to join a table to itself, as if it were two
separate tables. This allows rows in a table to be joined to rows in the same table.
The following query displays all employees who earn less than their managers.
76
Palestine Engineering CO
ORACLE7 SQL
MARTIN 1250 BLAKE 2850
BLAKE 2850 KING 5000
CLARK 2450 KING 5000
TURNER 1500 BLAKE 2850
ADAMS 1100 SCOTT 3000
JAMES 950 BLAKE 2850
MILLER 1300 CLARK 2450
11 rows selected.
Please note that the FORM clause refers to EMP twice, and therefore EMP has been
given an alias in both cases - E and M. Assign meaning full table aliases, for
example
E means employees and M means managers (it does help!).
The join clause in English reads: “ where an employee’s manager number is the
same
as his manager’s employee number”.
Set Operators
UNION, INTERSECT and MINUS are useful in constructing queries that refer to
different tables. They combine the results of two or more select statements into one
result. A query may therefore consist of two or more SQL statements linked by
one
or more set operators. Set operators are often called Vertical Joins, because the
join is not according to rows between two tables, but columns.
In the following three examples, the queries are the same, but the operator is
different in each case yielding different query result.
UNION
JOB
---------
CLERK
MANAGER
PRESIDENT
SALESMAN
INTERSECT
INTERSECT
77
Palestine Engineering CO
ORACLE7 SQL
JOB
---------
CLERK
MANAGER
MINUS
To return all rows retrieved by first query that are not in the second, enter:
JOB
---------
PRESIDENT
It is possible to construct queries with many set operators. If multiple set operators
are used, the execution order for the SQL statements is from top to bottom.
Brackets may be used to produce an alternative execution order.
9. Multiple set operators are possible with parentheses if necessary to alter the
sequence of execution.
78
Palestine Engineering CO
ORACLE7 SQL
Subqueries
To find the employee who earns the minimum salary in the company ( minimum
salary is an unknown quantity ), two steps must be taken:
MIN(SAL)
---------
800
Nested Subqueries
For example:
79
Palestine Engineering CO
ORACLE7 SQL
A select statement can be considered as a query block. The example above consists
of two query blocks - the main query and the inner query .
The inner statement or query block is executed first, producing a query result: 800
The main query block is then processed and uses the value returned by the inner
query to complete its search condition. In essence . the main query would kindly
look like this:
In the above example, the 800 is a single value. The subquery that returned the
value of 800 is called a single row subquery. When a subquery. When a subquery
returns only one row, a single row comparison or logical operator should be used.
For example: = ,<,>,<=, etc.
To find all employees who have the same job as BLAKE we would enter:
ENAME JOB
------------------------- ---------
JONES MANAGER
BLAKE MANAGER
CLARK MANAGER
The following query attempts to find the employees who earn who lowest salary in
each department .
Notice that the inner query has a GROUP BY clause. This means that it may return
more than one value. We therefore need to use a mufti-row comparison operator. In
this case, the IN operator MUST be used because it expects a list of values.
The result obtained does not show the department in which the qualifying employees
work. In addition, because we are only comparing salary values, the inner query
could return a value simply because it matches the lowest salary for one of the
80
Palestine Engineering CO
ORACLE7 SQL
departments, not employee’s own department. Therefore, the query should be
rewritten in order to match the combination of employee’s salary and department
number with the minimum salary and department number.
Notice that the columns on the LEFT of the search condition are in parenthesis and
that each column is separated with a comma.
Columns listed in the SELECT clause of the subquery MUST be IN THE SAME
ORDER as the bracketed column list on the WHERE clause of the outer query.
Columns returned by the inner query must also match in number and dataype the
columns to which they are compared in the outer query .
When a subquery returns more than one row and a single row comparison operator is
used, SQL*PLUS issues the following error message:
SQL> SELECT ENAME,SAL,DEPTNO FROM EMP
WHERE SAL = (SELECT MIN(SAL) FROM EMP
GROUP BY DEPTNO);
ERROR:
ORA-01427: single-row subquery returns more than one row
no rows selected
no rows selected
The ANY or ALL operators may be used for subqueries that return more than one
row. They are used on the WHERE or HAVING clause in conjunction with the
logical operators (=.!=, <,>,>=,<=).
81
Palestine Engineering CO
ORACLE7 SQL
To display employees who earn more than the lowest salary in Department 30, enter:
12 rows selected.
The lowest salary in Department 30 is $950 (James`). The main query has returned
employees who earn a salary that is greater than the lowest (minimum) salary in
department 30. So ‘>ANY’ means more than the minimum. `= ANY` is equivalent
to
IN.
When using ANY, the DISTINCT keyword is frequently used to prevent rows being
selected several times.
The following query finds employees who earn more than every employee in Dept. 30
SQL> SELECT ENAME, SAL, JOB, DEPTNO FROM EMP
WHERE SAL> ALL (SELECT DISTINCT SAL
FROM EMP WHERE DEPTNO = 30)
The highest salary in Dept 30 is $2850(Blake’s), so the query has returned those
employees whose salary is higher than $2850. That is, greater than the highest(max.)
salary for Dept 30, and consequently more than every salary in that department.
82
Palestine Engineering CO
ORACLE7 SQL
Nested subqueries can also be used in the HAVING clause.
DEPTNO AVG(SAL)
--------- ---------
10 2916.6667
20 2175
To construct a query which finds the job with the highest average salary, enter :
JOB AVG(SAL)
---------------- ---------
PRESIDENT 5000
The inner query first finds the average salary for each different job group, and the
MAX function picks the highest average salary. That value (500) is used in the
HAVING clause. The GROUP BY clause in the main query is needed because the
main query’s SELECT list contains both an aggregate and non-aggregate column.
The RULE remains that you can have ONLY ONE ORDER BY clause for a select
statement and, if specified, it must be the last clause in the select command.
Nesting Subqueries
Display the name, sal for employees whose salary is greater than the
highest salary in any SALES department .
83
Palestine Engineering CO
ORACLE7 SQL
ENAME SAL
------------------------- ---------
JONES 2975
SCOTT 3000
KING 5000
FORD 3000
Guidelines
- The ORDER BY clause appears at the end of the main select statement.
- Multiple columns on the select list of the inner query must be in the
same
order as the columns appearing on the condition clause of the main query.
The dataType and number of columns listed must also correspond.
- Subqueries are always executed from the most deeply nested to the least
deeply nested, unless they are correlated subqueries, ( discussed later ).
- Logical and SQL operators may be used as well as ANY and ALL.
- Subqueries can :
- Join Tables
Correlated Subqueries
84
Palestine Engineering CO
ORACLE7 SQL
` candidate row` considered by the main query and which on execution uses a value
from a column in the outer query . This causes the correlated subquery to be
processed in a different way to the ordinary Nested Subquery.
A Correlated subquery is identified by the use of an outer query’s column in the inner
query’s predicate clause.
With a normal nested subquery, the inner select runs first and it executes once,
returning values to be used by the main query. A Correlated Subquery, on the other
hand, executes once for each row (candidate row) considered by the outer query . The
inner query is driven by the outer query.
3. Use value (s) resulting from inner query to qualify or disqualify candidate
To find employees who earn a salary greater than the average salary for their
department, enter :
6 rows selected.
Note that the alias is necessary only to avoid ambiguity in column names.
2. EMP in FROM clause has alias E which qualifies depth column referenced in
inner query’s WHERE clause.
85
Palestine Engineering CO
ORACLE7 SQL
8. Repeat from step 1 for next candidate row, ALLEN in department 30 earning
$ 1600.
The selection of candidate rows continues with those meeting the condition appearing
in the query result.
UPDATE EMP E
SET (SAL,COMM) = (SELECT AVG(SAL)*1.1 , AVG(COMM) FROM EMP
WHERE DEPTNO = E.DEPTNO),
HIREDATE = '11-JUN-81'
Operators
When you are nesting select statements the logical operators are all valid as well as
ANY and ALL. In addition the EXISTS operator may be used.
EXISTS Operator
The EXISTS operator is frequently used with Correlated Subqueries. It tests whether
a value is there ( NOT EXISTS ensures that something is not there ). If the value
exists it returns TRUE, if does not exist FALSE is flagged.
To find employees who have at least one person reporting to them, enter:
86
Palestine Engineering CO
ORACLE7 SQL
7788 SCOTT ANALYST
7839 KING PRESIDENT
7902 FORD ANALYST
6 rows selected.
The Correlated subquery is one way of ` reading` every row in the table, and
comparing values in each row against related data,. It is used whenever a subquery
must return a different result or set of result for each candidate row considered by
the
main query.
The inner select is normally executed once for each candidate row.
87
This document was created with Win2PDF available at http://www.daneprairie.com.
The unregistered version of Win2PDF is for evaluation or non-commercial use only.