You are on page 1of 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 Codd’s 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 to 
work 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
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.0
The Log On dialog box appears:

                                                                                        2
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
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
• Run the file with the Run command from the File Menu.

Save As The Saves As command saves the contents of the SQLPLUS buffer in a command 
file.

Spool The Spool command contains two subcommands: Spool File and Spool Off.

Spool File  stores query results in a file. By default, SQLPLUS assigns the .LST 
extension to spool files. You can specify a different extension in the File name text 
box. You can edit the results with the Editor command from the Edit menu and 
also print the file.
Spool Off turns off spooling.

Run The Run command lists and executes the SQL command block currently stored in 
the SQL buffer.

Cancel The Cancel command cancels an in­progress operation.

Exit The   Exit   command   commits   all   pending   database   changes   and   closes   the 
SQLPLUS application window.

Edit Menu

The Edit Menu contains the following commands:

Copy The Copy command copies the selected text to the Clipboard.

After you copy text to the Clipboard, you can paste the text into other Windows 
applications, such as MS Excel and MS Word.
Paste The   Paste   command   pastes   the   contents   of   the   Clipboard   onto   the   SQLPLUS 
command line.

Clear The Clear command clears the screen of the SQLPLUS application window and 
the screen buffer.

Editor The   Editor   command   contains   two   subcommands:  Invoke  Editor  and  Define 
Editor.

                                                                                        5
Invoke   Editor  loads   the   contents   of   the   SQLPLUS   buffer   into   an   editor.   By 
default, SQLPLUS saves the file to AFIEDT.BUF. You can specify a different file 
name in the editor.
Define Editor defines the editor that is invoked.

Search Menu

The Search Menu contains the following commands:

Find The Find command searches for a character, a word, or a group of characters or 
words   in   the   SQLPLUS   application   window.   When   you   choose   the   Find 
command, SQLPLUS begins the search at the top of the displayed screen.

Note:   When   SQLPLUS   reaches   the   end   of   the   displayed   screen,   it   will   not 
automatically continue searching from the top of the SQLPLUS screen buffer.

Find Next The Find Next command finds the next occurrence of the search text.

Getting Help

You can obtain help from within SQLPLUS be typing HELP <topic> at the SQL> prompt.

e.g. SQL> HELP INSERT; gives help on the INSERT statement


SQL> HELP; lists all SQL and SQLPLUS commands

                                                                                        6
Note that for the remaining sections of this document, we will not include the SQL> prompt in 
example code segments.   These segments will appear just as they should be typed. Also the 
code will not be shown in a window.

 3. RETRIEVAL FROM A SINGLE TABLE 

In  practice,  retrieval   may  well be  from   a number  of  Tables  at  one  time.     However,  in   any 
introduction to SQL, many concepts can be illustrated by retrieving data from one table at a 
time.   It might  be useful for the novice ORACLE user to type in the examples in order to 
become familiar with the system and also see how the Queries work.

 3.1 Selecting Complete Tables 

eg SELECT *
FROM EMP

Selects   ALL   columns   and   ALL   rows   from   the   EMP   table.     The   asterisk   is   responsible   for 
selecting all the columns.

 3.2 Selecting Complete Rows 

e.g. SELECT *  SELECTS ALL columns from those rows of the


FROM EMP EMP table for which the value of the ENAME
WHERE ENAME = ‘SMITH’; column is ‘SMITH’.

The WHERE  clause is responsible for selecting particular rows of the table or tables.   The 


format of the WHERE clause is WHERE <condition> and those rows that are such that the 
condition is TRUE are chosen as the result of the SQL SELECT statement.

The <condition> can be complex, using combinations of various Boolean operators.  A full list 
of operators and their precedence is given in the ORACLE SQLPLUS Users’ Guide.

e.g. SELECT * selects ALL columns from those rows of the EMP


FROM EMP table for which the value of the SAL column is
WHERE SAL> 1300 greater than 1300 and the value of
AND DEPTNO = 30; DEPTNO is equal to 30.

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


FROM EMP is not MANAGER

                                                                                        7
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
<= less than or equal to
BETWEEN...AND... between two values
IN (list) any of a list of values
LIKE match a character pattern
IS NULL is a null value

To negate the last four operators, use the operator NOT: 
i.e. NOT BETWEEN, NOT IN, NOT LIKE and IS NOT NULL.

Combination Operators

Conditions formed from the above operators can be combined using the operators AND, OR 
and NOT.   AND will normally take precedence over OR but any special precedence can be 
achieved through judicious use of brackets ().

Examples

                                                                                        8
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 FALSE 


otherwise

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 BETWEEN 1200 AND 1400;

SELECT * This is equivalent to WHERE SAL < 1200
FROM EMP    OR 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
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
required, then an ORDER phrase must be added to the query.  The ORDER appears after any 
WHERE phrase.

e.g. SELECT *
FROM EMP
ORDER 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
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 JOB
FROM 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 SALARY
FROM EMP;

                                                                                        12
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 defined 
order 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
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 > 1000
AND 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 is 
because 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 this 
example.   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
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, ENAME
FROM 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, ENAME
FROM 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 the 
standard 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
999.99 56.478 56.48 Rounds to 2 decimal places
999v99 56.478 5648 Decimal point not displayed
9,999 8410 8,410 Comma separates thousands
9,999 39 639 No comma if no thousands
99999 07 607 Leading zeros normally absent
09999 07 00607 Leading zeros fill format
9999 ­5609 ­5609 Minus sign normally precedes
9999MI ­5609 5609­ Minus sign follows number
9999PR ­5609 <5609> Negative numbers parenthesised
B999 0 Zero values displayed as blanks
B999 564 564 No effect if value not zero
99.99 124.98 ##.## Value too large for format
$99.99 45.23 $45.23 Dollar sign displayed
$99.99PR ­45.23 <$45.23> Formats may be combined

Note that COLUMN is an SQLPLUS command.  The default value of a column can be retrieved 
after a different definition by using  COLUMN <column name> CLEAR.

 5.1.2 Arithmetic Expressions 

Arithmetic expressions involving number column names, number values and the Arithmetic 
Operators (+, ­, *, /) are allowed.

To display the result of an arithmetic expression, simply include it in a SELECT command as if 
it were an ordinary column.   The column will be given a name identical to the expression 
unless given another.

e.g. SELECT ENAME, SAL, COMM, SAL+COMM
FROM EMP
WHERE JOB=‘SALESMAN’

produces:

ENAME SAL COMM SAL+COMM


ALLEN $1,600 300 1900
WARD $1,250 500 1750
MARTIN $1,250 1400 2650
TURNER $1,500 0 1500

Note that although SAL+COMM is not a column in the EMP table, it is displayed as if it were.

                                                                                        16
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 BALANCE
GREATEST 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
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
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
e.g. SELECT JOB, AVG(SAL)
FROM EMP
GROUP BY JOB;

Note that the EMP table is split into groups by JOB and the AVG is applied to each JOB group.

e.g. SELECT DEPTNO, 12*AVG(SAL)
FROM EMP
WHERE JOB NOT IN (‘MANAGER’, ’PRESIDENT’)
GROUP BY DEPTNO;

Finds the average Annual salary of the non­managerial staff in each department.

e.g. SELECT DEPTNO, JOB, COUNT(*), 12*AVG(SAL)
FROM EMP
GROUP BY DEPTNO, JOB;

In this case, the groups are for each job within each department.   The number of employees 
and the average group salary for each job within each department are found.

 5.1.5.1 The HAVING clause 

Having split a table up into a number of groups of interest, sometimes we might only want to 
look at some of these groups.   The selection of these groups can be achieved by using the 
HAVING phrase.
e.g. SELECT JOB, COUNT(*), 12*AVG(SAL)
FROM EMP
GROUP BY JOB
HAVING COUNT(*) >2;

This query finds the number of employees and the Annual average salary for all JOB groups 
with more than two employees.

You can have a WHERE clause and a HAVING clause in the same query in which case the 
order of operations is:
1.  the WHERE clause is applied to select rows

2.  the groups are formed and calculations made

3.  the HAVING clause is applied to select the groups

                                                                                        20
e.g. SELECT DEPTNO
FROM EMP
WHERE JOB = ‘CLERK’
GROUP BY DEPTNO
HAVING 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 <column name> 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
FROM DEPT;

This results in:

DEPARTMENTS
  ACCOUNTING ­ 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 fred’s, you must use ‘fred’’s’.

 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 employee’s 


name in characters

LOWER LOWER(ENAME) Converts an employee’s 


name to lowercase

                                                                                        22
SOUNDEX SOUNDEX(‘DES MOINES’) Returns a value that 
represents the spoken 
sound of ‘Des Moines”

SUBSTR SUBSTR(GRADE,2,1) Two characters of GRADE 


from the first character

UPPER UPPER(ENAME) Translates lowercase 


letters in ENAME to 
capital letters

e.g. SELECT ENAME, JOB
DECODE(JOB,’CLERK’,1,’MANAGER’,3,’PRESIDENT’,5,2)JOB_CLASS
FROM EMP;

Displays  ENAME and JOB and a new column  JOB_CLASS.   The  value of  the JOB_CLASS 


column   depends   upon   the   value   of   the   JOB   column.     If   the   JOB   value   is   ‘CLERK’   then 
JOB_CLASS   has   the   value   1,   if   JOB   is   ‘MANAGER’   then   JOB_CLASS   is   3,   if   JOB   is 
‘PRESIDENT’ then JOB_CLASS is 5, else JOB_CLASS is 2.

Note that DECODE can return a value of any type.  e.g., it would have been possible to return a 
date or a decimal number if the JOB was ‘CLERK’ etc.

  e.g. SELECT INITCAP(ENAME) NAME, JOB
FROM EMP
WHERE UPPER(ENAME) = ‘WARD’;

The UPPER(ENAME) converts all the characters of the ENAME field to uppercase ready for 
comparing with ‘WARD’.  This means that options such as ‘Ward’, ‘waRd’, ‘ward’ etc. will all 
match.  Then, for display purposes, the INITCAP(ENAME) function capitalises the first letter 
of ENAME and converts all other letters to lowercase.

e.g. SELECT ENAME
FROM EMP
WHERE SOUNDEX(ENAME) = SOUNDEX(‘SMYTH’);

Selects employees with names sounding like SMYTH.

e.g. SELECT ‘EMPLOYEE’ ENAME
FROM EMP;

                                                                                        23
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.YYYY
MONTH 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
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
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 TODAY
FROM 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
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­86
ADAMS 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
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   for 
DAYS_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 on 
the 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’) )
RAISEDATE
FROM 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
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   get 
commission.  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 EMP
WHERE 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
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
 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 for 
employees in Dept 30.

                                                                                        31
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 
President’s 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 ( =, <>, >, >=, <, <=).

Using IN and NOT IN

There   are   options   IN,   which   is   equivalent   to  =ANY  and   NOT   IN,   which   is   equivalent   to 
<>ALL.

e.g. SELECT ENAME, JOB
FROM EMP
WHERE DEPTNO = 10
AND JOB IN
(SELECT JOB
   FROM EMP
   WHERE DEPTNO = 30);

This lists the names and jobs of anybody in DEPT 10 who has the same job as anybody in 
DEPT 30.
e.g. SELECT ENAME, JOB
FROM EMP
WHERE DEPTNO = 10
AND JOB NOT IN

                                                                                        32
(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, SAL
FROM 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 EMP
   WHERE ENAME = ‘FORD’)
ORDER BY JOB, SAL;

This lists employees with either the same job as Jones or a salary greater than or equal to Ford’s 
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
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, SAL
FROM 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
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 is 
ordered 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 is 
possible 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
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
 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
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. The 
number 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 for 
a table.

                                                                                        38
You   may   sometimes wish  to forbid the possibility  of  an  attribute  of  a table  having  NULL 
values (e.g. if it is a KEY column: this can be achieved by the use of the option NOT NULL 
which has been illustrated in the previous example. Any attempt to put a NULL value into a 
column which has been assigned the NOT NULL property will result in a SQLPLUS error 
message.

Dropping Tables

As well as creating new tables you may wish to get rid of old ones. This can be achieved by 
using the DROP TABLE statement. The general form of this is:­

DROP TABLE <table­name>;

e.g.  DROP TABLE EMP;

Renaming Tables

Another useful facility is the ability to change the names of existing tables. This is done by the 
RENAME statement. The general form of this is:­

RENAME <old name>
TO <new name>;

e.g.  RENAME EMP
TO EMPLOYEES;
 8. INSERTION, UPDATING and DELETION 

This chapter deals with the adding, changing and removing of values with respect to a table. It 
also considers problems of integrity.

 8.1 INSERT 

The format of the INSERT statement is:­

INSERT INTO table­name

                                                                                        39
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
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
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 EMP
SET 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.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
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
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 can 
be 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
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 EMP10
WHERE 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
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
e.g. CREATE VIEW PAY (NAME, MONTHLY, SAL, ANNUAL_SAL, DEPTNO)
AS SELECT ENAME, SAL, SAL*12, DEPTNO
FROM EMP;

....... creates a view called PAY with columns that are explicitly named in brackets.

In order to see how the view appears try a query on it:­

e.g. SELECT *
FROM PAY
WHERE DEPTNO = 30;

 10.6 Group functions in views 

It is possible to define a view with a GROUP BY function in the defining query.

e.g. CREATE VIEW DEPT_COMP (DEPTNO, LOSAL, MEDSAL, HISAL, 
TOTSAL)
AS SELECT DEPTNO, MIN(SAL), AVG(SAL), MAX(SAL), 
SUM(SAL)
FROM EMP
GROUP BY DEPTNO;

If we wish to look at this view then the query:­

e.g. SELECT DEPTNO, LOSAL, HISAL, TOTSAL
FROM DEPT_COMP;

....... gives the result:

DEPTNO    LOSAL     HISAL    TOTSAL

10 800 5000 9550


20 920 3910 19420
30 950 2850 12050

                                                                                        48
 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
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
 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 <column name> HEADING <column heading>

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

Example:
COLUMN ENAME HEADING ‘Employee| Name’;

You can change the displayed width of a column by:

COLUMN <column name> FORMAT <format>

The <format> is defined so that 'A' is used for character columns and '9' is used for numeric 
columns.

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 <column name> NOPRINT

                                                                                        51
 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 <column name> *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 <column name> ON <break column>

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
 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
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 SQL 
statement 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
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      DEPTNO

7369  SMITH  CLERK  7902  17­DEC­80     800.00       20 


7499  ALLEN  SALESMAN  7698  20­FEB­81  1,600.00     300.00  30 
7521  WARD  SALESMAN  7698  22­FEB­81  1,250.00     500.00  30 
7566  JONES  MANAGER  7839  02­APR­81  2,975.00    20 
7654  MARTIN  SALESMAN  7698  28­SEP­81  1,250.00  1,400.00  30 
7698  BLAKE  MANAGER  7839  01­MAY­81  2,850.00    30 
7782  CLARK  MANAGER  7839  09­JUN­81  2,450.00    10 
7788  SCOTT  ANALYST  7566  09­DEC­82  3,000.00    20 
7839  KING  PRESIDENT    17­NOV­81  5,000.00    10 
7844  TURNER  SALESMAN  7698  08­SEP­81  1,500.00         0.00 30 
7876  ADAMS  CLERK  7788  12­JAN­83  1,100.00  20 
7900  JAMES  CLERK  7698  03­DEC­81     950.00  30 
7902  FORD  ANALYST  7566  03­DEC­81  3,000.00  20 
7934 MILLER CLERK 7782 23­JAN­82 1,300.00 10

DEPT SALGRADE 
DEPTNO    DNAME                    LOC GRADE     LOSAL       HISAL

10  ACCOUNTING  NEW YORK  1    700  1200 


20  RESEARCH  DALLAS  2  1201  1400 
30  SALES  CHICAGO  3  1401  2000 
40 OPERATIONS BOSTON 4  2001  3000 
5 3001 9999

                                                                                        55

You might also like