0% found this document useful (0 votes)
19 views

Oracle-SQL 19c 2020

This document serves as an introduction to using SQL with the Oracle database management system, specifically Oracle 19c. It includes instructions, sample relational database structures, and various SQL commands, supplemented by a lecture course. The document is designed for students to take notes and practice SQL commands as they learn about relational databases.

Uploaded by

Isuru Amarasena
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Oracle-SQL 19c 2020

This document serves as an introduction to using SQL with the Oracle database management system, specifically Oracle 19c. It includes instructions, sample relational database structures, and various SQL commands, supplemented by a lecture course. The document is designed for students to take notes and practice SQL commands as they learn about relational databases.

Uploaded by

Isuru Amarasena
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

Introduction to

Oracle
and
SQL
UNIVERSITY OF WOLVERHAMPTON

Faculty of Science and Engineering (FSE)

Introduction to Oracle and SQL

 Oracle 19c Version 19.0.0.0.0

The purpose of this hand-out is to introduce the reader to using SQL from the Oracle
database management system (DBMS). It is intended to be supplemented by a lecture
course. Spaces are provided throughout the document for the student to add notes and
answers to questions.

Commands to try out are in BOLD UPPERCASE

e.g., SELECT * FROM DEPT

Note, you will need to press RETURN after each line.

Problems to be tackled are indicated by a  in the margin. The output for these queries is
shown, so you can check if you have got the right answer. Note, the order of the output
may vary.

Hints, or things to watch out for, are indicated by either the  or  symbol. Things not to
do, or be careful with, are represented by a . A  probably needs no explanation!

Menu options that involve more than one step will be shown as a sequence, separated by
the greater than symbol (>), for example:

File>Open

Means select File from the main Window menu then Open from the submenu.

NOTE, this document is not meant to be completed in one session!

Version 3.1
Mary Garvey
October 2020
Note, some pages have been left intentionally blank – the document is designed to be
printed double sided!
Table of Contents

1 INTRODUCTION........................................................................................................................... 1
2 THE SAMPLE RELATIONAL DATABASE .............................................................................. 1
3 INTRODUCTION TO ORACLE .................................................................................................. 3
3.1 USING SQL*PLUS VIA ORACLE DEVELOPER ............................................................................ 3
3.2 ORACLE WIKI ............................................................................................................................... 3
3.3 REGISTERING FOR AN ACCOUNT ................................................................................................. 4
3.4 ACCESSING ORACLE..................................................................................................................... 4
3.5 APPS ANYWHERE .......................................................................................................................... 5
3.6 STARTING THE WINDOWS CLIENT SOFTWARE .......................................................................... 5
3.7 EASY CONNECT STRING ............................................................................................................... 7
3.8 FIRST TIME USERS........................................................................................................................ 8
3.9 THE SQL*PLUS COMMAND LINE......................................................................................... 8
3.10 COPYING THE SAMPLE DATABASE ................................................................................. 8
3.10.1 FROM WINDOWS  .................................................................................................................. 8
3.10.2 FROM LINUX ............................................................................................................................. 9
3.11 LISTING YOUR DATABASES........................................................................................................ 9
3.12 GETTING INFORMATION ABOUT THE ATTRIBUTES OF A TABLE ............................................. 9
4 SQL OVERVIEW ........................................................................................................................... 9
4.1 INTRODUCTION ............................................................................................................................. 9
4.2 ENVIRONMENT SETTINGS .......................................................................................................... 11
4.3 EDITING COMMANDS.................................................................................................................. 12
4.4 GETTING INFORMATION FROM A TABLE ................................................................................. 12
4.4.1 RESTRICTING COLUMNS............................................................................................................ 13
4.4.2 RESTRICTING ROWS .................................................................................................................. 13
5 QUITTING ORACLE .................................................................................................................. 14
5.1 RESTARTING ORACLE ................................................................................................................ 14
6 GETTING HELP .......................................................................................................................... 14
7 SUMMARY SO FAR .................................................................................................................... 15
8 STORING QUERY OUTPUT ..................................................................................................... 19
9 SAVING AND RETRIEVING QUERIES.................................................................................. 19
9.1 SAVING A QUERY ......................................................................................................................... 19
9.2 RETRIEVING AND EXECUTING A QUERY .................................................................................... 20
9.3 LOGIN.SQL................................................................................................................................... 21
10 SELECTION CONDITIONS..................................................................................................... 25
10.1 INTRODUCTION ......................................................................................................................... 25
10.2 COMPARISON OPERATORS....................................................................................................... 25
10.3 THE LIKE OPERATOR .............................................................................................................. 26
10.4 SOME EXAMPLE QUERIES ........................................................................................................ 26
10.5 PREVENTING THE SELECTION OF DUPLICATE ROWS ............................................ 28
11 CONTROLLING THE ORDER IN WHICH ROWS ARE DISPLAYED............................ 29
11.1 THE ORDER BY CLAUSE ........................................................................................................ 29
11.2 ORDERING WITH NULL VALUES ............................................................................................... 29
12 MANIPULATING DATA .......................................................................................................... 30
12.1 COMMITTING THE CHANGES ................................................................................................... 30
12.2 INSERTING ROWS...................................................................................................................... 31
12.3 INSERTING ROWS WITH NULL VALUES .................................................................................... 31
12.4 DELETING RECORDS ................................................................................................................ 32
12.5 UPDATING ROWS ...................................................................................................................... 33
13 DATA DEFINITION COMMANDS ......................................................................................... 33
13.1 CREATING A TABLE .................................................................................................................. 33
13.2 COMPOSITE PRIMARY AND FOREIGN KEYS ........................................................................... 35
13.3 CREATING A SEQUENCE FOR A TABLE'S PRIMARY KEY. ...................................................... 36
13.4 CREATING A TABLE WITH AN AS CLAUSE ............................................................................... 36
13.5 COPYING ROWS FROM ONE TABLE TO ANOTHER ................................................................... 37
13.6 MULTIPLE INSERTS .................................................................................................................. 37
13.7 DELETING A TABLE .................................................................................................................. 37
13.8 MAKING CHANGES TO COLUMNS ............................................................................................ 38
13.8.1 ALTERING COLUMNS .............................................................................................................. 38
13.8.2 ADDING A COLUMN ................................................................................................................ 38
13.8.3 DELETING A COLUMN ............................................................................................................. 39
13.9 VIOLATING SCHEMA DEFINITION ........................................................................................... 39
14 JOINING TABLES ..................................................................................................................... 39
14.1 INTRODUCTION ......................................................................................................................... 39
14.2 BASIC SQL STRUCTURE FOR JOINING TABLES ..................................................................... 40
14.3 JOIN OPERATORS...................................................................................................................... 40
14.4 SOME EXAMPLE JOIN QUERIES ............................................................................................... 40
14.5 RECURSIVE QUERIES ................................................................................................................ 42
14.6 OUTER JOINS............................................................................................................................. 43
15 ARITHMETIC EXPRESSIONS AND GROUP FUNCTIONS .............................................. 44
15.1 ARITHMETIC OPERATORS........................................................................................................ 44
15.2 SOME EXAMPLE QUERIES INVOLVING ARITHMETIC EXPRESSIONS .................................... 44
15.3 ARITHMETIC FUNCTIONS ......................................................................................................... 44
15.4 GROUP FUNCTIONS ................................................................................................................... 45
15.5 SOME EXAMPLE QUERIES INVOLVING GROUP FUNCTIONS .................................................. 45
15.6 SUBQUERIES .............................................................................................................................. 46
15.7 A GROUP FUNCTION IN A SUBQUERY ...................................................................................... 46
15.8 SUMMARISING SEVERAL GROUPS - GROUP BY ................................................................... 47
15.9 SOME EXAMPLE QUERIES USING GROUP BY....................................................................... 47
16 DISPLAYING AND WORKING WITH DATE VALUES ..................................................... 48
16.1 DATE ARITHMETIC ................................................................................................................... 48
16.2 DATE FUNCTIONS ..................................................................................................................... 48
16.3 SOME EXAMPLE QUERIES INVOLVING DATE FUNCTIONS ..................................................... 49
16.4 INSERTING DATE VALUES ........................................................................................................ 50
16.5 THE CURRENT DATE ................................................................................................................ 51
17 WORKING WITH CHARACTER VALUES .......................................................................... 51
17.1 CHARACTER EXPRESSIONS ...................................................................................................... 51
17.2 CHARACTER FUNCTIONS ......................................................................................................... 52
18 CONTROL COMMANDS ......................................................................................................... 54
18.1 FORMATTING REPORTS ........................................................................................................... 54
18.2 SOME BASIC REPORT FORMATTING COMMANDS .................................................................... 54
18.2.1 CHANGING COLUMN HEADINGS ............................................................................................. 55
18.2.2 CHANGING COLUMN WIDTH ................................................................................................... 55
18.2.3 FORMATTING NUMBER COLUMNS .......................................................................................... 56
18.3 ORGANISING ROWS INTO GROUPS: THE BREAK COMMAND ................................................ 57
18.4 SOME USEFUL BREAK FORMATS ............................................................................................ 57
18.5 SOME USEFUL ACTIONS AT BREAK ........................................................................................ 58
18.6 COMPUTING SUBTOTALS AT BREAKS ...................................................................................... 58
18.7 PAGE SIZE COMMANDS ............................................................................................................. 58
19 SUBSTITUTION VARIABLES ................................................................................................ 59
19.1 USING PARAMETERS WITH THE START COMMAND ............................................................. 60
20 VIEWS IN ORACLE .................................................................................................................. 61
20.1 CREATING A VIEW .................................................................................................................... 61
20.2 DELETING A VIEW ..................................................................................................................... 62
21 INDEXING TABLES IN ORACLE .......................................................................................... 62
21.1 CREATING AN INDEX................................................................................................................. 62
21.2 USING AN INDEX TO ENFORCE UNIQUENESS ........................................................................... 62
21.3 DELETING AN INDEX ................................................................................................................. 62
21.4 GENERAL RULES FOR INDEXES ................................................................................................ 62
22 DATA DICTIONARY ................................................................................................................ 63
22.1 THE DATA DICTIONARY TABLE ............................................................................................... 63
22.2 USEFUL DICTIONARY TABLES .................................................................................................. 63
23 ADVANCED SQL FEATURES: PL/SQL AND SQL/2 .......................................................... 68
23.1 INTRODUCTION TO PL/SQL..................................................................................................... 68
23.2 AN INTRODUCTION TO DATABASE TRIGGERS ........................................................................ 68
23.3 AN INTRODUCTION TO DATABASE PROCEDURES ................................................................... 70
APPENDICES ..................................................................................................................................... 74
APPENDIX A ORACLE SETUP CODE ................................................................................................ 74
APPENDIX B ER DIAGRAM .............................................................................................................. 77
APPENDIX C USING ORACLE FROM HOME ..................................................................................... 78
APPENDIX D APPENDIX D USEFUL SQL WEBSITES ....................................................................... 78
APPENDIX E INSTALLING THE PALO ALTO VPN CLIENT ............................................................. 79
HOW TO INSTALL THE CLIENT ............................................................................................................... 79
HOW TO USE THE CLIENT ...................................................................................................................... 81
CHECKING THE CLIENT STATUS ............................................................................................................ 81
RE-AUTHENTICATING ............................................................................................................................ 82
Table of Figures

Figure 3-1 Oracle Programs ........................................................................................... 6

Figure 3-2 Logging into Oracle ....................................................................................... 6

Figure 3-3 Oracle SQL*Plus – Initial Screen ..................................................................... 7

Figure 4-1 Output Results .............................................................................................11

Figure A-1 ER Diagram ................................................................................................. 77


Getting Started
1 INTRODUCTION

The purpose of this module is to teach you about databases, in particular databases based
on the relational model. The relational model is widely used in industry and many vendors
provide relational products. Oracle, Microsoft Access and Visual FoxPro are three such
products. SQL (Structure Query Language) is regarded as being the de facto query language
for relational databases and this module uses Oracle as a vehicle for teaching SQL.

SQL is subject to a number of standards: ANSI X3.135 - 1989; SQL2 (or SQL92) and SQL3
(SQL99) and recently SQL4 (2003). The current version of Oracle (version 10g) supports
most of the SQL92 standard. It does also offer some support for objects, which is in the
SQL99 standard.

 Oracle can be run in different environments, from a PC running Windows software in


client/server mode or directly on the mi-linux server running Linux (another
operating system). Some of the commands are applicable only to the PC and are
indicated by a Window icon .

As you get more familiar with the product, you will come to realise that a lot of the
commands detailed in this booklet could have been more easily entered/executed using the
power tools. The purpose of the module is to teach you SQL which is standard across many
relational products, e.g., Sysbase, Ingres, DB2. The Oracle Developer tools however are
proprietary and every product has different tools. The commands in this booklet however
can be executed on most relational platforms with little amendment; this would not be true
if the toolset were used.

2 THE SAMPLE RELATIONAL DATABASE

A relational database is a named collection of tables and other associated database objects
(e.g., indexes, screens, menus, etc.). Typically a database management system (DBMS) can
support more than one database simultaneously (or in ANSI-1989 terms, more than one
environment). This allows the user to organise their tables into different databases if
required. For example, you could have a different database for each module.

The following tables are used for illustrative purposes throughout the handout:

EMP(EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)


DEPT(DEPTNO, DNAME, LOC)
SALGRADE(GRADE, LOSAL, HISAL)
CUSTOMER(CNO, ORDERDATE, NAME, CITY, COUNTRY, PNO,
DESCRIPTION, QTY)

Where:

 EMP contains information about the employees of a sample company


 DEPT contains information about the departments in the company
 SALGRADE groups salary ranges into grades
 CUSTOMER details information about the company's customers

Introduction to Oracle and SQL Page – 1


Sample data:
TABLE: DEPT
Attribute Names  DEPTNO DNAME LOC

Tuples/Rows  10 ACCOUNTING NEW YORK


 20 RESEARCH DALLAS
 30 SALES CHICAGO
 40 OPERATIONS BOSTON
TABLE: EMP (HIRE DATE VALUES MAY BE DIFFERENT!)
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7876 ADAMS CLERK 7788 12-JUN-2000 1100 20
7499 ALLEN SALESMAN 7698 20-FEB-1995 1600 300 30
7698 BLAKE MANAGER 7839 01-MAY-1981 2850 30
7782 CLARK MANAGER 7839 09-JUN-1989 2450 10
7902 FORD ANALYST 7566 03-DEC-1991 3000 20
7900 JAMES CLERK 7698 03-DEC-1981 950 30
7566 JONES MANAGER 7839 02-APR-1991 2975 20
7839 KING PRESIDENT 17-NOV-1980 5000 10
7654 MARTIN SALESMAN 7698 28-SEP-1993 1250 1400 30
7934 MILLER CLERK 7782 23-JAN-1985 1300 10
7788 SCOTT ANALYST 7566 09-MAY-2000 3000 20
7369 SMITH CLERK 7902 17-DEC-1990 800 20
7844 TURNER SALESMAN 7698 08-SEP-1981 1500 0 30
7521 WARD SALESMAN 7698 22-FEB-1994 1250 500 30
TABLE: SALGRADE
GRADE LOSAL HISAL
1 700 1200
2 1201 1400
3 1401 2000
4 2001 3000
5 3001 9999
TABLE: CUSTOMER
CNO ORDER NAME CITY COUNTRY PNO DESCRIPTION QTY
DATE
1 01-JAN-1997 J BOND STOCKPORT ENGLAND 1 BONNET 20
1 11-JUN-1997 J BOND STOCKPORT ENGLAND 2 WIDGET 10
1 21-APR-1998 J BOND STOCKPORT ENGLAND 1 BONNET 40
1 15-AUG-1998 J BOND STOCKPORT ENGLAND 3 PAINT: WHITE 4
2 22-APR-1996 B TURPIN MANCHESTER ENGLAND 2 WIDGETS 41
2 11-JUN-1997 B TURPIN MANCHESTER ENGLAND 1 BONNET 1
3 06-FEB-1996 I PERRY WOLVERHAMPTON ENGLAND 5 NAILS 60
3 17-NOV-1997 I PARRY WOLVERHAMPTON ENGLAND 3 PAINT: WHITE 2
4 14-JUL-1997 P FOLWER BIRMINGHAM ENGLAND 6 HAMMER 1
4 30-MAY-1998 P FOLWER BIRMIGNAM ENGLAND 7 PAINT: BLUE 2
4 28-AUG-1998 P FOLWER BIRMINGHAM UNITED 11 WIDGET 40
KINGDOM

Introduction to Oracle and SQL Page – 2


A table is a two-dimensional, fixed length structure that holds information about something
you wish to store data about, e.g., employees or customers. Each table will contain a
number of records (also called rows or tuples), e.g., each employee will be represented as a
single record in the EMP table and each record will contain a number of fields (also called
columns or attributes), e.g., DEPT has the fields DEPTNO, DNAME and LOC. The relational
model can be described in more formal terms, but for the moment let's keep things simple!

More specific constraints have been added to each table, constraints are a way of
enforcing integrity rules on the data and include:

 The department name for the DEPT table (DNAME) must be entered
The manager number attribute (MGR) refers to another employee’s number. You can see
from the sample data that employee 7566 (JONES) is managed by employee 7839 (KING).

 An employee's salary must be entered and be greater than 0


 An employee's commission may or may not be entered, but if it is must be greater
than or equal to 0.
 An employee's department may or may not be entered, but if it is it must also exist
in the department table DEPT.
 The low point of a salary grade (LOSAL) must be greater than 0
 The high point of a salary grade (HISAL) must be greater than or equal to the low
point.
 All of this has been specified with NO traditional 3rd generation language
programming. The database management system (DBMS) will enforce these
constraints at all times.

3 INTRODUCTION TO ORACLE

3.1 Using SQL*PLUS via Oracle Developer

The DBMS software used in several database modules is known as Oracle and is supplied by
the Oracle Corporation. Oracle is a fully featured multi-user database designed for large-
scale applications. The main feature of Oracle that you will use is the SQL interface known
as SQL*Plus.

You will use Oracle mainly in client-server mode. That means that you will use a Windows
client program to communicate with Oracle that is situated on a Linux server. The database
and the database management system are stored on machine called oradb-srv, the
program which you will use to talk to it is located on the University's Windows labs.

The advantage of this arrangement is that it will allow you to use familiar Windows
commands to enter and edit your SQL commands. The client software is available in all the
MI Labs, or in the Learning Centre labs that have the computing image. Alternatively, it is
possible to use SQL*Plus from the student Linux server (csl-student.wlv.ac.uk) using a
secure shell (SSH) program and the Linux command line interface.

3.2 Oracle Wiki

The information found in this work book, can also be found online:
https://mi-linux.wlv.ac.uk/wiki/index.php/Oracle_Workbook

Introduction to Oracle and SQL Page – 3


3.3 Registering for an account

Before you can start using Oracle you need to register for an account.

The registration program can be found here:


https://mi-linux.wlv.ac.uk/~oracle/reg/orareg.php

Login with your University username and password. You will be presented with a list of
modules to pick from. Ensure you pick the correct module; otherwise you may not get
access to all the resources required for your module.

Your username/password will appear on the screen and will be emailed to you if you have a
University account.

 should you forget your password details (or lock your account because you have
forgotten your password), then re-run the program as above. It will reset your
password back to the original one. Please note, we cannot recover your password if
you have changed it.

Please note: Oracle passwords are now CASE SENSTIVE! Hint: the initial password begins
with a capital letter.

3.4 Accessing Oracle

Students cannot logon to the Oracle server directly, instead you can access in a variety of
ways, including using client software, such as SQL*Plus, or embedding SQL in a
programming language, such as Java or PHP.

For this workbook we shall be using the SQL*Plus client (also called Instant Client).

You can use SQL*Plus in one of three ways:


 Apps Anywhere
 From the mi-linux.wlv.ac.uk server
 Instant Client software on your own PC, which can be downloaded from Oracle
directly at https://www.oracle.com/downloads/

For further information on how to access Oracle from mi-linux, please see this page:
http://ora-srv.wlv.ac.uk/info/UsingOracleAtHome.html#Server

Once you have logged into the mi-linux server, you can type the following to start SQL*Plus:
sqlplus

Do remember that linux is case-sensitive.

For information on how to install Instant Client on your own PC, please see this page:
http://ora-srv.wlv.ac.uk/info/InstantClient.html

Note, for all three ways, your Oracle username and password will be the same and you will
access the same database.

Introduction to Oracle and SQL Page – 4


3.5 Apps Anywhere

From a University lab, there will be an icon on your Desktop, that you can
click:

Oracle is available from outside the University on Apps Anywhere, but you need to install
and run the VPN client first. See Appendix E for information on how to do this.

Once you have been validated to use Apps Anywhere, use the “Search Apps” box to
search for: Oracle
This should bring up the following: Click on Launch to register for the tools:

3.6 Starting the Windows Client Software

In Windows select the following menu items:

Start>All Programs>Oracle >sqlplus

As shown below (note your desktop may look different):

Introduction to Oracle and SQL Page – 5


Figure 3-1 Oracle Programs

This will then present you with a log on screen as shown on the following figure:

Figure 3-2 Logging into Oracle

Introduction to Oracle and SQL Page – 6


Fill in the following, note the format of the username carefully:

Username: This is your student number, preceded by OPS$ and followed by


@ora19c
E.g., if your username is 0912345, then type in:
OPS$0912345@ora19c

Password: When you registered for Oracle, you will have been given a password.
Type this in when prompted.

Note, the password will not be echoed on the screen, nor any
asterisks shown.

This will then take you into the SQL*Plus session, as shown in figure 3.3:

Figure 3-3 Oracle SQL*Plus – Initial Screen

You should see an identical screen to the one shown here (except for the username and
date!). If you have something different please ask for help.

3.7 Easy Connect String

If you find the @ora19c returns with:

ORA-12154: TNS:could not resolve the connect identifier specified

This means there is a problem access the tnsnames.ora file that Oracle uses to find your
database. Alternatively, you can use an Easy Connect String instead.

To use this instead of @ora19c when prompted for a username in SQL*Plus, type in:
yourOracleUsername/[email protected]:1521/catdb.wlv.ac.uk

Introduction to Oracle and SQL Page – 7


This must be entered as one line at the Enter user-name: prompt. Replace
yourOracleUsername and yourOraclePassword with your own details.

3.8 First Time Users

Once logged into Oracle if you want to change your password to something different, type:

password

It will ask for your old password first, before you can set a new one.

Note, once you change your password, if you forget it we can only reset it to the original
password.

3.9 THE SQL*PLUS COMMAND LINE

The prompt SQL> means the system is waiting for you to enter a command.

There are two types of command that you may enter:

 SQL commands

for manipulating data in the database. Each SQL command is terminated by a semi-
colon, which will be seen later.

 Control commands

for formatting results and editing. The semi-colon is optional for these commands.

3.10 COPYING THE SAMPLE DATABASE

3.10.1 From Windows 

The sample database used in this workbook needs to be set-up first by the following steps.
This sets up your database on the central server and this same database can be accessed
from the MI labs, other University labs and from home. See Appendix C on the alternative
ways to access Oracle.

First of all you need to download the setup script:

 Go to the Oracle web server: http://ora-srv.wlv.ac.uk


 Look for the link called sqlload.sql setup script
 Right click on this and depending on your browser, select “Save Link As….” or “Save
Target As….”
 If on a University PC, save the file to your “Documents” Personal storage folder (U:\
drive), otherwise save it on your own PC somewhere easily accessible, but not the
Desktop.

Assuming you have logged into Oracle successfully as detailed in the previous section and
have saved the file to your “Documents” folder, type:

@ u:\sqlload

and press RETURN.

Introduction to Oracle and SQL Page – 8


If you have saved your file somewhere else, for example, a memory stick, then replace the
u:\ with the location of your file, including any subfolders, e.g., e:\oracle\sqlload

 Note, this command only needs to be executed once ever. 


3.10.2 From Linux

If you prefer to use mi-linux.wkv.ac.uk

3.11 Listing Your Databases

To find out what database tables you have, type:

select table_name from user_tables;

This refers to a data dictionary table. The data dictionary is a set of tables which allows you
to query what objects you own. See section 22 for further information on the Data
Dictionary.

3.12 Getting Information about the Attributes of a Table

To get a description of a particular table use the DESCRIBE command.

To describe the table EMP:

describe emp

Note, describe is a command proprietary to Oracle and is not part of the SQL standard.
These commands are part of the Plus commands Oracle provides and do not need a semi-
colon after them.

 Now show the structure of the CUSTOMER table.

Try out the following database queries in the Oracle window:

describe dept

select * from dept;

select * from emp;

describe salgrade

select * from salgrade;

What do you think the results of each of these commands means?

4 SQL OVERVIEW

4.1 Introduction

SQL is the standard language for manipulating data in a relational DBMS, becoming "the de
facto standard in the relational database world" (Chris Date). It is English-like and non-

Introduction to Oracle and SQL Page – 9


procedural and can be used to create, query and update data, or control access to the
database. It has a small number of statement types, yet is very powerful and flexible.

 SQL can be used in a number of ways:


 Interactively. Whereby the user directly types in a command to the database.
 Embedded. Where the commands are embedded in a host language, such as C, Java
or COBOL.

For the purposes of this workbook, we shall be using SQL in interactive mode.

SQL processes data a set-at-a-time, which means it works with groups of data items, e.g.,
the entire DEPT table. Traditional data processing usually works a record-at-a-time, which
means to process more than one record, e.g., to update the salary of all lecturers in the
Computing Department, the programmer would have to code loops in the program to
process all records. SQL eliminates the need to write loops, making it a very powerful
language.

SQL has three major components: a data definition language (DDL) for defining the
database structure, a data manipulation language (DML) for retrieving and updating data
and a data control language (DCL) for controlling access to the data. With some types of
database management systems (DBMS), typically hierarchical and network databases, the
database user would need to know a separate language for each of these components.

SQL combines all three within one language; however, we will be concentrating on the DDL
and DML commands initially.

The basic structure of the SQL command is


SELECT ..................................

FROM ..................................

WHERE .................................

The SELECT clause indicates the columns (attributes) to be retrieved.


The FROM clause indicates the tables from which the columns are to be retrieved.
The WHERE clause is optional and is used to specify a selection condition.

For example:
SELECT * FROM EMP;

Or type in the following over 3 lines:


SELECT
*
FROM EMP;

What do these commands retrieve?

 A command can extend from one line to another; however you must put a semi-
colon (;) at the end of the command. This tells Oracle to go and do something. If
you forget to add it on the end of the command just simply type it on the next blank
line.

Introduction to Oracle and SQL Page – 10


The results will look similar to below:

Figure 4-1 Output Results

SQL can be used to:

 Get information from a database


 Add new information to a database
 Revise information in a database
 Remove information from a database
 Create new tables

4.2 Environment Settings

Note, Oracle has default settings for its “environment”, such as how many rows it displays
before showing the column titles again, line width, etc. If you do not want the column titles
appearing more than once on the screen, or if you find the data is wrapping round, even
though there is still space on the right-hand side, the default settings can be altered by
changing the Environment parameters.

To see the settings for all the current environment parameters, type in:

show all

To see a specific parameter, type in, show keyword, where keyword can be substituted by
any parameter, for example:

show linesize

The parameters can be changed by using a SET command, the format is:

set parameter-name new-value

For example, to set the linesize to a larger value:

Introduction to Oracle and SQL Page – 11


set linesize 100

To change the number of rows outputted before re-showing the column titles, change the
pagesize parameter:

set pagesize 30

These are the two main cosmetic changes that you may wish to change; other settings will
be referred to later in the workbook.

Note, these changes are not permanent. If you prefer these settings they will have to be
redone each time you login, or see the section on the LOGIN.sql file (section 10.3).

4.3 Editing Commands

By now, you may have made some typing mistakes. Oracle has a built-in command line
editor, which can be used to correct errors but is tedious to use. In Oracle 11g, however,
the arrow keys can be used to return to an error and can be corrected. Once corrected, you
will have to press return to re-run the amended version.

Alternatively, typing mistakes can be easily corrected without having to type the full
command in again by using a screen editor. Under Windows the default editor is Notepad, if
using the server directly, e.g., via putty and mi-linux, the default editor is vi. If you are not
familiar with vi, you may prefer to use Notepad on your PC and copy & paste your
commands between the PC and the Linux server.

 Notepad is a Windows text editor, the main command you need to know is
File>Save found on the window menu bar to save any amendments and File>Exit
to return to Oracle.

To invoke the editor from within Oracle (either Windows or Linux) type:

ed

This will show the last command typed in (saved to a file called afiedt.buf), the arrow keys
can be used to move to any typing mistakes, correct any errors and return to Oracle (by
selecting File>Save then File>Exit if using Windows). The amended file will appear in the
Oracle Window, to run the amended file, type a forward slash:

This can be used at any time to re-run the last command again, not necessarily after
correcting a mistake.

4.4 Getting Information From A Table

In some cases you may wish to retrieve all information in a particular table, e.g., all the
customer or employee details.

To list all customer details:


SELECT * FROM CUSTOMER;

Introduction to Oracle and SQL Page – 12


As seen previously, * is like a wildcard for retrieving all columns in a table. In some cases
you may only be interested in certain rows and columns, image having to browse through a
database with over 1,000,000 rows and 50 columns!! You would be swamped with
information you probably did not need anyway. What is needed is a method of cutting down
the information.

SQL allows you to restrict which fields and rows you want.

4.4.1 Restricting Columns

To get specific columns, in this case the numbers, names and department numbers of each
employee, in place of the * type in the desired column names:
SELECT EMPNO, ENAME, DEPTNO FROM EMP;

To list the customer number, name and city type:


SELECT CNO, NAME, CITY FROM CUSTOMER;

 Now try and retrieve the employee's name, hiredate and sal:

The results should be similar to:

ENAME HIREDATE SAL


---------- --------- ----------
KING 17-NOV-81 5000
JONES 02-APR-81 2975
SCOTT 09-DEC-82 3000
ADAMS 12-JAN-83 1100
FORD 03-DEC-81 3000
SMITH 17-DEC-80 800
BLAKE 01-MAY-81 2850
ALLEN 20-FEB-81 1600
WARD 22-FEB-81 1250
MARTIN 28-SEP-81 1250
TURNER 08-SEP-81 1500
JAMES 03-DEC-81 950
CLARK 09-JUN-81 2450
MILLER 23-JAN-82 1300

14 rows selected.

4.4.2 Restricting Rows

The previous section showed how to restrict the columns required, now to cut down the
rows. Quite often you may only be interested in say employees from a certain department,
or students on a particular course, so the common value for a group of people can be use to
restrict what rows are retrieved.

The previous format retrieved all the rows in the required fields. To get the same
information just for managers we need to use the WHERE clause.

Introduction to Oracle and SQL Page – 13


Type:

SELECT ENAME, JOB, DEPTNO


FROM EMP
WHERE JOB = 'MANAGER';

Next list all the customers based in England:

SELECT * FROM CUSTOMER


WHERE COUNTRY = 'ENGLAND';

 Now retrieve the employees who are clerks:

ENAME JOB DEPTNO


---------- --------- ----------
ADAMS CLERK 20
SMITH CLERK 20
JAMES CLERK 30
MILLER CLERK 10

Note, although commands can be typed in either upper or lower case, the data stored in the
database is case sensitive. Matching the case exactly, type in the following:

select ename, job, deptno from emp


where job = 'manager';

 Why are no records retrieved?

5 QUITTING ORACLE

To exit ORACLE type:


QUIT

Remember to logout of Windows if finished completely.

 Your data in an Oracle database is saved centrally on the server on ora-srv. You do
not need to keep a backup of it elsewhere, such as a memory stick. You do however
need to keep a backup of any SQL query files that you wish to keep. Files can also
be backed up onto the Linux servers by using a secure ftp (File Transfer Protocol)
program, such as FileZilla, to transfer them to and from the server.

5.1 Restarting Oracle

Log back into Oracle again by following sections 3.4 and 3.5.

Note you do not need to reload the sample database.

6 GETTING HELP

Oracle have an online set of documents that give you further help on different topics:
Local version:
http://ora-srv.wlv.ac.uk/oracle19c_doc/

Introduction to Oracle and SQL Page – 14


Oracle’s version:
https://docs.oracle.com/en/database/oracle/oracle-database/index.html

There is a large range of topics, some beyond what you need to know. Useful areas include:
Introduction to http://ora-srv.wlv.ac.uk/oracle19c_doc/cncpt/introduction-to-oracle-
Oracle database.html
Introduction to http://ora-srv.wlv.ac.uk/oracle19c_doc/cncpt/sql.html
SQL
Database https://docs.oracle.com/en/database/oracle/oracle-
Concepts: database/19/cncpt/index.html
Database https://docs.oracle.com/en/database/oracle/oracle-
Development database/19/adfns/index.html
(Advanced)
Oracle Books: https://docs.oracle.com/en/database/oracle/oracle-
database/19/books.html

7 Summary so far

By now you:
 Will have an Oracle account, ensure you remember your password if you have
changed it
 Have been introduced to the tables and general SQL background
 Can list what tables you own
 Can carry out simple queries
 Know where to find the online help

If you cannot do any of these, please review the Basics section again.

For example, ensure you know how to do the following:

 Show the contents of the EMP table


 Show the structure of the EMP table

Introduction to Oracle and SQL Page – 15


Saving Queries and
Results
8 STORING QUERY OUTPUT

The results of a query can be stored in a file as well as displayed on screen.

To send the results of a query to a file use the SPOOL command:


SPOOL [drive:\folder\]filename

All information that is displayed on the screen after issuing the SPOOL command will also be
written to the specified file. The suffix .lst will be added to the specified filename to identify
it as a listing file. You can add a different suffix if required, e.g., filename.txt to denote a
text file. This can be useful if importing into Word or Excel so the package will automatically
know the file type. On Windows you can also add a directory and folder name.

SQL*PLUS will continue to spool information to the file until the spooling is turned of by the
following command:
SPOOL OFF

For example (press return after each line):


SPOOL u:\emplist.txt
SELECT * FROM EMP;
SPOOL OFF

 The file emplist.txt will be saved in your Documents folder, see if you can find it.
 If using Linux, then omit the directory name (u:\)
 If using your own PC, then replace u:\ with your own local drive name.

To do:
 Write an SQL command that lists all the departments
 Amend the command so that the output is stored in a file called ‘Output.txt’
 Look on the U: drive for a file called ‘Output.txt’ 
 Use Wordpad or Notepad to look at the contents of ‘Output.txt’ 

9 SAVING AND RETRIEVING QUERIES

9.1 Saving a query

If you wish to keep a query that you have just typed in:

SAVE [drive:\folder\]filename

saves the query in filename.sql

Note:
 that this instruction only saves the SQL command and not the associated
formatting commands (such as headers or footers). To save both SQL and format
commands you have to use the editor.
 You do not need to include the .sql file extension, this will be added automatically.
 The following examples assume you are using a University PC, where your “My
Documents” folder can be accessed from the U:\ drive. If you using your own PC,
replace U:\ with your own file structure, such as C:\Mary\MyOracle

Introduction to Oracle and SQL Page – 19


For example, to create a new command file that produces a report on salaries of employees
in department 30 and includes some formatting commands, first create a new file called
personnel (remember, you do not need to include the .sql file extension):

ed u:\personnel

Replace u:\ with your own drive, if using your own PC.

Then type in the following into this file:

TTITLE 'ACME WIDGET SALES DEPT PERSONNEL REPORT'


BTITLE 'COMPANY CONFIDENTIAL'
SELECT DEPTNO, ENAME, SAL
FROM EMP
WHERE DEPTNO = 30;
BTITLE OFF
TTITLE OFF

TTITLE and BTITLE are SQL*Plus commands to add header/footers to a report. They need
to be switched off at the end; otherwise they will appear with any future queries. Further
formatting commands will be introduced later.

Note, if using Linux:


 filenames are case sensitive, so if a file is saved in upper case then it must be
retrieved in upper case. The file suffixes that Oracle appends are always in
lowercase.
 You do not need to include the drive name (u:\)

SPOOL saves the results of a query; ed creates a SQL query file. The SQL query file could
include a SPOOL command so that the results of the query can also be saved.

To run the command file, enter:

START u:\PERSONNEL

 Use Notepad or another text editor to look at the file U:\PERSONNEL.sql 

9.2 Retrieving and executing a query

START u:\filename

retrieves the query stored in filename.sql and runs it.

Alternatively the @ symbol can be used instead of start:

@ u:\filename

To just retrieve the query:

GET u:\filename

To show the last command typed in:

Introduction to Oracle and SQL Page – 20


list

Create a query that lists all the employees in department 20 and save the results in a file
called EMP.txt:

 Create a query that lists all the clerks and save the results in a file called CLERKS.txt:

EMPNO ENAME JOB MGR HIREDATE SAL COMM


DEPTNO
----- ---------- --------- ---------- --------- ---------- ---------- -----
-----
7876 ADAMS CLERK 7788 12-JAN-83 1100
20
7369 SMITH CLERK 7902 17-DEC-80 800
20
7900 JAMES CLERK 7698 03-DEC-81 950
30
7934 MILLER CLERK 7782 23-JAN-82 1300
10

The editor can be used to create a file from scratch. To create a command file which
produces a report on Salesmen earning more than 2500, start Notepad by typing:

ed u:\query2

Then type in the following:

REM List salespeople who earn more than 2500 per month
SELECT DEPTNO, ENAME, SAL FROM EMP
WHERE JOB = 'SALESMAN' AND SAL + COMM > 2500;

REM at the start of the line indicates a comment, alternatively, if the documentation spans
several lines, use /* at the start and */ at the end of the comment.

Save as before and to execute it:


start u:\query2

 Use Notepad to create a file called QUERY3, which displays the name, salary and
commission of all salesmen:

ENAME SAL COMM


---------- ---------- ----------
ALLEN 1600 300
WARD 1250 500
MARTIN 1250 1400
TURNER 1500 0

9.3 Login.sql

When you login to Oracle it will search for a file called login.sql in the current working
directory (normally the U:\ drive, or Documents folder on the University labs). This can
contain any SQL or SQL*Plus commands that you want Oracle to execute when you first
login, similar to an autoexec.bat on a PC.

To create a login file:

Introduction to Oracle and SQL Page – 21


ed u:\login

Then add the following:

SET PAGESIZE 50
SET LINESIZE 120
SET PAUSE 'Press RETURN to Continue...'
SET PAUSE ON
ALTER SESSION SET NLS_DATE_FORMAT = "DD-MON-YYYY";

Where:

 PAGESIZE affect how many rows are shown before a page break
 LINESIZE affects how many characters are shown before it wraps the line
 The PAUSE commands will show 50 lines at a time, prompting you to press return in
between (useful if you have a lot of rows in your database)
 NLS_DATE_FORMAT command will show dates in 4-digit year format. The default is
to show 2-digit dates.

Save the file to your U:\ drive, which is Oracle’s working directory, do not save the file to a
different disk or drive, otherwise it will not work. You will not notice any changes until you
logout and in again to Oracle. In the meantime the effects of the file can be invoked by
running the file:

start u:\login

Note, no noticeable differences will be seen until a query is run!

Introduction to Oracle and SQL Page – 22


Data Manipulation
Commands
10 SELECTION CONDITIONS

10.1 Introduction

A selection condition is the part of the SQL command that forms the WHERE clause, e.g.
WHERE DEPTNO = 30

The WHERE clause is one of the most important and complex clauses in the SELECT
statement. It controls what rows are retrieved in the output, by applying a filter condition
called a search condition.

Standard SQL search conditions can involve:

 Simple comparisons
 Compound conditions formed with AND, OR and NOT
 Special SQL predicates such as BETWEEN, IN, LIKE and NULL
 Comparison with the results of a subquery (a SELECT statement within a SELECT
statement)
 Additional predicates designed for use with subqueries, such as ALL, ANY and
EXISTS

This large range of possibilities makes the WHERE clause so complicated.

WHERE always works in the following manner:

 The search condition is applied to each prospective row in the output.


 If the condition is satisfied, then that row will be included in the output.
 If the condition is not satisfied, then that row is omitted from the output.

10.2 Comparison Operators

All search conditions are built from logical expressions, which are always true or false. The
simplest form of a logical expression is known as a simple comparison, or relational
predicate. Simple comparisons use comparison operators to compare two values.

Relational predicates appear in the WHERE clause and can include references to column
names, literal constants, numeric or character expressions and non-aggregate functions.

The main rule to remember is that the two items being compared must of a compatible data
type. You cannot mix numeric and character values in a comparison. Numeric with numeric,
character with character and date with date are the only allowable forms.

E.g., ename = SMITH is not allowed (ename is a character field)

but ename = 'SMITH' is allowed

The usual format of a simple comparison is:

Column-Name Comparison-Operator Value Type

ename <> 'SMITH' character value


deptno = 95 numeric value
hiredate > '11-JUL-1996' date value

Introduction to Oracle and SQL Page – 25


The following are valid comparison operators. NOT can be optionally used with the last four
operators for negation:

= equal
<> not equal
> greater than
>= greater than, or equal to
< less than
<= less than, or equal to
[NOT] BETWEEN .... AND .... [not] between one value and another
[NOT] IN ( list ) [not] in a list of values
[NOT] LIKE [not] like a value
IS [NOT] NULL value is [not] equal to null

10.3 The LIKE operator

This operator uses two symbols:

% represents a string of characters


_ represents a single character (underscore)

To list all employees whose name begins with S:

SELECT * FROM EMP


WHERE ENAME LIKE 'S%';

10.4 Some Example Queries

Some example selection queries follow. Fill in the appropriate SQL in the spaces given.

Find all employees where their commission exceeds their salary:

SELECT ENAME, SAL, COMM FROM EMP


WHERE COMM > SAL;

 Find all salespeople in Department 30 whose salary is greater than or equal to


£1,500 (hint: no need to include the pound sign):

EMPNO ENAME SAL DEPTNO


---------- ---------- ---------- ----------
7499 ALLEN 1600 30
7844 TURNER 1500 30

List information about all managers across all departments and clerks in department 10:

SELECT *
FROM EMP
WHERE JOB = 'MANAGER' OR
(JOB = 'CLERK' AND DEPTNO = 10);

Introduction to Oracle and SQL Page – 26


 List information about managers and clerks in department 10:

EMPNO ENAME JOB MGR HIREDATE SAL COMM


DEPTNO
----- ---------- --------- ---------- --------- ---------- ---------- -----
-----
7782 CLARK MANAGER 7839 09-JUN-81 2450
10
7934 MILLER CLERK 7782 23-JAN-82 1300
10

 List information about employees in department 10 who are not managers or clerks:

EMPNO ENAME JOB MGR HIREDATE SAL COMM


DEPTNO
----- ---------- --------- ---------- --------- ---------- ---------- -----
-----
7839 KING PRESIDENT 17-NOV-81 5000
10

List names and departments of employees who are not clerks, analysts or salesmen:

SELECT ENAME, DEPTNO


FROM EMP
WHERE JOB NOT
IN ('CLERK', 'ANALYST', 'SALESMAN');

 List jobs of employees whose names begin with M:

EMPNO ENAME JOB


---------- ---------- ---------
7654 MARTIN SALESMAN
7934 MILLER CLERK

 List the employee number and name of employees who have A as the second letter
of their name:

EMPNO ENAME
---------- ----------
7521 WARD
7654 MARTIN
7900 JAMES

 List employees and jobs earning between £1,200 and £1,400:

EMPNO ENAME JOB SAL


---------- ---------- --------- ----------
7521 WARD SALESMAN 1250
7654 MARTIN SALESMAN 1250
7934 MILLER CLERK 1300

 List employees whose salaries are not between £1,200 and £1,400:

EMPNO ENAME JOB SAL


---------- ---------- --------- ----------
7839 KING PRESIDENT 5000
7566 JONES MANAGER 2975
7788 SCOTT ANALYST 3000

Introduction to Oracle and SQL Page – 27


7876 ADAMS CLERK 1100
7902 FORD ANALYST 3000
7369 SMITH CLERK 800
7698 BLAKE MANAGER 2850
7499 ALLEN SALESMAN 1600
7844 TURNER SALESMAN 1500
7900 JAMES CLERK 950
7782 CLARK MANAGER 2450

11 rows selected.

 List names and departments of employees who are clerks, analysts or salesmen:

EMPNO ENAME JOB DEPTNO


---------- ---------- --------- ----------
7788 SCOTT ANALYST 20
7876 ADAMS CLERK 20
7902 FORD ANALYST 20
7369 SMITH CLERK 20
7499 ALLEN SALESMAN 30
7521 WARD SALESMAN 30
7654 MARTIN SALESMAN 30
7844 TURNER SALESMAN 30
7900 JAMES CLERK 30
7934 MILLER CLERK 10

10 rows selected.

 List names, jobs and commission of employees who are not in department 10, 30 or
40:

EMPNO ENAME JOB COMM


---------- ---------- --------- ----------
7566 JONES MANAGER
7788 SCOTT ANALYST
7876 ADAMS CLERK
7902 FORD ANALYST
7369 SMITH CLERK

List employees who have not earned any commission:

SELECT * FROM EMP WHERE COMM IS NULL;

10.5 PREVENTING THE SELECTION OF DUPLICATE ROWS

To list all the distinct jobs in EMP:

SELECT DISTINCT JOB


FROM EMP;

 To list all the distinct Departments in EMP:

DEPTNO
----------
30
20

Introduction to Oracle and SQL Page – 28


10

11 CONTROLLING THE ORDER IN WHICH ROWS ARE DISPLAYED

11.1 The ORDER BY Clause

The ORDER BY clause lets you order rows:

In ascending order

In descending order

Using multiple columns

With null values

Note, an ORDER BY clause is always the last clause in a SELECT statement. The format is:

ORDER BY <order_column> [ASC | DESC]


[, <order_column> [ASC | DESC] .....]

Order by sorts the query results based on the data in one, or more columns. Each
order_column must correspond to a column in the query results and can be one of the
following:

A field in a FROM table that is a select item in the main SELECT clause (not in a subquery)

A numeric expression indicating the location of the column in the result table (The leftmost
column is number 1)

Specify DESC if you want the results in descending order, ASCending is the default. Query
results will appear unordered if the ORDER BY clause is missing.

11.2 Ordering with null values

When you order by columns that contain null (blank) values, the null entries are always
displayed first regardless of whether you chose ascending or descending order.

To list employees and jobs in department 30, in order of their salary:

SELECT ENAME, JOB, SAL FROM EMP


WHERE DEPTNO = 30 ORDER BY SAL;

To list the same details in descending order by salary:

SELECT ENAME, JOB, SAL FROM EMP


WHERE DEPTNO = 30
ORDER BY SAL DESC;

To sort employees by job and in descending order by name:

SELECT ENAME, JOB, DEPTNO FROM EMP


WHERE DEPTNO = 30

Introduction to Oracle and SQL Page – 29


ORDER BY JOB, ENAME DESC;

 To sort employees by job and then in descending order by salary:

EMPNO ENAME JOB SAL


---------- ---------- --------- ----------
7788 SCOTT ANALYST 3000
7902 FORD ANALYST 3000
7934 MILLER CLERK 1300
7876 ADAMS CLERK 1100
7900 JAMES CLERK 950
7369 SMITH CLERK 800
7566 JONES MANAGER 2975
7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7499 ALLEN SALESMAN 1600
7844 TURNER SALESMAN 1500
7521 WARD SALESMAN 1250
7654 MARTIN SALESMAN 1250

14 rows selected.

12 MANIPULATING DATA

SQL supports Data Manipulation Commands (DML) to allow tables to be queried, updated, or
deleted.

12.1 Committing the changes

Normally changes to a database e.g. inserts, deletes and modifies do not take an immediate
permanent affect. Modifications are assumed to be part of a transaction.

Transactions are sets of modifications that must either all succeed, or else all fail. For
example, given a transaction to raise every employee’s salary by 10%, everyone should get
the increase, not only say half if a power failure happened half way through the transaction.

Normally a user applies all the changes they want in a transaction and then if they are
happy with the results makes them permanent. Otherwise they restore the database to the
state it had before any changes were made.

The command to make changes permanent is COMMIT.

The command to reverse all the changes since the last commit is ROLLBACK.

COMMIT is like pressing File>Save in a Word document, whilst ROLLBACK is like quitting
Word without saving your changes.

Remember to type COMMIT after each insert/delete or update if you want to keep the
change(s) made.

The system will automatically commit your records if you carry out any data definition
commands, such as a CREATE TABLE statement, or if you exit the system cleanly (that is,
you quit the system properly rather than just closing the SQL*Plus window).

Introduction to Oracle and SQL Page – 30


12.2 Inserting Rows

To add a new employee to the EMP table type

INSERT INTO EMP


VALUES (7945, 'KING','CLERK',7698,'7-APR-1999',1000,NULL,30);

COMMIT;

The values for the fields must be in the order in which they were defined in the table,
otherwise, incorrect or invalid data will be inserted in the wrong fields and can cause an
error message. If the order is unknown use the DESCRIBE command (section 4.4) to check.

To verify the information you have added, type:


SELECT * FROM EMP
WHERE ENAME = 'KING';

Insert a new department:


INSERT INTO DEPT
VALUES (90,’FSE’,’WOLVERHAMPTON’);

COMMIT;

12.3 Inserting rows with null values

If you want to leave several fields in a table blank, it may be quicker to specify the fields to
be filled in rather than specifying NULL for the blank fields.
For example:
INSERT INTO EMP
(EMPNO, ENAME, JOB, HIREDATE, SAL, DEPTNO)
VALUES (7955,'WILSON','CLERK','22-APR-1988', 1500, 30);

COMMIT;

Remember that the DBMS will give you an error message if you attempt to assign a null
value to a field that must have a value entered. The above example will work, as the
database knows that the missing commission attribute COMM is allowed to hold a null value.

Numeric values do not require quotes round them, however character and date fields must
be enclosed in single quotes ('). The normal default format for the date field is ‘DD-MON-YY,
though other formats can be used with the TO_DATE function, see section 18.

 Now create a new EMP record with the following values – EMPNO: 9000, ENAME:
your surname, JOB: MANAGER, DEPTNO: 90, COMM: 0, MGR: 7839, HIREDATE: today's
date and give yourself a value for SAL:

The system should respond with the following messages:

1 row created.

Commit complete.

Introduction to Oracle and SQL Page – 31


Alternatively, if you know the exact order of the fields, it is probably quicker to insert null
values for any fields with missing values. To leave any field blank, use the value NULL:

INSERT INTO CUSTOMER


VALUES ('1111', NULL, 'A LEMMING', 'MANCHESTER',
'ENGLAND', NULL, NULL, NULL);

COMMIT;

 A point to ponder on, if the customer 1111, A Lemming, makes a lot of orders, is it a
good idea to constantly type in his details? Can you think of any disadvantages of
placing the Customer and Part details in one table? Plus, how would you represent a
new customer who has yet to place an order, or new parts that have yet to be
ordered by anyone? Keep this in mind when we look at database design in the
lectures.

12.4 Deleting Records

The format of the SQL - DELETE statement is:

DELETE FROM TableName

[WHERE FilterCondition1

[AND | OR FilterCondition2 ...]]

Where:

FROM TableName Specifies the table in which records are deleted from.
WHERE FilterCondition1 [AND | FilterCondition specifies the criteria that records must
OR FilterCondition2 ...] meet to be deleted. You can include as many filter
conditions as you like, connecting them with the AND
or OR operator.
You can also use the NOT operator to reverse the
value of a logical expression, or use IS NULL to check
for an empty field.
Our new employee KING has decided to leave, to remove the record from the EMP table
type:
DELETE FROM EMP
WHERE ENAME = 'KING'
AND EMPNO = 7945;

COMMIT;

 Why do we need to specify a number as well as the name when deleting the record?

 What command verifies the record has been deleted?

The system should respond with the message:

- no rows selected

Introduction to Oracle and SQL Page – 32


12.5 Updating Rows

The format of the command is:


UPDATE TableName1

SET Column_Name1 = eExpression1

[, Column_Name2 = eExpression2 ...]

WHERE FilterCondition1 [AND | OR FilterCondition2 ...]]


Where:
UPDATE TableName1 Specifies the table in which records are
updated with new values.
SET Column_Name1 = eExpression1 [, Specifies the columns that are updated and
Column_Name2 = eExpression2 their new values. If you omit the WHERE
clause, every row in the column is updated
with the same value.
WHERE FilterCondition1 [AND | OR Specifies the records that are updated with
FilterCondition2 ...]] new values. FilterCondition specifies the criteria
that records must meet to be updated with
new values.
You can include as many filter conditions as
you like, connecting them with the AND or OR
operator. You can also use the NOT operator to
reverse the value of a logical expression, or
use IS NULL to check for an empty field.
Note: SQL can only update one table at a time.
To update CLARK's manager and department number, type:
UPDATE EMP
SET MGR = 7566, DEPTNO = 20
WHERE ENAME = 'CLARK';

COMMIT;

Why could this command produce unexpected results?

13 DATA DEFINITION COMMANDS

13.1 Creating a Table

 The code that produced the sample database can be seen in Appendix A.

The following command illustrates how the sample DEPT table was created. DO NOT
TYPE THIS COMMAND IN!

CREATE TABLE DEPT


(DEPTNO NUMBER(2)
constraint PK_DEPT primary key,

Introduction to Oracle and SQL Page – 33


DNAME VARCHAR2(14) NOT NULL
constraint UC_DNAME check (DNAME=upper(DNAME)),
LOC VARCHAR2(13)
constraint UC_LOC check (LOC=upper(LOC)) );

The figure in brackets after the data type indicates the length.
The following constraints have been implemented on the Department table to ensure that
the integrity of the database is maintained:

 The department number attribute DEPTNO is the primary key because of the
constraint PK_DEPT. This also means that the user must insert a value into this
attribute when inserting or updating information in this table.
 The department name attribute DNAME must be entered because of the NOT NULL
clause and it must be in uppercase because of the constraint UC_DNAME.
 The location attribute LOC may be left blank because of the absence of a NOT NULL
clause. If it is entered it must be in uppercase because of the constraint UC_LOC.

 The constraint names (e.g. PK_DEPT) are specified so that Oracle can use these as
labels for the constraint in its Data Dictionary.
The basic valid data types are:
Type Precision Scale Description

CHAR n - Fixed character of width n

DATE - - Date

NUMBER n d Numeric of width n with d decimal places

VARCHAR2 N - Variable character of width n

The following command creates a table called PROJ with three columns PROJNO, PNAME
and BUDGET. You should type this in:

CREATE TABLE PROJ


(PROJNO NUMBER(5)
constraint PK_PROJ primary key,
PNAME VARCHAR2(32),
constraint UC_PNAME check (PNAME=upper(PNAME)),
BUDGET NUMBER(8,2) NOT NULL
constraint BD_BUDGET check (BUDGET >= 0));

The following constraints have been implemented on the project table PROJ:
 PROJNO is the primary key and is a number because we will use a sequence to
generate the next number automatically when a new record is inserted.
 BUDGET cannot have a null value.
 PNAME is a string of 32 characters.
 BUDGET is a number of maximum width 8 characters and with two decimal
places.

Introduction to Oracle and SQL Page – 34


13.2 Composite Primary and Foreign Keys

The primary key (PK) for tables with composite primary keys are defined slightly different
from above, the clause PRIMARY KEY is not put after each field taking part in the PK, but as
a separate clause. For example:
CREATE TABLE Tablename1
(col1 VARCHAR2(10), col2 VARCHAR2(10), col3 VARCHAR2(3),
CONSTRAINT PK_TAB PRIMARY KEY (col1,col2))

Single foreign keys (FK) can be defined using the REFERENCES clause (see the definition for
the EMP table in Appendix A for an example).

Composite foreign keys can be defined using the FOREIGN KEY clause, for example:

CREATE TABLE Tablename2 (col1 VARCHAR2 (10), col2 VARCHAR2 (10),


......,
CONSTRAINT FK_TAB2 FOREIGN KEY (col1,col2) REFERENCES
Tablename1)

This ensures that any values put into the col1 and col2 columns exist in the related columns
of Tablename1 so enforcing referential integrity.

If the column names are not the same in both tables, then the name of the related fields
must also be specified:

CREATE TABLE Tablename3(newcol1 VARCHAR2 (10), newcol2


VARCHAR2 (10), ......,
CONSTRAINT FK_TAB3 FOREIGN KEY (newcol1,newcol2)
REFERENCES Tablename1 (col1,col2))

For example, to create a table EMPPROJ that records which projects an employee works on:

CREATE TABLE EMPPROJ (


EMPNO NUMBER(4) constraint fk_emp REFERENCES EMP,
PROJNO NUMBER(5) constraint fk_proj REFERENCES PROJ,
HOURS NUMBER(4),
CONSTRAINT pk_empproj PRIMARY KEY(empno, projno));

To create a further table that keeps a history of an employee’s expenses per project:

CREATE TABLE EMPPROJ_EXPENSES (


EMPNO NUMBER(4),
PROJNO NUMBER(5),
CLAIMDATE DATE,
CLAIMTOTAL NUMBER(7,2),
CONSTRAINT pk_ep_exp
PRIMARY KEY(empno, projno, claimdate),
CONSTRAINT fk_ep
FOREIGN KEY(empno, projno) REFERENCES EMPPROJ);

Introduction to Oracle and SQL Page – 35


13.3 Creating a Sequence for a Table's Primary Key.

The PROJNO attribute is the primary key for the PROJ table. Whenever a new row is
inserted into this table a new unique number needs to be allocated. Oracle allows you to do
this automatically if you create a sequence for a TABLE.

To do this first create the sequence:

CREATE SEQUENCE PROJSEQ;

Now it can be used instead of a primary key value:

INSERT INTO PROJ VALUES


(PROJSEQ.NEXTVAL,'ORACLE VERSION 10',15000);

COMMIT;

The sequence can also be used to add a record to a related table, such as the EMPPROJ
table, so long as you add the employees to a particular project at the same time. For
example, to add a new project and an employee at the same time:

INSERT INTO PROJ VALUES


(PROJSEQ.NEXTVAL,'ORACLE DEVELOPER',10000);

INSERT INTO EMPPROJ VALUES (7902, PROJSEQ.CURRVAL, 20);


COMMIT;

Note, the above 2 inserts form part of a transaction, so the commit is only needed after the
last insert.

NEXTVAL returns the next available number, incremented automatically, whereas CURRVAL
returns the current value.

 List all of the information in the PROJ and EMPPROJ tables.

PROJNO PNAME BUDGET MGRPROJNO


---------- -------------------------------- ---------- ----------
1 ORACLE VERSION 10 15000 7698
2 ORACLE DEVELOPER 10000 7566
EMPNO PROJNO HOURS
---------- ---------- ----------
7902 2 20

13.4 Creating a table with an AS clause

It is possible to create a table and copy rows into it in a single operation.

To create the table BONUS and copy rows into it, type:

CREATE TABLE BONUS (ENAME, JOB, SAL , COMM)


AS ( SELECT ENAME, JOB, SAL, COMM
FROM EMP
WHERE JOB = 'MANAGER' or COMM > 0.25 * SAL );

Introduction to Oracle and SQL Page – 36


Note that the only employees eligible for the bonus are managers or those whose
commission is more than 25% of their salary.

13.5 Copying rows from one table to another

You can use INSERT to select rows from one table and copy them into another.

To add employees whose commission is greater than 10% of their salary:

INSERT INTO BONUS(ENAME, JOB, SAL, COMM)


SELECT ENAME, JOB, SAL, COMM
FROM EMP WHERE COMM > 0.10 * SAL;

COMMIT;

13.6 Multiple Inserts

Whilst an INSERT statement only allows you to insert a record to one table at a time, the
INSERT ALL command allows multiple inserts into either one or more tables.

For example, to add 3 new records to the DEPT table:

INSERT ALL
INTO Dept VALUES (15, 'MARKETING', 'BIRMINGHAM')
INTO Dept VALUES (25, 'ART AND DESIGN', 'LONDON')
INTO Dept VALUES (35, 'TEACHING', 'WALSALL')
SELECT * FROM DUAL;
COMMIT;

Note, the SELECT * FROM DUAL is part of the syntax and the above will not work without it.

To add 2 new records to the DEPT and EMP tables:

INSERT ALL
INTO Dept VALUES (45, 'SCIENCE', 'WOLVERHAMPTON')
INTO EMP (empno, ename, job, hiredate, sal, deptno)
VALUES (8888,'JAMES','TEACHER', '01-JAN-2014', 2000, 35)
SELECT * FROM DUAL;
COMMIT;

Note, you cannot set the deptno for a new emp record to department that did not previous
exist. This is to do with the referential integrity constraints. Constraint checking can be
deferred to commit time and this is covered in more advanced database modules.

13.7 Deleting a Table

A table can be deleted by using the following command.

DROP TABLE tablename;

where tablename is the name of the table to be deleted.

Introduction to Oracle and SQL Page – 37


13.8 Making changes to Columns

13.8.1 Altering Columns

Columns can be altered by the following command:

ALTER TABLE TABLENAME


MODIFY (COLUMN DEFINITION);

For example, to alter the BUDGET column of PROJ to accept numbers up to nine digits:

ALTER TABLE PROJ


MODIFY (BUDGET NUMBER(9,2));

The system will respond with:

- Table altered

Note, the column width can be decreased and the data type changed, but only if the column
contains NULL values.

A column can be changed from being NOT-NULL to allowing NULL values, by adding the
NULL clause at the end of the column specification. for example :

ALTER TABLE PROJ


MODIFY (BUDGET NUMBER(9,2) NULL);

13.8.2 Adding a Column

Extra columns can be added to a table:

ALTER TABLE TABLENAME


ADD (COLUMN DEFINITION)

For example, add a column MGRPROJNO to the table PROJ (the manager of the project):

ALTER TABLE PROJ


ADD (MGRPROJNO NUMBER constraint fk_empmgr
REFERENCES EMP(empno));

The system replies with:

- Table altered.

All fields in the new column will be initially set to NULL. To make a column contain only non-
NULL values:

 Add the new column


 Add values to every field, so there are no non-NULL values
 Alter the table to make the column NOT-NULL

Introduction to Oracle and SQL Page – 38


To add references in the project table to the project’s manager:

 Update the PROJ table so that BLAKE is the manager of project 1:

 Update the PROJ table so that JONES is the manager of project 2:

Don’t forget to commit the changes.

13.8.3 Deleting a Column

A column can be deleted using the following format:

ALTER TABLE table_name DROP COLUMN column_name;

13.9 Violating Schema Definition

Type the following insert statements. Can you say why you are getting error messages (see
Appendix A for clues)?

INSERT INTO CUSTOMER


VALUES ('2000',NULL, 'K WEBSTER', 'MANCHESTER',
'ENGLAND', 6, 'WHEEL', 0);

Problem?

INSERT INTO EMP


(EMPNO, ENAME, HIREDATE, DEPTNO)
VALUES (7955, 'HARPER', ’11-JUL-2000’, 30);

Problem?

INSERT INTO DEPT VALUES (100, 'computing', 'MAIN SITE');

Problems?

INSERT INTO EMP


(EMPNO, ENAME, HIREDATE, DEPTNO)
VALUES (7810, 'JONES', ’01-DEC-1999’, 50);

Problem?

Note, since these all generate error messages, there is no need to rollback the transaction.

14 JOINING TABLES

14.1 Introduction

Sometimes information needs to be retrieved from more than one table. The relationships
between rows in one table and rows in another are established by the values in certain
corresponding columns (foreign key).

Introduction to Oracle and SQL Page – 39


For example:

EMP DEPT
EMPNO ENAME JOB ..... DEPTNO DEPTNO DNAME ......

7499 ALLEN SALES ..... 30 30 SALES ......

 
JOIN ATTRIBUTES

The table must have matching values in the Join attributes to enable a join to take place. If
there are no matching values, the tables will not join! For example, if 30 was missing from
the DEPT table, then the employees from department 30 would not appear in any output
that joins tables DEPT and EMP together. (A consequence of violating referential integrity!)

14.2 Basic SQL Structure For Joining Tables

SELECT some columns

FROM two or more tables

WHERE table1.col1 = table2.col2 [ AND table3.col3 = table4.col4 [AND ....]]

Note, two, or more tables can be joined in a SQL statement, but each join condition
specifies the link between two tables only. If, for example, three tables appear in the FROM
clause, there should normally be two join conditions.

14.3 Join Operators

= Equal

<> Not equal

> Greater than

>= Greater than, or equal to

< Less than

<= Less than, or equal to

BETWEEN lower-value AND higher-value A value between lower and higher

LIKE Pattern matching

14.4 Some Example Join Queries

To find ALLEN's location:

SELECT ENAME, LOC


FROM EMP E, DEPT D
WHERE ENAME = 'ALLEN' AND E.DEPTNO = D.DEPTNO;

Introduction to Oracle and SQL Page – 40


 When two columns from different tables have the same name (i.e., DEPTNO in this
case), you must use the table name prefixes to clarify exactly which columns you mean.

Aliases can be used for tables, e.g., E represents EMP and D DEPT. In this case the aliases
work as a shorthand notation for the relevant tables. In other cases, for example, when
comparing a table to itself (see later), they are vital.

To list information about all the employees in Chicago (without aliases):

SELECT DEPT.DEPTNO, DNAME, LOC, ENAME, JOB


FROM EMP, DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO AND LOC = 'CHICAGO';

 Run the previous query using table abbreviations/aliases:

DEPTNO DNAME LOC ENAME JOB


---------- -------------- ------------- ---------- ---------
30 SALES CHICAGO BLAKE MANAGER
30 SALES CHICAGO ALLEN SALESMAN
30 SALES CHICAGO WARD SALESMAN
30 SALES CHICAGO MARTIN SALESMAN
30 SALES CHICAGO TURNER SALESMAN
30 SALES CHICAGO JAMES CLERK
30 SALES CHICAGO WILSON CLERK

7 rows selected.

Note that the abbreviations are defined in the FROM clause. Once defined they must be
used in place of the table they are representing.

Columns can also be given aliases with the AS new_column_name clause. This should
directly follow the column name in the SELECT clause. The new column name can not
contains spaces and can be a maximum of 10 characters.

What does the following command do?

SELECT DEPT.DEPTNO, DNAME AS DEPT_NAME,


JOB, ENAME AS EMP_NAME
FROM DEPT, EMP
WHERE DEPT.DEPTNO = EMP.DEPTNO
ORDER BY DEPT.DEPTNO;

To find the salary grade of each employee:


SELECT GRADE, JOB, ENAME, SAL
FROM SALGRADE, EMP
WHERE SAL BETWEEN LOSAL AND HISAL
ORDER BY GRADE, JOB;

In this BETWEEN join, the SAL field of each row of the EMP table is "tested" against the
LOSAL and HISAL values of each row of the SALGRADE table.

SALGRADE
GRADE LOSAL HISAL

Introduction to Oracle and SQL Page – 41


1 700 1200
2 1201 1400
3 1401 2000

In SQL, a column cannot be compared to itself, however for some queries this may be
necessary, e.g., it may be required to compare one salesman's commission against another.
To achieve this table aliases must be used.

To find the name and department of salesmen who earn more commission than 'Ward':

SELECT S.ENAME, S.DEPTNO, S.COMM,


J.ENAME, J.DEPTNO, J.COMM
FROM EMP S, EMP J
WHERE J.ENAME = 'WARD'
AND S.JOB = 'SALESMAN'
AND S.COMM > J.COMM;

To find the salary and jobs of employees who earn more than Jones:

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';

The query should result in something similar to:

ENAME SAL JOB ENAME SAL JOB


---------- --------- --------- ---------- --------- ---------
KING 5000 PRESIDENT JONES 2975 MANAGER
SCOTT 3000 ANALYST JONES 2975 MANAGER
FORD 3000 ANALYST JONES 2975 MANAGER

When joining tables you are not limited to just two tables. As many tables as required can
be accessed.

 The important thing is that the all the join clauses are specified otherwise you will
cause a Cartesian product! Generally, for N tables there are normally N-1 join clauses
in the WHERE clause.

To list the employee name, location and project name:

SELECT ENAME, LOC, PNAME


FROM EMP E, DEPT D, PROJ P, EMPPROJ EP
WHERE E.DEPTNO = D.DEPTNO
AND E.EMPNO = EP.EMPNO
AND P.PROJNO = EP.PROJNO;

14.5 Recursive Queries

Recursive queries are needed where a relation has a recursive relationship associated with it
(a pig’s ear on an ER diagram). In our sample database the manager is represented by the

Introduction to Oracle and SQL Page – 42


MGR attribute, which is a recursive “manages” relationship on Emp. These queries require a
table to be compared against itself as seen above.

To compare a table against itself, you have to create two “versions” of the table and use
them as if they were two different tables. The join condition in this case will compare an
employee’s manager number (MGR) against their manager’s employee number (EMPNO).

To list employees whose salary exceeds their manager's:

SELECT E.ENAME AS WORKER, E.SAL, M.ENAME AS MANAGER, M.SAL


FROM EMP E, EMP M
WHERE E.MGR = M.EMPNO
AND E.SAL > M.SAL;

14.6 Outer Joins

If a row in one of the tables does not satisfy the join condition, that row ordinarily will not
appear in the query's result. For example, department 40 in the table DEPT has no matching
employees in the table EMP. Therefore, the result of a join on DEPT and EMP would not
include department 40.

If you do want to display those department rows that have no matching employees, use the
outer join operator (a plus sign enclosed in parentheses) directly after the column that will
generate blanks in the join condition.

As an example, to join the emp and bonus table:

SELECT DEPTNO, EMP.ENAME, EMP.JOB, BONUS.COMM


FROM EMP, BONUS
WHERE EMP.ENAME = BONUS.ENAME (+);

List the employee names (ename) and department details for all departments, whether they
have employees or not:

SELECT DEPT.DEPTNO,DNAME, JOB,


ENAME FROM DEPT, EMP
WHERE DEPT.DEPTNO = EMP.DEPTNO (+)
ORDER BY DEPT.DEPTNO

List the department details for all departments with no employees:

SELECT DEPT.DEPTNO,DNAME
FROM DEPT, EMP
WHERE DEPT.DEPTNO = EMP.DEPTNO (+)
AND EMP.DEPTNO IS NULL;

 Remove the outer join symbol for all the above queries and note what the differences
are.

Note, the SQL Standard now includes ANSI joins, which will be introduced later in the
database modules.

Introduction to Oracle and SQL Page – 43


15 ARITHMETIC EXPRESSIONS AND GROUP FUNCTIONS

15.1 Arithmetic Operators

Arithmetic expressions can be included in an SQL command. The following operators may be
used in arithmetic expressions:
+ plus

- minus

* multiply

/ divide
Parentheses may be used in the arithmetic expressions.
15.2 Some Example Queries Involving Arithmetic Expressions

To calculate total monthly compensation (salary plus commission) for every salesperson,
ordered by compensation:

SELECT ENAME, SAL, COMM, SAL + COMM AS total_sal


FROM EMP
WHERE JOB = 'SALESMAN'
ORDER BY total_sal DESC;

Note, when creating new columns, i.e., the sum of SAL+COMM is creating a temporary new
column, the column does not have an actual name. If you wish to refer to this column in an
order by clause then you can either repeat the expression again, give the new column an
alias as seen above or refer to the column's position in the select list, which in this case is
the fourth one.

To list employees whose commission is greater than 25% of their salary:

SELECT ENAME, SAL, COMM FROM EMP


WHERE COMM > 0.25 * SAL;

To calculate total annual compensation for all salespeople:

SELECT ENAME, SAL, COMM, 12 * (SAL + COMM)


FROM EMP
WHERE JOB = 'SALESMAN';

15.3 Arithmetic Functions

The following arithmetic functions can be used in SQL commands:

Function Returns

ABS(X) absolute value of X

CEILING(X) smallest integer > X

Introduction to Oracle and SQL Page – 44


FLOOR(X) largest integer < X

MOD(X,N) remainder of X divided by N

ROUND(X,N) X rounded to N places

SIGN(X) if X<0, -1; if X=0, 0; if X>0, 1

SQRT(X) square root of X

where X is an attribute name and N is an integer.

Note that when an expression or individual function refers to a column that contains a null
value, the result is also null.

15.4 Group Functions

The following are group functions.


 AVG(X)
 COUNT(X)
 MAX(X)
 MIN(X)
 SUM(X)

where X can be any attribute name, e.g., AVG(sal).

In general group functions ignore null values.

15.5 Some Example Queries Involving Group Functions

To find the average salary of clerks:

SELECT AVG(SAL)
FROM EMP WHERE JOB = 'CLERK';

 To find the total salary and total commission of salespeople:

SUM(SAL) SUM(COMM)
---------- ----------
5600 2200

 To find the average annual pay of all salespeople:

12*AVG(SAL+COMM)
----------------
23400

 To find the highest and lowest salaries and the difference between them:

MAX(SAL) MIN(SAL) DIFFERENCE


---------- ---------- ----------
5000 800 4200

 To count the number of employees:

Introduction to Oracle and SQL Page – 45


COUNT(*)
----------
16

 To count the number of different jobs held by employees in department 30:

JOB_COUNT
----------
3

15.6 Subqueries

A subquery, or nested query is a query within a query. Subqueries are usually used in the
WHERE part of the SQL statement, though some books now use nested expressions in place
of column and table names, for example:

SELECT * FROM

(SELECT * FROM EMP);

Subqueries are often used where you need to perform a calculation, or a check of some
sort, where the result is then passed to the outer query. Subqueries can be used with
comparison operators such as =, <, >, >=, <= etc. If using equals, only one result must be
returned from the subquery, if more than one value is returned then either the IN or NOT IN
comparison operator must be used instead of equals.

For example, the outer join query above that showed departments with no employees could
be written as this instead:

SELECT DEPTNO, DNAME


FROM DEPT
WHERE DEPTNO NOT IN (SELECT DEPTNO FROM EMP);
 Use a subquery to list all employees who are involved in a project:

ENAME DEPTNO
---------- ----------
FORD 20

15.7 A Group Function in a Subquery

If you include group functions in a SELECT command, you may not select individual results
as well. For instance if you wanted to find the name of the employee who receives the
highest salary, you cannot enter:

SELECT ENAME, MAX(SAL) .....

because this mixes individual and group functions. Instead you have to use a subquery:

SELECT ENAME, JOB, SAL FROM EMP


WHERE SAL = (SELECT MAX(SAL) FROM EMP);

Show the details of the latest employee to be hired by the company:

SELECT ENAME, JOB, SAL FROM EMP

Introduction to Oracle and SQL Page – 46


WHERE HIREDATE =
(SELECT MAX(HIREDATE) FROM EMP);

This should return the row you inserted for yourself in section 12.

15.8 Summarising Several Groups - GROUP BY

To summarise several groups within the same query, use the GROUP BY clause. This clause
divides a table into groups of rows so that the rows in each group have the same value in a
specified column. You can select groups to display by using the HAVING clause with the
GROUP BY clause.

The format of the GROUP BY clause is:

GROUP BY column name


HAVING condition expression involving some property of the group
(i.e., a group function) and a constant

15.9 Some Example Queries Using GROUP BY

To list the average salary for each department:

SELECT DEPTNO, AVG(SAL)


FROM EMP
GROUP BY DEPTNO;

To list the average salary for each department, whose average salary is greater than 2500:

SELECT DEPTNO, AVG(SAL) FROM EMP


GROUP BY DEPTNO
HAVING AVG(SAL) > 2500;

 To find the average annual salary of the non-managerial staff in each department:

SELECT DEPTNO, 12*AVG(SAL) FROM EMP

WHERE JOB NOT IN ('MANAGER', PRESIDENT')

GROUP BY DEPTNO;

DEPTNO 12*AVG(SAL)
---------- -----------
30 16100
20 23700
10 37800

To count the employees and calculate the average annual salary for each job group in each
department:

SELECT DEPTNO, JOB, COUNT(*), 12*AVG(SAL)


FROM EMP
GROUP BY DEPTNO, JOB;

(COUNT(*) counts the number of rows in the table satisfying the query).

Introduction to Oracle and SQL Page – 47


To list the average annual salary for all job groups with more than two employees:

SELECT JOB, COUNT(*), 12 * AVG(SAL)


FROM EMP
GROUP BY JOB
HAVING COUNT(*) > 2;

To list the total annual salary and commission for all job groups in each department:

SELECT DEPTNO, JOB, SUM(SAL+NVL(COMM,0)) AS SUMMARY


FROM EMP
GROUP BY DEPTNO, JOB;

NVL is a function that will convert nulls to a specific value (try the query without the function
to see the difference made).

16 DISPLAYING AND WORKING WITH DATE VALUES

16.1 Date Arithmetic

You can perform arithmetic operations on date fields.

The operations you can use are:

date + number

date - number

date - date

To find the review dates of employees in department 20 where the review occurs one year
after the hiredate:

SELECT ENAME, HIREDATE,


HIREDATE + 365 AS REVIEW
FROM EMP
WHERE DEPTNO = 20;

Note, AS REVIEW will give the new derived column a name. If omitted, Oracle will use the
expression instead. The AS column-name clause can be used after any column name if you
wish to rename it.

16.2 Date Functions

The following table lists some date functions available in Oracle (where D, D1, D2 are date
fields or date strings and N is an integer):

Function Example Results


ADD_MONTHS(D,N) ADD_MONTHS(hiredate,3) date D plus N months. Use a
negative number to subtract
months

Introduction to Oracle and SQL Page – 48


GREATEST(D1,D2) GREATEST(hiredate, later of D1 and D2 (column
'11-JUL-2014') names usually used here)
LEAST(D1,D2) LEAST(hiredate,'01-JAN-2014') earlier of D1 and D2 (column
names usually used here)
LAST_DAY(D1) LAST_DAY('01-FEB-2014') date of the last day of given
month
MONTHS_BETWEEN MONTHS_BETWEEN(sysdate, number of months between
(D1,D2) hiredate) D1 and D2
NEXT_DAY(D, 'a day') NEXT_DAY('01-JAN-2014', date of next particular day of
'FRIDAY') week after given date
TO_CHAR(D, TO_CHAR(hiredate, 'MM/DD/YY') changes format displayed to
'MM/DD/YY') MM/DD/YY
SYSDATE SYSDATE Current date and time

There are a number of other date conversion formats that can be used with TO_CHAR,
some examples are:

Format Display

blank (without TO_CHAR) 25-DEC-18

MM/DD/YY 12/25/18

DD.MM.YYYY 25.12.2018

Month DD, YYYY December 25, 2018

DY DD MON YY SUN 25 DEC 18

Day Mon DD Sunday Dec 25

Day Month DD, YYYY Sunday December 25, 2018

DY DD Month YYYY SUN 25 December 2018

ddth "of" Month 25th of December

HH:MM:SS 12:30:29 (retrieves time element)

Note, always insert dates using the 4-digit year format, otherwise you may find ’10-AUG-11’
becomes ’10-AUG-1911’!

16.3 Some Example Queries Involving Date Functions

To find the review dates of employees hired in the last 90 days where reviews take place
one year after hire:

SELECT ENAME, TO_CHAR(HIREDATE ,‘MM/DD/YYYY’) AS hiredate,


TO_CHAR(SYSDATE, ‘HH:MI:SS’) AS TIME,
TO_CHAR(HIREDATE + 365, ‘ddth “of” Month’) AS reviewdate
FROM EMP

Introduction to Oracle and SQL Page – 49


WHERE HIREDATE + 90 > SYSDATE;

How many days are left in the current month:

SELECT SYSDATE,
LAST_DAY(SYSDATE) AS "Last",
LAST_DAY(SYSDATE) – SYSDATE AS "Days Left"
FROM DUAL;

DUAL is a special one-row, one-column "dummy" table that can be used when performing
calculations, or retrieve system data, as above, rather than extracting data from any
particular user-defined tables.

Show the earliest, latest and last date of the hiredates and current dates in the emp table:

SELECT LEAST(HIREDATE, SYSDATE) AS EARLIER,


GREATEST(HIREDATE, SYSDATE) AS LATEST,
LAST_DAY(HIREDATE) AS LAST_DAY FROM EMP;

 To list each employee's hiredate and review date, where the review date occurs 6
months after hiredate:

EMPNO ENAME HIREDATE REVIEW_DA


---------- ---------- --------- ---------
7839 KING 17-NOV-81 17-MAY-82
7566 JONES 02-APR-81 02-OCT-81
7788 SCOTT 09-DEC-82 09-JUN-83
7876 ADAMS 12-JAN-83 12-JUL-83
7902 FORD 03-DEC-81 03-JUN-82
7369 SMITH 17-DEC-80 17-JUN-81
7698 BLAKE 01-MAY-81 01-NOV-81
7499 ALLEN 20-FEB-81 20-AUG-81
7521 WARD 22-FEB-81 22-AUG-81
7654 MARTIN 28-SEP-81 28-MAR-82
7844 TURNER 08-SEP-81 08-MAR-82
7900 JAMES 03-DEC-81 03-JUN-82
7782 CLARK 09-JUN-81 09-DEC-81
7934 MILLER 23-JAN-82 23-JUL-82
7955 WILSON 22-APR-88 22-OCT-88
9000 GARVEY 23-JUL-08 23-JAN-09

16 rows selected.

 List each employee's name and month of hire only:

SELECT ENAME, TO_CHAR(HIREDATE,'MON') AS MONTH FROM EMP;

16.4 Inserting Date Values

When you enter a value into a date field, it must be in the standard format. Character
expression can be converted by using the TO_DATE function.

For example:

INSERT INTO EMP

Introduction to Oracle and SQL Page – 50


VALUES (7657, 'MASON', 'ANALYST', 7566,
TO_DATE('11/07/2008',’DD/MM/YYYY’), 3400, 0, 20);

COMMIT;

16.5 The Current Date

To enter the current date, use the SYSDATE system variable.

To enter a new employee just hired:

INSERT INTO EMP


VALUES (7659, 'FOX', 'ANALYST', 7566,
SYSDATE, 2900, 0, 20);

COMMIT;

 To list this new employee's name and hiredate, with the hiredate shown in the
format of the Month in full, day and year:

ENAME HIREDATE
---------- -------------------
FOX 23RD JULY 2008

17 WORKING WITH CHARACTER VALUES

17.1 Character Expressions

You can combine character columns and constants into char expressions with the
concatenation operator: || (two broken pipes).

For example, to join the DNAME and LOC columns from the DEPT table into a single column,
separating the two values with a blank space, a hyphen and another blank space:

SELECT DNAME || ' - ' || LOC FROM DEPT;

 To join the ENAME and JOB columns from the EMP table, separating the two values
with a space, colon(:) and another blank space and give the combined columns a
new name:

EMP_JOBS
----------------------
KING : PRESIDENT
JONES : MANAGER
SCOTT : ANALYST
ADAMS : CLERK
FORD : ANALYST
SMITH : CLERK
BLAKE : MANAGER
ALLEN : SALESMAN
WARD : SALESMAN
MARTIN : SALESMAN
TURNER : SALESMAN

Introduction to Oracle and SQL Page – 51


JAMES : CLERK
CLARK : MANAGER
MILLER : CLERK
WILSON : CLERK
GARVEY : MANAGER
MASON : ANALYST
FOX : ANALYST

18 rows selected.

17.2 Character Functions

SQL has many character functions. The following are the ones used most often. Col can
represent either a column or character string.

Introduction to Oracle and SQL Page – 52


Function Example Result
CONCAT CONCAT(CONCAT Returns col1 concatenated with col2.
(col1, col2) (forename, ' '), surname) This function is equivalent to the
concatenation operator (||).
The example uses the operator twice to
join the forename and surname with a
space in between.
DECODE(col, DECODE (GRADE,'A',14,'B', Translates letter grades in the grade
'value', new_value 11,'C',8,'D',5,0) column into grade points.
[,'value', The last number represents the default
new_value[,…]], value.
default_value)
INITCAP(col) INITCAP(surname) Capitalises the first letter of each word
in surname
INSTR(col, INSTR(address,' ') Returns the position of the first blank
'search-string') space in address
LENGTH(col) LENGTH(surname) Returns the character length of
surname
LOWER(col) LOWER(surname) Converts upper-case characters in
surname to lower-case
LTRIM(col [,set]) LTRIM(surname) Removes characters from the left of col,
with all the leftmost characters that
appear in set removed; set defaults to a
single blank if omitted.
RTRIM(col [,set]) RTRIM(address) Similar to LTRIM but removes
characters on the right.
SOUNDEX(col) SOUNDEX('Des Moines') Returns a value that represents the
spoken sound of 'Des Moines'
SUBSTR(col, m [, SUBSTR(surname,1,2) Returns part of the column, beginning
n]) at character m, for n characters long.
This example gives the first two letters
of surname.
M can be positive, or negative. If
positive the count starts from the
beginning of the column, if negative, it
counts backwards from the end of the
column. If n is omitted, all characters to
the end of the column are returned.
UPPER(col) UPPER(surname) Translates lower-case characters in
surname to capital letters
 Suppose you wish to display records from the EMP table, but cannot remember
whether the employees’ names are in upper, lower or mixed case. Which function is
necessary to make sure you find the right records and display them correctly?

To select and display an employee name in upper case and job capitalised:

SELECT UPPER(ENAME), INITCAP(JOB)


FROM EMP
WHERE LOWER(ENAME) = 'ward';

Introduction to Oracle and SQL Page – 53


 Note, the value being compared in the WHERE clause should match the function,
e.g., if the last line was changed to WHERE LOWER(ENAME) = 'WARD' it would
retrieve any rows. Can you see why?

 To select employees with names sounding like SMYTH:

ENAME
----------
SMITH

HINT: Both the attribute and string 'SMYTH' need to be converted to their phonetic values
for this to work.

18 CONTROL COMMANDS

Control commands can be used to:

 Format reports
 Edit SQL commands
 Store and retrieve queries
 Get help

Some of these have been introduced in previous sections.

18.1 Formatting Reports

When saving the query results, you may wish to format them to make them more
meaningful. For example:

 Change column headings


 Format number, character and date columns
 Copying, listing and resetting column display attributes
 Suppress duplicate values and inserting spaces in the output for clarity
 Setting page dimensions
 Placing titles at the top and bottom of reports (headers and footers)
 Display column values, or the current date, or page numbers in the titles
 Calculating and printing summary lines (totals, averages, minimums, etc.)
 Listing and removing spacing and summary line definitions
Displaying column values and the current date or page number in your titles

Some of these commands have been introduced already, but the following sections will
introduce some new formatting commands.

18.2 Some basic report formatting commands

The format of the output can be changed via various control commands.

Note, formatting commands do not need to be terminated by a semi-colon. The formatting


commands are not part of the SQL standard and are an extra feature provided by the
database vendor. Each database management system (DBMS) has its own set of formatting

Introduction to Oracle and SQL Page – 54


features, for example, the way Oracle formats a report will be different from FoxPro or
Access. The extra features provided by Oracle are called SQL*Plus.

Column headings can be given more user-friendly names with the COLUMN command. This
can be used to change the name of the column or reformat the column data in a query.

18.2.1 Changing Column Headings

SQL*Plus uses column or expression names (e.g., EMPNO, or COUNT(*)) as the default
column name when outputting results. Column names can be short and cryptic and
expressions can be hard to understand.

To define a more useful column heading, you need to use the HEADING clause of the
FORMAT command.

The format is:

COLUMN column_name HEADING new_column_name

Note:

If the column to be renamed is an expression, e.g., SUM(sal), then the column_name is


substituted by the expression.

If spaces are needed in the new name, enclose the name in either single or double quotes,
e.g., "Student Name".

The new heading is case sensitive, that is if you type it in lower/mixed case, it will appear
exactly as typed, e.g., Student_Code.

To display the column heading over more than one line, use a vertical bar (|) where you
want to begin a new line, e.g., "Course|Code".

18.2.2 Changing Column Width

The displayed width of a VARCHAR2, LONG or DATE field can be changed in a report by
using the COLUMN command with a format model consisting of the letter A (for
alphanumeric) followed by a number representing the width of the column.

The structure for the FORMAT clause is:

COLUMN column_name FORMAT model

The column_name can also be an expression.

To cancel an individual formatting command:

COLUMN column_name CLEAR

or to clear all column headings:

CLEAR COLUMNS

To see what column definitions are in action type:

Introduction to Oracle and SQL Page – 55


columns

For example

To list information about employees who work for Blake:

COLUMN DEPTNO HEADING DEPARTMENT


TTITLE 'WILLIAM BLAKE || LIST OF EMPLOYEES'

SELECT ENAME, JOB, MGR, SAL, COMM, DEPTNO


FROM EMP WHERE MGR = 7698;

Notice the difference from normal. In a report the formatting commands should also be
cancelled afterwards, otherwise they will remain active until you exit Oracle.

To cancel the formatting commands:

COLUMN DEPTNO CLEAR


TTITLE OFF

BTITLE can be used to display a title at the end of the report. It displays the title centred
on a single line with no date or page number added.

18.2.3 Formatting Number Columns

When working with numerical data, or calculated fields, for example, the SUM or COUNT of
a particular field, the format model needs to reflect numerical data. A format model is a
representation of the way you want the numbers in the column to appear, using 9's to
represent the digits.

The format for numerical data is similar to before:

COLUMN column_name FORMAT model

The format model can be a combination of the following:

Element Example(s) Description

9 9999 Determines the display width by the number of digits


entered. Does not display leading zeros.
Note, if you give fewer digits than the size of the
number, only ####'s will be displayed!
0 0999 Displays leading zeroes.
9990 Displays zero instead of a blank when a value is zero
$ $9999 Prefixes a dollar sign to a value.
(No £ signs!)
B B9999 Display a zero value as a blank
MI 9999MI Displays "-" after a negative value
PR 999PR Displays a negative value in angle brackets

Introduction to Oracle and SQL Page – 56


Comma 9,999 Displays a comma in the position indicated
Period 99.99 Aligns the decimal point in the position indicated
V 999V99 Multiples the value by 10n, where n is the number of
"9's" after the "V"
EEEE 9.999EEEE Displays in scientific notation (format must contain
exactly four "E's"
DATE Date Displays value as a date in the MM/DD/YY format. Used
to format a number that represents a Julian date.

A Julian date is the number of days elapsed since Jan 1,


4712 BC. Julian dates allow continuous dating from a
common reference.

You will find these formats useful for expressions involving COUNTs or SUMs.

For example type in the following and re-run the previous query:

COLUMN SAL FORMAT $9999.99


COLUMN COMM FORMAT $9999.99

18.3 Organising rows into groups: the BREAK command

The BREAK command can organise the rows of a report into groups and specify an action
that a query is to take between groups.

To print a personnel report on the entire company with breaks where the value of DEPTNO
changes and to skip a line in the report at each break:

BREAK ON DEPTNO SKIP1;


TTITLE 'ACME WIDGET PERSONNEL REPORT'
BTITLE 'COMPANY CONFIDENTIAL'

SELECT DEPTNO, ENAME, SAL


FROM EMP
ORDER BY DEPTNO;

A BREAK definition can be cleared by

CLEAR BREAK

Note that to make sensible use of the BREAK command the rows must be in a specific order.
The order in which rows are displayed can be controlled by the ORDER BY command (see
section 16).

18.4 Some useful BREAK formats

Generic Format Examples

BREAK ON column name BREAK ON DEPTNO

Introduction to Oracle and SQL Page – 57


BREAK ON column name ON column BREAK ON MGR ON DEPTNO
name ON column name

BREAK ON ROW (Breaks whenever a row is selected)

BREAK ON PAGE (Breaks between pages of a report)

BREAK ON REPORT (Breaks at the end of the report)

18.5 Some useful actions at BREAK

BREAK ON ....... SKIP (n) Skips N number of lines

BREAK ON ........ PAGE Begins a new page

18.6 Computing subtotals at breaks

If you organise the rows of a report into groups with the BREAK command, you can make a
query perform various computations on the rows in each group. The format of the
COMPUTE command is:

COMPUTE function_name OF column_name, column_name ON


break_column name

where the function name can be SUM, MIN, MAX, AVG, STD VAR, or COUNT.

For example:

BREAK ON DEPTNO SKIP1


COMPUTE SUM OF SAL ON DEPTNO

SELECT DEPTNO, EMPNO, ENAME, SAL


FROM EMP
ORDER BY DEPTNO;

CLEAR BREAK

18.7 Page size commands

The following commands alter the page size and width, which are useful for printed reports.
The default values are shown first.

Function Action

SET PAGESIZE {14|n} sets the number of lines from the top title to the end of the
page. With 11 inch long paper, a value of 54 (plus a NEWPAGE
value of 6) leaves one-inch margins above and below a report.
Set PAGESIZE to 0 to suppress headings, page breaks, titles,
the initial blank line, and other formatting information

Introduction to Oracle and SQL Page – 58


SET NEWPAGE {1|n} sets the number of blank lines printed between the beginning
of each page and the top title. A value of 0 sends a formfeed
between pages and clears the screen on most terminals.

SET LINESIZE {80|n} sets the total number of characters displayed on a line before
starting a new line and controls the position of centred and
right-aligned text in TTITLE and BTITLE. The range is 1 to a
system-dependent maximum.

For example,

SET PAGESIZE 65

SET NEWPAGE 1

SET LINESIZE 100

Will print 65 lines per page, 100 characters wide and will throw one new line at the top of a
new page. For reports that will be viewed on the screen only, set the pagesize to about 40.

 Create a file which produces a report on Salesmen earning more than £3000. The
report should be headed ‘Computing Salesmen Report’ and each page should have
‘For Your Eyes Only’ at the bottom. The output should be ordered by salary. The file
should be stored in U:\salesman.sql. Save the output of the query into a file
U:\salary.txt.

19 Substitution Variables

A Substitution Variable is a user variable name preceded by one ampersand ('&') or two
ampersands ('&&'). When SQL*Plus encounters an undefined substitution variable, it will
prompt the user for a value.

E.g. if the following is typed:

SELECT count(*) FROM &TABLENAME;

SQL*Plus will display the prompt:

Enter value for tablename:

Reply with the name of one of your own tables, such as EMP.

This command is useful for queries that are going to be saved and reused with different
values.

If you use a variable with one ampersand, SQL*Plus does not define the variable when it
prompts for a value. Thus, if the same command is executed later, it will prompt again for
another value. However, if you use a variable with two ampersands, SQL*Plus does define
the variable, so when the command is later executed, it will not prompt for a value again,
instead it will use the previous value.

Introduction to Oracle and SQL Page – 59


 If the variable is for a character or date field, then the ampersands must be enclosed
in quotes, any wildcards can be added also.

For example, to count the employees from a particular department:

select count(empno) from emp


where deptno = '&deptno';

When prompted for the deptno, type in a department number. Type RUN to run the
command again and try a new department.

You can call the substitution variables anything you like, but it makes more sense to call
them a similar name to the field they are related to.

Numeric fields do not need the quotes round the substitution variable.

19.1 Using Parameters with the START Command

Parameters can be passed from the command line when using the START or @ command, in
the form of:

start [drive:\folder\]filename parameter1 parameter2

With this, a SQL query can be saved to a file that lets you enter one or more parameters on
the command line after the filename. This is useful if you want to run the same query
several times from a batch file, but with different parameters.

A batch file is where several queries can be invoked, one after the other, from the same file.

This is done by placing an ampersand ('&') followed by a number in the SQL query. Each
time the query is run, each '&1' is replaced by the first parameter on the command line,
each '&2' is replaced by the second parameter and so forth.

Save the following to a file called batch:

select * from emp


where deptno = &1;

To run this command, type:

@u:\batch 10

This will list the above details for employees in department 10.

 Select employees with a given name, where name is prompted for:

The output for this query will depend on which department has been chosen

Introduction to Oracle and SQL Page – 60


20 VIEWS IN ORACLE

20.1 Creating a view

A view is like a window through which you can view or change information tables. A view
allows you to see as a single table parts of one (or more than one) table(s).

To define a view of department 10 of the EMP table:

CREATE VIEW EMP10 AS


SELECT EMPNO, ENAME, JOB
FROM EMP
WHERE DEPTNO = 10;

Once EMP10 is created, it can be used as any other table. Any updates are automatically
applied to the 'base' tables, though there are restrictions covering updates to views, which
will be covered in later database modules.

Column names take on the names from the base table; however these can be changed by
including the new column names after the View-Name, for example, to create a view for
department 20, renaming all the columns:

CREATE VIEW EMP20 (EMPNUMBER, EMPLOYEE, POSITION) AS


SELECT EMPNO, ENAME, JOB
FROM EMP
WHERE DEPTNO = 20;

Views can be based on more than one table.

To create a view joining EMP to EMPPROJ (this assumes you have created EMPPROJ and
updated EMP as directed earlier):

CREATE VIEW PROJSTAFF


( EMPLOYEE, PROJECT, PROJECT_NUMBER) AS
SELECT ENAME, PNAME, EMPPROJ.PROJNO
FROM EMP, EMPPROJ
WHERE EMP.PROJNO = EMPPROJ.PROJNO;

Since views occupy no storage space they are sometimes called "virtual tables".

There are two main reasons to use views:

 Security

Why?

 Convenience

Why?

Introduction to Oracle and SQL Page – 61


20.2 Deleting a view

A view can be deleted with the DROP command.

DROP VIEW viewname

For example:

DROP VIEW EMP10;

21 INDEXING TABLES IN ORACLE

21.1 Creating an index

A table index should include the columns you use most frequently in search conditions.

To index the ENAME column of the EMP table:

CREATE INDEX EMP_ENAME


ON EMP(ENAME);

21.2 Using an index to enforce uniqueness

The primary key of the EMP table is EMPNO, however there may also be another candidate
key, for example the National Insurance Number of every person is also unique.

To create a unique index on a column such as this you could:

CREATE UNIQUE INDEX EMP_NI ON EMP(NI);


OR
Specify it with the facilities available in the SQL CREATE TABLE command. This is
outside the scope of an introductory course in SQL.

Oracle Version 6, a previous release of their Relational Database Management System


(RDBMS), did not implement primary keys or constraints. You could specify them but
Oracle did very little with your specifications. Since Version 7 Oracle fully supports primary
keys, foreign keys and specified constraints as shown in previous sections with the creation
of the sample database tables and the SQL script shown in Appendix A.

21.3 Deleting an index

To delete an index use the command DROP.

DROP INDEX EMP_EMPNI ON EMP

21.4 General rules for indexes

If a table has more than a few hundred rows, index it

Introduction to Oracle and SQL Page – 62


Try not to create more than two or three indexes on a table

Choose which columns to index based on frequency of use

DO NOT Create a unique index on primary keys, specify the primary key constraint at table
creation time, or alter the table to add the primary key constraint. The former is preferable.

22 DATA DICTIONARY

22.1 The Data Dictionary table

The data dictionary describes tables, columns, indexes and other objects in the database.
The dictionary is held in the form of tables that can be read like any other tables. You
cannot change any data in these tables manually (i.e. Using SQL INSERT, DELETE and
UPDATE statements).
Oracle implicitly changes these tables based upon your actions, such as:
 Creating, deleting or updating a table
 Creating, deleting or updating a view
 Creating, deleting or updating a index
 Creating, deleting or updating a trigger
 Creating, deleting or updating a procedure, function or package

The dictionary table DICTIONARY describes the tables that make up the data dictionary.

To display the names and descriptions of dictionary tables:

SELECT * FROM DICTIONARY;

22.2 Useful dictionary tables

TABLE NAME DESCRIPTION


USER_CONSTRAINTS Describes information regarding the constraint on tables
defined by the user.
USER_CONS_COLUMNS Describes information about the columns involved in
constraints defined by the user.
USER_ERRORS Describes the errors for all triggers and procedures that
the application developer has attempted to register to the
database.
USER_INDEXES Lists the indexes that you own and those that other users
have defined for tables that you own.
USER_IND_COLUMNS Defines the attributes involved in an index, especially
useful for composite indexes.
USER_SEQUENCES Descriptions of all the users sequences.
USER_SOURCE Describes all the Procedures, Functions and Packages
defined by the user, including the source code.
USER_TABLES Describes all the tables that you own.
USER_TAB_COLUMNS Describes the names and column definitions of tables that
you own.
USER_TRIGGERS Defines all the triggers defined by the user, including the
source code.
USER_TRIGGER_COLS Defines the columns involved for a user defined trigger.

Introduction to Oracle and SQL Page – 63


USER_VIEWS Lists the subqueries that define the views you own.

For example:

SELECT TABLE_NAME, INDEX_NAME FROM USER_INDEXES


ORDER BY TABLE_NAME

Lists what indexes you have on each table.

The dictionary tables can contain a lot of information, use DESCRIBE tablename to see what
columns each dictionary table has before querying them.

 Congratulations, you have now finished the main body of the workbook. Take a well-
deserved coffee break!

Introduction to Oracle and SQL Page – 64


Advanced Features
23 Advanced SQL Features: PL/SQL AND SQL/2

 Note this section covers some of the more advanced features of SQL. It is not
essential to the module that you complete this section; so only continue if you have
time.

23.1 Introduction to PL/SQL

PL/SQL is Oracle's extension to SQL that allows the database application developer to write
block structured procedural code to interrogate the database. It allows the programmer to
define variables and complex control structures.

PL/SQL can be incorporated into the suite of applications that Oracle provide to support
application development, such as SQL*Forms. As PL/SQL is available in the Oracle range of
products the programmer does not need to learn different facilities for each Oracle product.

The following sections cover PL/SQL very briefly. An extensive examination of PL/SQL is
outside the scope of an introductory course in SQL.

It's main use is the development of routines that can be shared by application developers.

23.2 An Introduction to Database Triggers

Database triggers are programs that are executed after a specific event has happened on a
target table, such as inserting a row. They are commonly used for:

 Audit purposes
 Security
 Complex Integrity Checks that cannot be handled by constraints

If you refer back to the employee table EMP and salary grade table SALGRADE you can see
that there exists a complex relationship, one not based on Foreign Keys. At present it is
possible to insert a row in the EMP table whose salary is not covered by the SALGRADE
table. To enforce such a check you can create a trigger and store it within the database.

Introduction to Oracle and SQL Page – 68


The following PL/SQL script enforces such a check:

create trigger EMP_AFTERCHANGE


after INSERT
or UPDATE of SAL
on EMP
for each row

DECLARE
salarygrade NUMBER;

BEGIN
select grade
into salarygrade
from SALGRADE
where LOSAL <= :new.sal
and HISAL >= :new.sal;

EXCEPTION
when NO_DATA_FOUND then
raise_application_error(-20001,
'Salary given is not included in the salary grades');

when OTHERS then


raise_application_error(-20000,
'Error has occured in EMP_AFTERCHANGE trigger');
END;
/

This PL/SQL trigger declares a numeric variable to store a specific salary grade that the
employee earns. If this query returns no values then the EXCEPTION code is fired. In this
block a check is to see if the pre-defined error NO_DATA_FOUND has occurred or the catch
all error has occurred. If so then the pre-defined raise_application_error procedure is called
with a suitable error code and message. This procedure rollbacks any of the changes in the
current transaction. The error codes must be in the range -20000 and 20999.

If you now attempt to enter a row or update a row in the EMP table that does not have a
corresponding salary grade Oracle will notify you of the error.

INSERT INTO EMP


VALUES
(1111,'TEST’,’JOB',NULL,'21-AUG-94',10000,NULL,10, NULL);

Whenever you create a trigger or procedure you may get compilation errors. To give full
details of the most recent Trigger or Procedure compilation errors enter the SQL command:

SHOW ERRORS;

Introduction to Oracle and SQL Page – 69


23.3 An Introduction to Database Procedures

Whereas Triggers are fired based on an event occurring, Procedures are programs that must
be explicitly called. These too can be stored in the database and made available to
application developers. The following PL/SQL script takes a number of parameters and
inserts a row into the EMP table.

create procedure
create_emp( nm_empno NUMBER,
vc_ename VARCHAR2,
vc_job VARCHAR2,
nm_mgr NUMBER,
dt_hiredate DATE,
nm_sal NUMBER,
nm_comm NUMBER,
nm_deptno NUMBER)
as
BEGIN
insert into EMP
values (nm_empno,vc_ename,vc_job,nm_mgr,
dt_hiredate,nm_sal,nm_comm,nm_deptno
);
END create_emp;
/

To execute this procedure you can type (note it must be typed as one line):

execute
create_emp(1234,'SMITH','MANAGER',NULL,SYSDATE,2000,NULL,10
);

The parameters in procedures may also be given default values.

Check the EMP table to see that the new row has been added.

Introduction to Oracle and SQL Page – 70


Appendices
APPENDICES
Appendix A Oracle Setup Code

host echo "Oracle Version 12c"


host echo "Building Demonstration tables. Please wait..."
rem
rem Emp TABLE
rem =========
rem
rem 1. Primary key (Enforces NOT NULL too)
rem 2. Ensure all data entered in upper case.
rem 3. Foreign key must be in related table or be NULL.
rem 4. Salary must be greater than 0
rem 5. Commission must be greater than 0 or null.
rem

host echo "Droping previous version of demonstration tables"


DROP TABLE Emp;
DROP TABLE Dept;
DROP TABLE Bonus;
DROP TABLE Salgrade;
DROP SEQUENCE ProjSeq;
host echo "Previous Demonstration tables removed"
host echo "Building DEPT table"
CREATE TABLE Dept
(deptno NUMBER(2)
CONSTRAINT pk_dept PRIMARY KEY,
dname VARCHAR2(14) NOT NULL
CONSTRAINT uc_dname CHECK (dname=UPPER(dname)),
loc VARCHAR2(13)
CONSTRAINT uc_loc CHECK (loc=UPPER(loc))
);

rem Now insert the data


rem
host echo "Inserting data into DEPT table"
INSERT INTO Dept VALUES
(10,'ACCOUNTING','NEW YORK');
INSERT INTO Dept VALUES (20,'RESEARCH','DALLAS');
INSERT INTO Dept VALUES
(30,'SALES','CHICAGO');
INSERT INTO Dept VALUES
(40,'OPERATIONS','BOSTON');

host echo "Building Emp table"


CREATE TABLE Emp
(empno NUMBER(4)
CONSTRAINT pk_emp PRIMARY KEY,
ename VARCHAR2(10) NOT NULL
CONSTRAINT uc_ename CHECK (ename = UPPER(ename)),
job VARCHAR2(9) NOT NULL
CONSTRAINT uc_job CHECK (job = UPPER(job)),
mgr NUMBER(4)
CONSTRAINT fk_mgr references Emp(empno),
hiredate DATE,
sal NUMBER(7,2) NOT NULL
CONSTRAINT BD_SAL CHECK (SAL > 0),
comm NUMBER(7,2)
CONSTRAINT BD_COMM CHECK (COMM >= 0),
deptno NUMBER(2)

Appendices Page - 74
CONSTRAINT FK_DEPTNO references DEPT(DEPTNO)
);

host echo "Inserting data into Emp table"


rem Management Structure is as follows:-
rem
rem LEVEL EmpLOYEE JOB
rem =========================================
rem
rem 1 KING PRESIDENT
rem 2 JONES MANAGER
rem 3 SCOTT ANALYST
rem 4 ADAMS CLERK
rem 3 FORD ANALYST
rem 4 SMITH CLERK
rem 2 BLAKE MANAGER
rem 3 ALLEN SALESMAN
rem 3 WARD SALESMAN
rem 3 MARTIN SALESMAN
rem 3 TURNER SALESMAN
rem 3 JAMES SALESMAN
rem 2 CLARK MANAGER
rem 3 MILLER

INSERT INTO Emp VALUES


(7839,'KING','PRESIDENT',NULL,'17-NOV-1980',5000,NULL,10);
INSERT INTO Emp VALUES
(7566,'JONES','MANAGER',7839,'2-APR-1991',2975,NULL,20);
INSERT INTO Emp VALUES
(7788,'SCOTT','ANALYST',7566,SYSDATE-85,3000,NULL,20);
INSERT INTO Emp VALUES
(7876,'ADAMS','CLERK',7788,SYSDATE-51,1100,NULL,20);
INSERT INTO Emp VALUES
(7902,'FORD','ANALYST',7566,'3-DEC-1991',3000,NULL,20);
INSERT INTO Emp VALUES
(7369,'SMITH','CLERK',7902,'17-DEC-1990',800,NULL,20);
INSERT INTO Emp VALUES
(7698,'BLAKE','MANAGER',7839,'01-MAY-1981',2850,NULL,30);
INSERT INTO Emp VALUES
(7499,'ALLEN','SALESMAN',7698,'20-FEB-1995',1600,300,30);
INSERT INTO Emp VALUES
(7521,'WARD','SALESMAN',7698,'22-FEB-1994',1250,500,30);
INSERT INTO Emp VALUES
(7654,'MARTIN','SALESMAN',7698,'28-SEP-1993',1250,1400,30);
INSERT INTO Emp VALUES
(7844,'TURNER','SALESMAN',7698,'8-SEP-1981',1500,0,30);
INSERT INTO Emp VALUES
(7900,'JAMES','CLERK',7698,'3-DEC-1981',950,NULL,30);
INSERT INTO Emp VALUES
(7782,'CLARK','MANAGER',7839,'09-JUN-1989',2450,NULL,10);
INSERT INTO Emp VALUES
(7934,'MILLER','CLERK',7782,'23-JAN-1985',1300,NULL,10);
INSERT INTO Emp VALUES
(8000,'REEVE','MANAGER',7839,'14-MAR-81',4000,0,90);
host echo "Building Salgrade table"

CREATE TABLE Salgrade


(grade NUMBER
CONSTRAINT PK_GRADE PRIMARY KEY,
losal NUMBER NOT NULL
CONSTRAINT BD_LOSAL CHECK (losal > 0),

Appendices Page - 75
hisal NUMBER NOT NULL,
CONSTRAINT BD_HISAL CHECK (hisal >= losal)
);

host echo "Inserting data into Salgrade table"


INSERT INTO Salgrade VALUES (1,700,1200);
INSERT INTO Salgrade VALUES (2,1201,1400);
INSERT INTO Salgrade VALUES (3,1401,2000);
INSERT INTO Salgrade VALUES (4,2001,3000);
INSERT INTO Salgrade VALUES (5,3001,9999);

CREATE TABLE Customer


(cno NUMBER(4), orderdate DATE, name VARCHAR2(15),
city VARCHAR2(15), country VARCHAR2(15),
pno NUMBER(4), description VARCHAR2(20),
qty NUMBER(4) CHECK (qty >= 1));

INSERT INTO Customer VALUES


(0001,'01-JAN-1997','J BOND','STOCKPORT','ENGLAND',1,'BONNET',20);
INSERT INTO Customer VALUES
(0001,'11-JUN-1997','J BOND','STOCKPORT','ENGLAND',2,'WIDGET',10);
INSERT INTO Customer VALUES
(0001,'21-APR-1998','J BOND','STOCKPORT','ENGLAND',1,'BONNET',40);
INSERT INTO Customer VALUES
(0001,'15-AUG-1998','J BOND','STOCKPORT','ENGLAND',3,'PAINT:
WHITE',4);
INSERT INTO Customer VALUES
(0002,'22-APR-1996','B
TURPIN','MANCHESTER','ENGLAND',2,'WIDGETS',41);
INSERT INTO Customer VALUES
(0002,'11-JUN-1997','B TURPIN','MANCHESTER','ENGLAND',1,'BONNET',1);
INSERT INTO Customer VALUES
(0003,'06-FEB-1996','I PERRY', 'WOLVERHAMPTON', 'ENGLAND',
5,'NAILS',60);
INSERT INTO Customer VALUES
(0003,'17-NOV-1997','I PARRY','WOLVERHAMPTON','ENGLAND',3,'PAINT:
WHITE',2);
INSERT INTO Customer VALUES
(0004,'14-JUL-1997','P FOLWER','BIRMINGHAM','ENGLAND',6,'HAMMER',1);
INSERT INTO Customer VALUES
(0004,'30-MAY-1999','P FOLWER','BIRMIGNAM','ENGLAND',7,'PAINT:
BLUE',2);
INSERT INTO Customer VALUES
(0004,'28-AUG-2000','P FOLWER','BIRMINGHAM','UNITED
KINGDOM',11,'WIDGET',40);

host echo "Demonstration tables build"


COMMIT;
DROP TABLE EmpProj;
DROP TABLE Proj;
DROP VIEW Emp10;
DROP VIEW ProjStaff;

Appendices Page - 76
Appendix B ER Diagram

Below is an ER diagram that represents how the tables fit together. Note the Customer table
is not part of this schema and is included in the booklet to show the problems of using a
poorly designed table.

Figure A-1 ER Diagram

Appendices Page - 77
Appendix C Using Oracle from Home

There are several ways to access Oracle from home, or any non-FSE lab in the University:

 Linux Server
 Instant Client (SQL*Plus)

For a summary of how to login to Oracle and frequent problems see:

http://ora-srv.wlv.ac.uk/info/

For up-to-date information on how to use the above access methods, please see:

http://ora-srv.wlv.ac.uk/info/UsingOracleAtHome.html

Appendix D Appendix D Useful SQL Websites

Beware that some websites can be tailored to a particular DBMS product, where there can
be differences in the syntax.

The W3schools have a set of useful references:


 https://www.w3schools.com/sql/sql_ref_keywords.asp
 https://www.w3schools.com/sql/sql_ref_select.asp
 https://www.w3schools.com/sql/sql_ref_insert_into.asp
 https://www.w3schools.com/sql/sql_ref_delete.asp
 https://www.w3schools.com/sql/sql_ref_create_table.asp
 https://www.w3schools.com/sql/sql_ref_constraint.asp

Oracle:
 http://ora-srv.wlv.ac.uk/oracle19c_doc/
 http://ora-srv.wlv.ac.uk/oracle19c_doc/cncpt/introduction-to-oracle-database.html
 http://ora-srv.wlv.ac.uk/oracle19c_doc/cncpt/sql.html

Appendices Page - 78
Appendix E Installing the Palo Alto VPN Client

The VPN client software gives your own PC at home the same access to servers in the
University as it would have if using the wireless network on a University campus. For
example, some servers in the Faculty of Science and Engineering can only be used from
outside the University if you are running this software.

For staff or students who need to work from home, and have requested this facility via the
IT Service Desk, the VPN client will provide access as if using a University staff desktop PC.

How to install the client

1. Start a web browser.


2. Go to https://vpn.wlv.ac.uk.
3. Log in to that web page using your standard University username and password.
Do not prefix this with the University domain (unv\), or use your email address –
it won’t work.
4. The next page will offer you a choice of downloads: for 32-bit Windows, 64-bit
Windows or Macintosh. The 32-bit Windows client will work on 64-bit systems
too, but any copy of Windows 8 or 10 will be 64-bit. Click the appropriate link.
5. Let the system install the software.
6. When the installation finishes, the VPN client will start up. The first time you use
it, it will prompt you for the portal. Enter “vpn.wlv.ac.uk”:

Classified by Max Caines at Thu, 26 Oct 2017 08:30:08 GMT Page - 79


7. Next it will ask you for your username and password, as with the web page:

8. The system should now connect, which will take typically 15 to 30 seconds. You
will find a small icon will appear in the system tray (or on the status bar at the
top of the screen on a Mac) like this:

9. To terminate the VPN client, click the icon in the system tray and the
GlobalProtect window will open like this:

10. Then click the “Disconnect” button.

Classified by Max Caines at Thu, 26 Oct 2017 08:30:08 GMT Page - 80


How to use the client

Once it’s installed, the VPN client icon will always be available in the system tray:

You can start the VPN by clicking the icon, to open the window shown below:

then clicking the “Connect” button.

Checking the client status

If you click the icon in the system tray, to open the window as above, then click the
gearwheel icon at the top right.

Classified by Max Caines at Thu, 26 Oct 2017 08:30:08 GMT Page - 81


Select “Settings” from the menu, you will see a window like the one below. This tells you
about the connection, and any errors that have occurred:

Re-authenticating

The VPN client remembers your credentials and you don’t generally have to type them in
again. However, if you change your password, it will try to use the old one, which will fail. It
will tell you that, and ask you to supply your username and password again.

Classified by Max Caines at Thu, 26 Oct 2017 08:30:08 GMT Page - 82

You might also like