Oracle-SQL 19c 2020
Oracle-SQL 19c 2020
Oracle
and
SQL
UNIVERSITY OF WOLVERHAMPTON
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.
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.
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
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.
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.
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:
Where:
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).
3 INTRODUCTION TO ORACLE
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.
The information found in this work book, can also be found online:
https://mi-linux.wlv.ac.uk/wiki/index.php/Oracle_Workbook
Before you can start using Oracle you need to register for an account.
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.
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).
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
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.
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:
This will then present you with a log on screen as shown on the following figure:
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:
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.
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
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.
The prompt SQL> means the system is waiting for you to enter a command.
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.
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.
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
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.
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.
describe dept
describe salgrade
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-
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.
FROM ..................................
WHERE .................................
For example:
SELECT * FROM EMP;
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.
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:
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).
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.
In some cases you may wish to retrieve all information in a particular table, e.g., all the
customer or employee details.
SQL allows you to restrict which fields and rows you want.
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;
Now try and retrieve the employee's name, hiredate and sal:
14 rows selected.
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.
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:
5 QUITTING ORACLE
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.
Log back into Oracle again by following sections 3.4 and 3.5.
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/
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.
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
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’
If you wish to keep a query that you have just typed in:
SAVE [drive:\folder\]filename
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
ed u:\personnel
Replace u:\ with your own drive, if using your own PC.
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.
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.
START u:\PERSONNEL
START u:\filename
@ u:\filename
GET u:\filename
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:
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
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.
Use Notepad to create a file called QUERY3, which displays the name, salary and
commission of all salesmen:
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.
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
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.
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
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.
= 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
Some example selection queries follow. Fill in the appropriate SQL in the spaces given.
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);
List information about employees in department 10 who are not managers or clerks:
List names and departments of employees who are not clerks, analysts or salesmen:
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 whose salaries are not between £1,200 and £1,400:
11 rows selected.
List names and departments of employees who are clerks, analysts or salesmen:
10 rows selected.
List names, jobs and commission of employees who are not in department 10, 30 or
40:
DEPTNO
----------
30
20
In ascending order
In descending order
Note, an ORDER BY clause is always the last clause in a SELECT statement. The format is:
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.
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.
14 rows selected.
12 MANIPULATING DATA
SQL supports Data Manipulation Commands (DML) to allow tables to be queried, updated, or
deleted.
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 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).
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.
COMMIT;
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:
1 row created.
Commit complete.
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.
[WHERE FilterCondition1
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?
- no rows selected
COMMIT;
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!
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
DATE - - Date
The following command creates a table called PROJ with three columns PROJNO, PNAME
and BUDGET. You should type this in:
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.
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:
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:
For example, to create a table EMPPROJ that records which projects an employee works on:
To create a further table that keeps a history of an employee’s expenses per project:
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.
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:
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.
To create the table BONUS and copy rows into it, type:
You can use INSERT to select rows from one table and copy them into another.
COMMIT;
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.
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.
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.
For example, to alter the BUDGET column of PROJ to accept numbers up to nine digits:
- 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 :
For example, add a column MGRPROJNO to the table PROJ (the manager of the project):
- Table altered.
All fields in the new column will be initially set to NULL. To make a column contain only non-
NULL values:
Type the following insert statements. Can you say why you are getting error messages (see
Appendix A for clues)?
Problem?
Problem?
Problems?
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).
EMP DEPT
EMPNO ENAME JOB ..... DEPTNO DEPTNO DNAME ......
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!)
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.
= Equal
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.
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.
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
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':
To find the salary and jobs of employees who earn more than Jones:
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.
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
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).
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.
List the employee names (ename) and department details for all departments, whether they
have employees or not:
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.
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:
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.
Function Returns
Note that when an expression or individual function refers to a column that contains a null
value, the result is also null.
SELECT AVG(SAL)
FROM EMP WHERE JOB = 'CLERK';
SUM(SAL) SUM(COMM)
---------- ----------
5600 2200
12*AVG(SAL+COMM)
----------------
23400
To find the highest and lowest salaries and the difference between them:
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
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:
ENAME DEPTNO
---------- ----------
FORD 20
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:
because this mixes individual and group functions. Instead you have to use a subquery:
This should return the row you inserted for yourself in section 12.
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.
To list the average salary for each department, whose average salary is greater than 2500:
To find the average annual salary of the non-managerial staff in each department:
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:
(COUNT(*) counts the number of rows in the table satisfying the query).
To list the total annual salary and commission for all job groups in each department:
NVL is a function that will convert nulls to a specific value (try the query without the function
to see the difference made).
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:
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.
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):
There are a number of other date conversion formats that can be used with TO_CHAR,
some examples are:
Format Display
MM/DD/YY 12/25/18
DD.MM.YYYY 25.12.2018
Note, always insert dates using the 4-digit year format, otherwise you may find ’10-AUG-11’
becomes ’10-AUG-1911’!
To find the review dates of employees hired in the last 90 days where reviews take place
one year after hire:
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:
To list each employee's hiredate and review date, where the review date occurs 6
months after hiredate:
16 rows selected.
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:
COMMIT;
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
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:
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
18 rows selected.
SQL has many character functions. The following are the ones used most often. Col can
represent either a column or character string.
To select and display an employee name in upper case and job capitalised:
ENAME
----------
SMITH
HINT: Both the attribute and string 'SMYTH' need to be converted to their phonetic values
for this to work.
18 CONTROL COMMANDS
Format reports
Edit SQL commands
Store and retrieve queries
Get help
When saving the query results, you may wish to format them to make them more
meaningful. For example:
Some of these commands have been introduced already, but the following sections will
introduce some new formatting commands.
The format of the output can be changed via various control commands.
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.
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.
Note:
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".
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.
CLEAR COLUMNS
For example
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.
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.
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.
You will find these formats useful for expressions involving COUNTs or SUMs.
For example type in the following and re-run the previous query:
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:
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).
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:
where the function name can be SUM, MIN, MAX, AVG, STD VAR, or COUNT.
For example:
CLEAR BREAK
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
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
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.
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.
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.
Parameters can be passed from the command line when using the START or @ command, in
the form of:
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.
@u:\batch 10
This will list the above details for employees in department 10.
The output for this query will depend on which department has been chosen
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).
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:
To create a view joining EMP to EMPPROJ (this assumes you have created EMPPROJ and
updated EMP as directed earlier):
Since views occupy no storage space they are sometimes called "virtual tables".
Security
Why?
Convenience
Why?
For example:
A table index should include the columns you use most frequently in search conditions.
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.
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
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.
For example:
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!
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.
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.
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.
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');
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.
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;
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
);
Check the EMP table to see that the new row has been added.
Appendices Page - 74
CONSTRAINT FK_DEPTNO references DEPT(DEPTNO)
);
Appendices Page - 75
hisal NUMBER NOT NULL,
CONSTRAINT BD_HISAL CHECK (hisal >= losal)
);
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.
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)
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
Beware that some websites can be tailored to a particular DBMS product, where there can
be differences in the syntax.
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.
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:
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:
If you click the icon in the system tray, to open the window as above, then click the
gearwheel icon at the top right.
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.