SQL For Beginners
SQL For Beginners
Training Guide
Course Introduction
Course Objectives
This course is designed to give each delegate a
basic understanding/awareness of the following...
• Oracle SQL
• Oracle SQL*Plus
Course Objectives
This course is designed to give each delegate a basic
understanding of the following topics...
Course Contents
1 – Getting Started 11
RDB – A quick refresher 12
What are SQL & SQL*Plus? 19
Lab 1 26
Nesting Functions 95
Group Functions 96
Group functions 97
Grouping Data 98
Omitting Groups 100
Summary 101
Lab 3 103
Lab 4 131
Copyright © 1999 – 2004 ApplTop Solutions Limited 8
Training Guide www.appltop.com
info@appltop.com
SQL & SQL*Plus for Beginners
Lab 5 165
Lab 6 177
Section One
Getting Started
RDB Constructs
To understand Relational Databases, you need to understand the
four basic constructs of an RDB and the concept of key values: -
RDB Constructs
The EMP Table
A primary key
column containing A normal column,
employee number not a key value
A foreign key
A single row A field, found at column which
representing a the intersection of links employee
single employee a row and column to department
Relational Operators
X =
Product
Restriction Projection
+ =
Relational Operators
Relation Description
Restriction Restriction is an operation that selects rows from a
relation that meet certain conditions. There can be
none, one or many conditions. This is sometimes
referred to as a ‘horizontal subset’.
Projection This is an operation that only selects specified
columns from a relation and is suitably referred to
as the ‘vertical subset’.
Product The product operation is the result of selecting
rows from two or more relations. The resulting set
of rows returned is often very large.
Join This operation is the result of selecting rows from
two more relations using one or more specified
conditions. Joins are often made via foreign key
columns.
Union This retrieves unique rows that appear in either or
both of two relations. UNION ALL can be used to
retrieve ALL rows from either or both tables.
Intersect This retrieves all rows that appear in both of two
relations.
Difference This retrieves rows that appear in one relation
only.
RDB Properties
Database Properties: -
• Individual collection of tables
• User does not need to know how data is accessed
• Uses simple language called SQL for all actions
• Uses set operations, not row by row processing
• Can be modified online
Table Properties: -
• No duplicate columns or rows
• Row and column order is insignificant
• Field values are atomic, i.e. They cannot be
broken into component parts
RDB Properties
Table Properties
* You may come across table definitions in Oracle that have no primary key
column enforcing uniqueness. This is allowed, but under the hood Oracle
maintains uniqueness using a special column called ROWID
What is Next?
We’ve had a quick refresher on the concepts of a
Relational Database and we’ve had a very brief
description what SQL & SQL*Plus are. The next
section jumps straight in and actually starts on basic
SQL commands.
Section Two
Introduction to SQL
Introduction to SQL
DML or DDL?
Starting SQL*Plus
Starting SQL*Plus
Before you can use any SQL commands, you must log into the
database using SQL*Plus. SQL*Plus can usually be found as an
Icon on your desktop (if you are running a windows OS), or,
SQL*Plus can be accessed whilst logged into a UNIX box where
the database server can be found.
• If you want to run SQL*Plus from Windows, simply double click
on the SQL*Plus Icon, at this point you will be asked for an
Oracle username and password.
• If you are wanting to start SQL*Plus from in your UNIX
session, simply type sqlplus at the command line, you will
now be asked for a Oracle username and password.
UNIX – An example
From the UNIX command line, simply enter:
sqlplus
or, you can provide the username and password from the
command line:
sqlplus user/password
you can also provide the database instance name you wish to log
onto:
sqlplus user/password@DEV
Lab 1
Table Definition
To view the columns on a table use the desc
SQL*Plus command:
desc emp
Arithmetic Operators
Column Aliases
Concatenation
NAME
--------
Name=JONES
Name=SMITH
Literals
NULL Values
NVL Function
NVL Examples
Note
Both parameters passed to NVL must have matching
datatypes.
Duplicate Rows
Ordering Data
ORDER BY Examples
SELECT ename
, sal*12 + NVL(comm,0) renum
FROM emp
ORDER BY renum DESC;
SELECT deptno
, hiredate
, ename
FROM emp
ORDER BY deptno
, hiredate DESC
, ename
Row Restriction
will return all rows from the emp table, but if you
only want a list of employees who work in
department 10, you would use the WHERE clause.
The WHERE clause MUST appear after the FROM
clause. You specify conditions in the WHERE clause
that must be met if the row is to be returned.
Conditions are basically comparisons of
columns/literals using logical operators and SQL
operators. Here is an example:
SELECT empno
FROM emp
WHERE deptno = 10
ORDER BY empno;
Some examples:
SELECT empno
FROM emp
WHERE hiredate <= '01-Jan-98';
SELECT ename
, empno
FROM emp
WHERE job = 'CLERK';
SELECT empno
FROM emp
WHERE deptno = 10;
SELECT *
FROM emp
WHERE comm > sal;
Some examples:
SELECT empno
FROM emp
WHERE deptno BETWEEN 20 AND 50;
SELECT ename
, job
FROM emp
WHERE deptno IN (10,20,30,40,50);
SELECT empno
FROM emp
WHERE comm IS NULL;
Some examples:
To list all employees whose names begin with S:
SELECT *
FROM emp
WHERE ename LIKE 'S%';
Negating a Comparison
Rather than writing a WHERE clause which says
"select rows which meet a certain condition", it may
well be easier to say "select rows which DO NOT
meet a certain condition". You do this with a negate
expression.
Negating Logical Operators
Operator Meaning
<> Not equal to
!= Same as <>
NOT column = Same as <>
NOT column > Not greater than
Multiple Conditions
A WHERE clause is not restricted to a single
condition - it can contain any number of conditions.
Multiple conditions used together are referred to as
a compound logical expression.
You can use the AND and OR keywords to create
WHERE clauses with multiple conditions.
• A condition using the AND keyword is true if
BOTH conditions are true
• A condition using the OR keyword is true if
EITHER condition is true
Some examples:
To select all rows where the department is 10 AND
the salary is greater than 1000:
SELECT *
FROM emp
WHERE deptno = 10
AND sal >= 1000;
Operator Precedence
When constructing a WHERE clause you need to be
aware of operator precedence. This determines
how a condition is evaluated, and it can greatly
affect the results. Operators are evaluated in a strict
order, as follows:
1. All Logical and SQL operators
2. NOT
3. AND
4. OR
Default Operator Precedence can be overruled by
using parentheses.
Basic SQL*Plus
As we saw earlier, the SQL language is actually
accessed from within a tool called SQL*Plus. Before
we finish this section of the course with the
exercises, we need to take a look at some of the
basic SQL*Plus commands you will need to use
when working with SQL. We will quickly cover the
following:
• Editing and executing SQL in the buffer
• Saving, loading and executing SQL files
SQL*Plus Buffer
When you enter a SQL command at the SQL*Plus
prompt, it is stored in the SQL buffer and it will
remain there until you enter a new command. If you
press [RETURN] before completing a line,
SQL*Plus will prompt you for a line number where
you can continue to enter the command. You
terminate the buffer by pressing [RETURN] again.
A semicolon, forward slash or entering RUN will
terminate and execute a SQL statement.
For example:
SQL> select *
2 from emp;
or:
SQL> select *
2 from emp
3 /
or:
SQL> select *
2 from emp
3 [RETURN]
SQL> run
Editing SQL
Once you have entered some SQL, you may want to
execute the same code but with a few changes.
You could simply re-type the code with the changes,
or you could use some basic SQL*Plus commands to
edit what is stored in the SQL Buffer.
Editing Commands
Command Abbreviation
Purpose
APPEND text A text
Adds text to end of
current line
CHANGE c/old/new/
Changes old top new on
current line
CHANGE c/text/
Deletes text from current
line
CLEAR BUFFER cl buff
Deletes all lines from
buffer
DEL Deletes current line
INPUT i
Inserts an indefinite
number of lines
INPUT i text
Inserts a line consisting
of text
LIST l Lists all lines in buffer
l n (or just Lists one line specified
LIST n
n) by n
LIST m n l m n Lists from line m to n
ED
Invokes editor with
contents of SQL Buffer
RUN r
Displays and runs what
is in buffer
/ Runs what is in buffer
To remove line 2:
SQL> 2
2* , job
SQL> del
Command Description
Saves the current contents of the
SAVE filename
SQL buffer to a file
Loads the contents of a file into the
GET filename
SQL buffer
START filename Runs a file (can also use @file)
ED filename Invokes an editor to edit the file
EXIT Quits SQL*Plus
Summary
To summarise, we have seen the basic syntax for
the SELECT statement:
SELECT [DISTINCT]{*,COLUMN [ALIAS]….}
FROM TABLE
WHERE CONDITION(S)
ORDER BY {COLUMN|EXPRESSION}[ASC|DESC]};
What is Next?
Having covered the most commonly used type of
SQL statement, the SELECT statement and also
briefly looked at SQL*Plus commands, we are now
ready to take a look at some of the more complex
features of SQL.
Lab 2
Section Three
Row & Group Functions
Row Functions
Row Functions
Character Functions
LOWER
Converts all characters to lower case
Syntax
LOWER(argument)
Example
SELECT LOWER('ORACLE') … = oracle
UPPER
Converts all characters to upper case
Syntax
UPPER(argument)
Example
SELECT UPPER('oracle') … = ORACLE
INITCAP
Forces the first letter of each word to be in upper
case
Syntax
INITCAP(argument)
Example
SELECT INITCAP('oracle') … = Oracle
Notes
If string is longer than len then string is
truncated to len characters.
SUBSTR
The SUBSTR function is used to extract a portion of
a string.
Syntax
SUBSTR(string,pos,len)
Arguments
string the string to be extracted from
len starting position to extract
pstring length of extraction
Example
SELECT SUBSTR('ORACLE',2,3) … = RAC
INSTR
Returns the starting position of string within another
string.
Syntax
INSTR(string,search)
INSTR(string,search,pos,n)
Arguments
string The string to be searched
search The search string
pos Start position of search
n Finds the nth occurrence
Example
SELECT INSTR('Oracle','cle') … = 4
LENGTH
The length function returns the number of
characters in a string.
Syntax
LENGTH(string)
Arguments
string The string you want the length of
Example
SELECT LENGTH('Oracle) … = 6
TRANSLATE
The TRANSLATE function searches through a string
for a character, and replaces it with another.
Syntax
TRANSLATE(string,from,to)
Arguments
string The string you wish to modify
from Searches for this character
to Replaces with this character
Example
SELECT TRANSLATE('hekko','k','l') … = hello
REPLACE
The REPLACE function searches through a string for
another string and replaces all occurrences of it with
another string
Syntax
REPLACE(string,search,replace)
REPLACE(string,search)
Arguments
string The string you wish to modify
search Searches for this string
replace Replaces with this string. If replace is
omitted then search is removed from
string
Example
SELECT REPLACE('orafred','fred','cle') … = oracle
Number functions
We will look at the following number functions:
• ROUND
• TRUNC
• SIGN
• CEIL & FLOOR
• Mathematical functions
ROUND
The ROUND function rounds a number to a specified
number of decimal places.
Syntax
ROUND(number,n)
Arguments
number The number you want to round
n The number of decimal places: if n is
negative then the number to the left of
the decimal point is rounded
Example
SELECT ROUND(10.25,1) … = 10.3
SELECT ROUND(10.25,-1) … = 10
TRUNC
The TRUNC function truncates a number to a
specified number of decimal places.
Syntax
TRUNC(number,n)
Arguments
number The number you want to truncate
n The number of decimal places
Example
SELECT TRUNC(10.25,1) … = 10.2
SIGN
The SIGN function returns -1 if a number is
negative, 0 if a number is zero and +1 if a number
is positive.
Syntax
SIGN(number)
Example
SELECT SIGN(10),SIGN(-100) … = 1 and -1
SELECT FLOOR(10.25) … = 10
Mathematical Functions
There are more number functions available. Here is
a list of some of them:
Function Arguments Returns
power mn Raises m to the power n
mod mn Returns remainder of m
divided by n
abs m Returns absolute value of m
sqrt m Square root on m
log mn Logarithm, base m of n
sin n Sine of n
sinh n Hyperbolic sine of n
tan n Tangent of n
tanh n Hyperbolic tangent on n
cos n Cosine of n
cosh n Hyperbolic cosine of n
exp n e raised to the nth power
where e=2.71828183
ln n Natural logarithm on n,
where n is greater than zero
Oracle Dates
Dates in Oracle are stored as a number which
represents the following:
• Century
• Year
• Month
• Day
• Hours
• Minutes
• Seconds
The default display format is DD-MON-RR (or DD-
MON-YY) which represents a 2 digit day, followed by
a 3 character month, and ending in a 2 digit year:
for example, 10-JUL-99.
Date Arithmetic
Arithmetic operators can be performed on dates.
The following table describes how this works:
Operation Result Type Description
date + number date Adds number of
days to date
date - number date Subtracts number
of days from date
date - date number of days Subtracts one
date from another
date + number/24 date Adds number of
hours to date
Date functions
We will look at the following Date functions:
• MONTHS_BETWEEN
• ADD_MONTHS
• NEXT_DAY
• LAST_DAY
• ROUND
• TRUNC
MONTHS_BETWEEN
This function returns the number of months
between two dates. The non-integer part of the
result represents a portion of a month.
Syntax
MONTHS_BETWEEN(date1,date2)
Example
SELECT MONTHS_BETWEEN(sysdate,sysdate-30) … = 1
ADD_MONTHS
This function adds a specified number of months to
a date.
Syntax
ADD_MONTHS(date,mon)
Arguments
date The date you are adding too
mon The number of months to add. mon can
be negative
Example
SELECT ADD_MONTHS(sysdate,2) …
NEXT_DAY
The NEXT_DAY function is used to find the next
date of the specified day after a specified date.
Syntax
NEXT_DAY(date,day)
Arguments
date The starting date
day A string representing the day you are
looking for, i.e. Monday, Tuesday, etc.
Can also be given as a number where 1 is
Sunday and 7 is Saturday.
Example
SELECT NEXT_DAY(SYSDATE,'Monday') …
LAST_DAY
The LAST_DAY function is used to find the last day
of the month which contains a specified date.
Syntax
LAST_DAY(date)
Example
SELECT LAST_DAY(sysdate) …
Arguments
date The date to be rounded
what Can either be MONTH or YEAR - if omitted
then time element is set to 12:00:00am
(useful for comparing dates with different
times).
Example
SELECT ROUND(sysdate,'YEAR') …
Conversion Functions
When you are selecting columns from a table,
specifying literals or using the results of functions,
you are working with specific datatypes. There will
be times when you need to mix and match
datatypes, and you do this using conversion
functions. We will cover the following conversion
functions:
• TO_CHAR
• TO_NUMBER
• TO_DATE
TO_CHAR
The TO_CHAR function is used convert a value into
a char, with or without a specified format.
Syntax
TO_CHAR(number)
TO_CHAR(number,format)
TO_CHAR(date)
TO_CHAR(date,format)
Arguments
number The number you want to convert to a char
date A date you want to convert to a char
format The format mask you wish to apply to the
resulting char. Many format masks are
available.
Examples of TO_CHAR
Convert a number to a char:
TO_CHAR(10)
TO_NUMBER
The TO_NUMBER function is used convert a char into
a number.
Syntax
TO_NUMBER(string)
Example
SELECT TO_NUMBER('10') …
TO_DATE
The TO_DATE function is used convert a char into a
date.
Syntax
TO_DATE(string)
TO_DATE(string,format)
Arguments
string The string to be converted
format The format mask you wish to apply to the
input string: this ensures that the string is
in a correct date format. If format is
omitted then the default date format
(usually DD-MON-RR) is used.
Example
SELECT TO_DATE('10-JUL-1999','DD-MON-YYYY') …
NVL
The NVL function returns a specified value if
another is NULL.
Syntax
NVL(value,new value)
Arguments
value The value you wish to check for null
new value Returns this if value is null
Examples
SELECT NVL(mgr,'No manager') …
SELECT NVL(comm,0) …
Arguments
valuen Makes up list of values
Examples
SELECT GREATEST(10,20,50,40) …
will return 10
DECODE
The DECODE function is very powerful. It works like
an IF statement, but can be embedded within a SQL
statement.
Syntax
DECODE( value,
, search1, result1
[, search2, result2 . . .]
, default)
Arguments
value The value to be evaluated
search The value to search for
result Returns value if a match is found
default Returns this if no match is found
Examples
To display a percentage based on salary grade:
SELECT DECODE( salgrade
, 1,'15%'
, 2,'10%'
, 3,'8'
, '5%' ) bonus …
Nesting Functions
There will be times when you need to perform two
or more functions on a single value. The second
function may depend on the result of the first, and
so on: you can do this kind of thing by nesting
functions.
As a simple example, let's say that you want to list
all employees, and that you want the manager
column to contain some readable text if it is null.
You might at first try:
SELECT NVL(mgr,'NO MANAGER') ..
Group Functions
Single row functions act upon each row returned
from a query. Group functions, on the other hand,
act on sets of rows returned from a query. This set
can be the whole table or the table split into smaller
groups.
A table is split into smaller groups with the GROUP
BY clause. This appears after the WHERE clause in a
SELECT statement.
Group Functions
Grouping Data
You can split the data in a table into smaller groups,
you can then use Group Functions to return
summary information about each group. You split a
table using the GROUP BY clause.
The GROUP BY clause instructs the query to return
rows split into groups determined by the specified
columns. GROUP BY generally takes the following
form:
SELECT job
, AVG(sal)
FROM emp
WHERE deptno = 20
GROUP BY job;
Grouping Data
Summary
In this section we have covered:
• Row Functions
• Row functions act on each row returned
• Character functions
• Number functions
• Oracle dates & date functions
• Conversion functions & format masks
• Functions that accept any datatype
• Nesting functions
• Group Functions & Grouping Data
• Group functions act on a group of rows
• Many different group functions
• Grouping Data
• Omitting groups
What is Next?
In the next section we take a look how to select
data from more than one table at a time. We cover
joins, set operators and subqueries.
Lab 3
1 List all employees, give each a 15% pay increase and display
new salary always rounded down to the nearest whole
number. Display name, old salary and new salary.
2 List all employee names in upper and lower case, also
display the name with the first character in upper and the
rest in lower.
3 Create a list that displays the first 2 digits of the employee
name, followed by the empno, followed by the rest of the
name, display as a single column.
4 Generate the following output:
EMPLOYEES
-----------------------
Smith is 5 digits long
Allen is 5 digits long
Ward is 4 digits long
Jones is 5 digits long
Martin is 6 digits long
Blake is 5 digits long
. . . . .
Section Four
Querying More Than One
Table
Joins
So far, any queries we've seen have been from a
single table at a time - but SQL allows you to query
many tables at the same time through the use of
joins. We will now cover some of the basics of
joining tables within a SELECT statement. We will
look at the following types of join:
• Product
• Equi join
• Non-equi join
• Outer join
• Self join
Joins - Product
If you construct a SELECT statement which contains
information from two or more tables without
specifically linking any of the columns from one
table to the next, the resulting query would be what
is known as a product (sometimes referred to as a
Cartesian join). This basically means that ALL rows
from ALL tables are returned in EVERY combination.
So for example, lets say we have two tables - “emp”
with 14 rows and “dept” with 4 rows - and we
entered the following statement:
SELECT dname,ename
FROM emp,dept;
The above query would return all rows from both
tables in all combinations, resulting in a total of 56
rows being returned (14 * 4 ).
You will very rarely need to perform this kind of
query, but it is mentioned so that you are aware of
the result of a product join. If you unintentionally
create one then the results could be very different
to what you might expect: imagine 2 tables, with
over 1,000,000 rows each!!
Joins - Equi
An equi join is a join which directly links columns
from one table to another, or in other words, an
equi join joins tables where a column on one table is
equal to a column from another table. As an
example, let's say you have the following statement:
SELECT ename,deptno
FROM emp;
Table Aliases
As a rule, when selecting data from more than one
table, you should qualify the column names you use
with the table name. This removes any ambiguity if
there are duplicate column names across different
tables: you do this by prefixing a column name with
the table name followed by a dot (.):
SELECT TABLE.COLUMN …
A better method of this is to use a table alias. A
table alias is very similar a column alias, in that it is
a method of renaming a table only for the purposes
of the query - you can then use this alias within
your query as if the table were actually called by the
alias. This can save a lot of typing, make SQL easier
to read and allowing for self joins (covered later).
The syntax for a table join is simple: just follow the
table name with the alias:
SELECT e.ename,d.dname
FROM emp e,dept d
WHERE e.deptno = d.deptno;
Qualifying column names can also improve
performance of your code because you are telling
the system exactly where to find the column.
Joins - Outer
An outer join allows you to join tables together and
still return rows even if one side of a condition is not
satisfied. For example, the dept table has 4
departments (10, 20, 30 and 40), and the emp table
has employees in all departments except 40, so if
you were to write some SQL to join the two tables
together using a standard equi-join, the row from
dept which does not appear in emp would not be in
the returned rows. You can use an outer join to get
around this problem.
SELECT e.ename,d.dname
FROM emp e,dept d
WHERE d.deptno = e.deptno(+);
Joins - Self
By using a self join with table aliases you can join a
table to itself. A self join basically allows you to
select from the same table more than once within
the same SQL statement - this is very useful if a
table has rows on it which relate to other rows on
the same table. For example, the emp table holds
employees, and each employee has a manager
(except the big boss). This manager is stored on
the same table: so, you would need a self join if
you wanted to create a statement that listed all
employee names along with their manager name.
SELECT e.ename employee_name
, m.ename manager_name
FROM emp e,emp m
WHERE m.empno = e.mgr;
Set Operators
We covered the concepts of Set Operators in the
introduction to Relational Databases at the start of
this course. So far we have covered:
• restriction with the WHERE clause
• projection with the SELECT clause,
• joins
• product
We will now cover:
• UNION
• INTERSECT
• MINUS
Set Operators
UNION, INTERSECT and MINUS set operators are
used when you need to construct two or more
queries and you want to see the results as if it were
a single query.
The queries you use could be totally different, i.e.
different tables, or they could be using the same
table but be using different WHERE or GROUP BY
clauses.
UNION ALL
Instead of using UNION, you could use UNION ALL
which would return ALL rows from both queries.
Subqueries
A sub query is basically a SELECT statement within
another SELECT statement; they allow you to select
data based on unknown conditional values. A
subquery generally takes the form:
SELECT column(s)
FROM table(s)
WHERE column(s) = (SELECT column(s)
FROM table(s)
WHERE condition(s) );
Subqueries
When constructing subqueries you should be aware
of the following:
• ORDER BY can appear in the outer query only
• You can nest subqueries to a level of 255 (you
never would!)
• Subqueries can be used with the HAVING clause,
for example, to list the departments which have
an average salary bill greater than the average
salary bill for department 30:
SELECT deptno,AVG(sal)
FROM emp
GROUP BY deptno
HAVING AVG(sal) >
(SELECT AVG(sal)
FROM emp
WHERE deptno=30);
Correlated Subqueries
A correlated subquery is a way of executing a
subquery once for each row found in the outer
query. A correlated subquery works as follows:
1. Get a candidate row from outer query
2. Execute subquery using candidate row data
3. Use values from subquery to either include or
exclude candidate row
4. Continue until no more candidate rows are found
in the outer query.
A correlated subquery is identified by the use of an
outer query column within the subquery. They are
useful when you need the subquery to return
different results based on the outer query.
Correlated Subqueries
As an example, let’s say we wanted to list all
employees who earn a salary greater than the
average for their department. A standard subquery
would not work because the rows returned from the
subquery will not be related (correlated) to the rows
in the outer query. Using a correlated subquery you
would have something like:
SELECT empno,ename,sal,deptno
FROM emp e
WHERE sal > (SELECT avg(sal)
FROM emp
WHERE deptno = e.deptno);
The above query says: select all employees as
candidate rows, then find the average salary for the
current department, using this average, either
include or exclude the candidate row.
The key to this working is the table alias used in the
outer query - we need to ensure the emp table is
called something different in both queries, otherwise
we would not be able to link the columns together.
Correlated Subqueries
The EXISTS Operator
You can use the EXISTS operator with a correlated
subquery: this is used to determine if any rows are
returned from the subquery. If any are returned
then the condition is true and the row in the outer
query is returned. For example, to select all
employees who manage someone,…
SELECT empno,ename,job,deptno
FROM emp e
WHERE EXISTS (SELECT 'FOUND A ROW'
FROM emp
WHERE emp.mgr = e.empno);
Summary
In this section we have covered a lot of ground: we
have looked at some of the more complex types of
queries. We briefly covered ways in which you can
select data from more than one table at a time.
• Joins - Product, Equi, Non-equi, Outer and Self
• Set Operators - UNION, INTERSECT and MINUS
• Subqueries - Single Row, Multi Row and
Correlated
What is Next?
In the next section we take a quick look at using
DML and DDL to modify data within the database,
and how to change the structure of the database.
Lab 4
Section Five
Modifying Data & the
Database
Using DML
Inserting New Data
If you need to create new data within the database,
you use the INSERT statement. This allows you to
create new rows on any table (as long as you have
the correct privileges).
INSERT
SQL statement used to insert rows into the database
Syntax
INSERT INTO table [ (column,column,……) ]
VALUES (value,value,…..);
Example
INSERT INTO dept (deptno,dname,loc)
VALUES (50,'MARKETING','DAVENTRY');
Using DML
Updating Existing Data
If you need to change some data within the
database, you use the UPDATE statement. This
allows you to change a single row or many rows at
the same time (as long as you have the correct
privileges).
UPDATE
SQL statement used to update rows in the database
Syntax
UPDATE table [alias]
SET column [,column…] =
{expression,subquery}
[WHERE condition];
Example
UPDATE emp
SET sal = sal * 1.1
WHERE job = 'CLERK';
Using DML
Deleting Data
If you need to delete data within the database, you
use the DELETE statement. This allows you to
delete a single or many rows at once (as long as
you have the correct privileges).
DELETE
SQL statement used to delete rows from the
database
Syntax
DELETE [FROM] table
[WHERE condition];
Example
DELETE emp
WHERE job = 'MANAGER';
Using DML
Deleting Data
Another way to remove all the data from a table is
using the TRUNCATE TABLE command.
TRUNCATE TABLE
SQL statement used to remove ALL rows from a
table
Syntax
TRUNCATE TABLE table
Example
TRUNCATE TABLE emp;
Truncates are DDL, not DML. A truncate moves the High Water Mark of the table
back to zero. No row-level locks are taken, no redo or rollback is generated. All
extents except those defined in the MINEXTENTS parameter are de-allocated from
the table.
By resetting the High Water Mark, the truncate prevents reading of any table's data,
so they it has the same effect as a delete, but without the overhead. There is,
however, one aspect of a Truncate that must be kept in mind. Because a Truncate
is DDL it issues a COMMIT before it acts and another COMMIT afterward so no
rollback of the transaction is possible.
Transaction Processing
Oracle ensures the consistency of data through the
use of transactions. Transactions give you more
control when changing data and will ensure data
consistency in the event of a system failure.
A transaction can be thought of as a single
consistent change to the database which may
directly relate to some kind of business
functionality: this change to the database may
consist of a single or multiple DML statements. For
example, in a banking system, a transfer funds
transaction would involve the transfer of funds out
of one account and then further transfer into
another account - this would require two DML
statements but is considered a single transaction.
Transaction processing allows you to perform all the
DML you need before committing the changes to the
database. This ensures that both of DML statements
are always complete and in the event of a failure,
none of the DML statements would complete.
Transaction Processing
There are two types of transaction:
• DML - holds a number of DML statements
• DDL - holds a single DDL statement
Transaction Processing
The COMMIT command
Whenever you issue a DML statement which
changes the data held within the database, you are
not actually changing the database. You are
effectively putting your changes into a buffer, and
to ensure this buffer is flushed and all your changes
are actually in the database for others to see, you
must first commit the transaction. You can do this
with the COMMIT statement.
Syntax
COMMIT [WORK];
Example
UPDATE dept
SET dname = initcap(dname);
COMMIT;
The above code will update all dept rows then
commit the changes to the database.
After the COMMIT command has run, the following
is true:
• Your changes are in the database and permanent
• The current transaction has ended
• Any locks are released
Transaction Processing
The ROLLBACK command
If you have started a transaction by issuing a
number of DML statements, but you then decide
you want to abort the changes and start again, you
need to use the ROLLBACK statement.
Syntax
ROLLBACK [WORK];
ROLLBACK [WORK] TO SAVEPOINT_NAME;
Example
UPDATE dept
SET dname = initcap(dname);
ROLLBACK;
Transaction Processing
The SAVEPOINT command
You can split a transaction up into smaller portions
using the SAVEPOINT command. SAVEPOINT
allows you to specify markers within a transaction,
and these markers can be easily rolled back to if
needed.
Syntax
SAVEPOINT savepoint_name;
Example
UPDATE dept
SET dname = initcap(dname);
SAVEPOINT done_dept;
UPDATE emp
SET sal = sal * 1.1;
ROLLBACK TO done_dept;
COMMIT;
Transaction Processing
Keep in mind the following about transaction
processing:
• Other database users will not see your changes
until you COMMIT them.
• An uncommitted transaction is one which holds
locks on the data, for example, if you update a
single emp row without committing, other people
will still see the unchanged emp row but will not
be able to change it themselves until you either
issue a COMMIT or ROLLBACK.
Using DDL
DDL is a subset of SQL commands that allows you
to make changes to the structure of the database.
We will briefly cover the following kinds of database
objects:
• Tables
• Indexes
• Synonyms
• Privileges
• Views
• Sequences
Using DDL
When working with any kind of object within the
database, there are usually three basic commands
that apply to all objects. These are:
• CREATE - used to create an object
• ALTER - used to alter/change an object
• DROP - used to remove an object
Column Types/Datatypes
All columns on a table must be given a datatype, as
this determines what kind of data the column can
hold. A few of the more common data types are:
Datatype Purpose
NUMBER Holds number data of any precision
NUMBER(w) Holds number data of w precision
NUMBER(w,s) Holds number data of w precision and
s scale, i.e. 10,2 is a number upto 10
digit in length, with 2 digits after the
decimal point.
VARCHAR2(w) Holds variable length alphanumeric
data upto w width.
CHAR(w) Holds fixed length alphanumeric upto
w with.
DATE Holds data/time data
Examples
To create a unique index called emp_idx01 on the
emp table using the empno column:
CREATE UNIQUE INDEX emp_idx01
ON emp
(empno);
Summary
In this section we have covered both how to use
DML and DDL, and specifically we have seen:
• Insert, Update and Delete data
• Transaction Processing
• Creating, deleting and altering Tables
• Indexes
• Synonyms
• Privileges
• Views
• Sequences
What is Next?
As far as SQL is concerned, we have pretty much
finished: all that is left to do now is take a quick
look at some features of SQL*Plus.
Lab 5
7 Insert a row into the new table, set INFO_ID to be the next
value from the sequence you created, set EMPNO to a valid
employee number, INFO_DATE to today's date and enter
some text into INFO.
8 Create a synonym called einfo for your new table.
9 Select all rows from your new table using the synonym;
10 Remove the new synonym and table.
Section Six
More SQL*Plus
More SQL*Plus
We have already seen a little of SQL*Plus: we will
now cover a little more on how to use SQL*Plus and
what it can do. We will briefly cover:
• SQL*Plus Variables
• Basic SQL*Plus Reporting
• Saving Output to a file
SQL*Plus Variables
A SQL*Plus variable is basically a way of storing a
value in a temporary space. This value can then be
referenced from within a SQL statement. We will
take a very quick look at:
• Ampersand substitution variables
• Double ampersand substitution variables
SQL*Plus Variables
Ampersand Variables
A single ampersand substitution variable is a
method of asking the user for input before some
SQL executes, then substituting the value entered
for the reference to the variable within your SQL.
Simply prefix a variable name with a single
ampersand and SQL*Plus will prompt you to enter a
value at runtime. For example:
SELECT *
FROM emp
WHERE deptno = &department_number;
SQL*Plus Variables
Double Ampersand Variables
A double ampersand substitution variable is almost
the same as a single ampersand variable. The only
difference is that the value is remembered, so you
only need enter a value once.
Example
SQL> TTITLE 'Employee List'
SQL> SELECT * FROM emp;
Sun Jul 18 page 1
Employee List
EMPNO ENAME
--------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
20 SMITH
ADAMS
The BREAK command says: set up a BREAK point
on deptno and skip a line each time it changes.
Summary
SQL*Plus is a very powerful tool, and it can do
much more than described on this course: but, you
should now have an idea as to what can be
achieved using SQL*Plus. We briefly covered:
• SQL*Plus variables
• Basic SQL*Plus Reporting
• Saving Output to a File
What is Next?
This is the end of the course; we have covered an
awful lot of topics in such as short space of time.
Don't be concerned if you haven't quite taken it all
in, as this course was really designed to give you a
taster of SQL and SQL*Plus. You should be
equipped with enough knowledge to make it easy to
further progress your knowledge in these areas.
Lab 6
1 Create a query that lists all employees. Prompt for a job type
and only list employees in that job.
2 Ask for a column list, (columns separated by commas) then
list all employees, showing only those columns you entered
when asked.
3 Create a simple SQL*Plus report, it should have a title of
'Employees By Job' and list each job type with all employees
for that job, skip 1 line between jobs. Show job type,
employee number, employee name and hiredate.
Answers To Exercises
Answers To Exercises
Lab Exercise Answer
1 1 Double Click the SQL*Plus icon on the desktop. Login to the
database using the username and password supplied
2 From the UNIX prompt enter, sqlplus
<username>/<password>
Answers To Exercises
Lab Exercise Answer
2 1 SELECT *
FROM salgrade;
2 SELECT *
FROM emp;
3 SELECT *
FROM emp
WHERE sal BETWEEN 1600 AND 3000;
4 SELECT deptno
, dname
FROM dept
ORDER BY dname;
5 SELECT DISTINCT job
FROM emp
ORDER BY job DESC;
6 SELECT ename
, hiredate
FROM emp
WHERE job = 'CLERK'
AND deptno = 20;
7 SELECT *
FROM emp
WHERE ename LIKE 'S%';
8 SELECT ename
, job
, mgr
, sal
FROM emp
WHERE mgr IS NOT NULL
ORDER BY sal DESC;
9 SELECT ename
, sal + NVL(comm,0) "Remuneration"
FROM emp;
10 SELECT ename
, sal
, sal*12 "Annual Salary"
, comm
FROM emp
WHERE sal < NVL(comm,0)
ORDER BY sal DESC
Answers To Exercises
Lab Exercise Answer
3 1 SELECT ename
, sal
, ROUND(sal*1.15) new_sal
FROM emp;
2 SELECT ename
, LOWER(ename)
, INITCAP(ename)
FROM emp;
3 SELECT SUBSTR(ename,1,2)
|| TO_CHAR(empno)
|| substr(ename,3,LENGTH(ename)-2)
FROM emp;
4 SELECT RPAD(INITCAP(ename),7,' ')
|| ' is '||TO_CHAR(LENGTH(ename))
|| ' digits long'
FROM emp
5 SELECT
ename,hiredate,FLOOR(MONTHS_BETWEEN(SYSDATE,hiredate
)) months
FROM emp
ORDER BY months DESC;
6 SELECT ename
, DECODE(SIGN(1500-sal)
, 1,'BELOW 1500'
, 0,'On Target'
, sal ) salary
FROM emp;
7 SELECT TO_CHAR(SYSDATE,'DAY') Day
FROM dual;
8 SELECT MAX(sal) max
, MIN(sal) min
, AVG(sal) avg
FROM emp;
9 SELECT job
, SUM(sal) total
FROM emp
GROUP by job;
10 SELECT COUNT(*)
FROM emp
WHERE job = 'CLERK';
11 SELECT deptno,COUNT(*) employees
FROM emp
GROUP BY deptno
HAVING COUNT(*) > 3;
Answers To Exercises
Lab Exercise Answer
4 1 SELECT e.ename
, d.dname
FROM emp e
, dept d
WHERE d.deptno = e.deptno;
2 SELECT e.ename
, e.deptno
, d.dname
, d.loc
FROM emp e
, dept d
WHERE d.deptno = e.deptno;
3 SELECT e.ename
, e.sal
, g.grade
FROM emp e
, salgrade g
WHERE e.sal BETWEEN g.losal AND g.hisal;
4 SELECT d.deptno
FROM dept d
WHERE NOT EXISTS
(SELECT deptno
FROM emp e
WHERE e.deptno = d.deptno);
5 SELECT e.ename
, m.ename
FROM emp e
, emp m
WHERE m.empno = e.mgr;
6 SELECT e.ename
, NVL(m.ename,'NO MANAGER') manager
FROM emp e
, emp m
WHERE m.empno(+) = e.mgr;
7 SELECT job,sal
FROM emp
WHERE (job,sal) IN
(SELECT e.job,MAX(e.sal)
FROM emp e
GROUP BY job)
8 SELECT '*'||ename name
, hiredate
FROM emp
WHERE hiredate = (SELECT MAX(hiredate)
FROM emp)
UNION
SELECT ename name
, hiredate
FROM emp
WHERE hiredate <> (SELECT MAX(hiredate)
FROM emp);
Answers To Exercises
Lab Exercise Answer
5 1 UPDATE emp
SET sal = sal * 1.25;
COMMIT;
SELECT ename
, sal
FROM emp;
2 UPDATE emp
SET sal = sal * 1.05
WHERE deptno IN (SELECT deptno
FROM dept
WHERE loc = 'NEW YORK');
ROLLBACK;
SELECT ename
, sal
FROM emp;
3 INSERT INTO dept VALUES (50,'IT','ENGLAND');
4 ROLLBACK
or if you committed your work,..
DELETE dept
WHERE deptno = 50;
5 CREATE SEQUENCE empinfo_seq
START WITH 10
INCREMENT BY 1;
6 CREATE TABLE employee_info
( info_id NUMBER
, empno NUMBER
, info_date DATE
, info VARCHAR2(80));
7 INSERT INTO employee_info VALUES
(empinfo_seq.NEXTVAL,7900,SYSDATE,'Some Info');
8 CREATE SYNONYM einfo
FOR employee_info;
9 SELECT *
FROM einfo;
10 DROP TABLE employee_info;
Answers To Exercises
Lab Exercise Answer
6 1 SELECT *
FROM emp
WHERE job = '&1';
2 SELECT &1
FROM emp;
3 TTITLE 'Employees By Job'
BREAK ON job SKIP 1
SELECT job
, empno
, ename
, hiredate
FROM emp;
Demo Tables
DEPT
DEPTNO DNAME LOC
--------- -------------- -------------
10 ACCOUNTING New York
20 RESEARCH Dallas
30 SALES Chicago
40 OPERATIONS Boston
EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ---------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2572.5 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5250 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1365 10
SALGRADE
GRADE LOSAL HISAL
--------- --------- ---------
1 700 1200
2 1201 1400
3 1401 2000
4 2001 3000
5 3001 9999
NOTES
NOTES