Oracle Sqlplus Interface
Oracle Sqlplus Interface
Oracle Sqlplus Interface
Logging On to SQL*Plus
Host String:
OK
From the GUI interface you are prompted for username, password and host
string where the host string is the name or alias of the database you wish to
connect to.
IMMTy jg] xi
MicrosoftEndow.; 2008 !Torsion S.00.21951 11
CC) Copyright 19E-2000 Microsoft Corp.
Via the command line the SQL*Plus executable is invoked by typing sqlplus.
You can also pass in the username and password and the connect string (the
name of the database that you are connecting to) on the same line, or if you
just hit enter, you will be prompted for the user name and password. You will
not be asked for the connect string, so if your environment is not pre-set to
that database, you will find yourself unable to connect.
C:\>sqlplus
SQL Plus: Release9.0.1.0.1 ® Production on Sun Feb 3 15:54:43 2802
Cc> Copyi yht 2001 Oracle Corporation. All ri9
Enter user --name:
Enter password:
Connected, to:
Orac1e9i Enterprise Edition Release 9 .
With the Partitioning option
.Server Release 9.0.1.1.1 — Production
Setting Description
SQLP [ROMPT] { SQL> I text} The SQL*Plus prompt
PAGES [IZE] {24 1 n} How many lines to write before
rewriting the column headings
FEED [BACK] { 6 I n I ON 'OFF} States the number of rows affected by
an operation. The default gives
feedback for result sets larger than 5
rows
LIN [ESIZE] {801n} Total number of characters displayed
on a line before starting a new line
WRA[P] { ON I OFF} Whether text wraps onto multiple lines
PAU [ SE ] { ON I OFF I text} Waits for the user to hit enter before
displaying the next page
Another useful command is the HOST command. This allows you to change
context to execute an Operating System command in the host environment
without exiting the SQL*Plus session
Example
To copy a file from one location to another (very useful when writing backup
scripts!) you could use the command
HOST cp file loci file loc2
Finally, two useful commands are CLEAR SCREEN, which erases the output
on the screen, and CLEAR BUFFER, which deletes the contents of the
buffer.
PriAi A 4 L..
r•
J
t -r
ts.
f
Li
:e
The SQL*Plus Buffer only records the last SQL or PL/SQL statement made. It
does not record any SQL*Plus environment settings.
For example, if you executed a simple SELECT statement and then you
changed the setting for the TIME environment variable. If you executed the
contents of the buffer by typing a slash (/), the SELECT statement would re-
execute, not the environment setting.
Most of the commands listed may also be invoke via menu options in the GUI
interface, however, it is often quicker to type the commands than to navigate
with the mouse.
Slide 9
The use of the line editing commands in SQL*Plus tend to be more a matter
of preference than necessity. Most environments support the use of the GUI
version of SQL*Plus where the standard GUI editing options are also
supported. (Like CTRL+c for copy and CTRL+v for pasting).
s
it 1 rC
(AAX Cs4AC4
. 0
, i•-
.A.,,„
.S tc,4 LA' ( ,7,.., i
• vi,• -
( T
Summary
SQL Statements
(,4
— rt
e
S (j
; cirr OA+ V C, I I IG
"
[WHERE condition]
[GROUP BY]
[ORDER BY]
This is an abbreviated form of the SELECT statement syntax. For the full
syntax see the SQL Reference of the Oracle Documentation
The column list of the SELECT statement may have derived values. For
example, if you wished to calculate the yearly salary of all the employees in
the emp table, you would need to multiply the sal column by 12. In the
following example output the derived column, sal*12 , has also been given
what is known as a column alias. This is a way of renaming the column when
it outputs, so that the column title can be something more meaningful than
sometimes obscure column names.
Example
SMITH 9600
ALLEN 19200
WARD 15000
JONES 35700
MARTIN 15000
BLAKE 34200
CLARK 29400
SCOTT 36000
KING 60000
TURNER 18000
ADAMS 13200
JAMES 11400
FORD 36000
MILLER 15600
There are three columns in the dept table. If you wished to view all the
columns without typing in the column names individually, you could use the
asterisk (*) in the column list of the SELECT statement. The asterisk
simply means to select all columns.
Example
ECSC.
The WHERE clause allows you to restrict the quantity of data returned by
specifying a condition. A SELECT statement with no WHERE clause will return
an output for every row in the table. If you have a table with millions of rows
this is an impractical way of viewing the data.
In the emp table, if you wished to view only the rows for employees who work
in department 10, you could use a WHERE clause to restrict the output in the
following manner:
It is not necessary to include the column(s) from the WHERE clause in the
column list of the SELECT statement. In the previous example, if you know
that you are viewing employees from department 10 it is superfluous to list the
department number in the output.
If you needed the output sorted, for example, first by the employee name in
descending order, and then by the job in ascending order, you can use the
ORDER BY clause:
Logical Operators
Operator Description
Example - NOT
SQL> SELECT ename
2 FROM emp
3 WHERE deptno NOT IN (10, 20)
4 ORDER BY 1;
ENAME
ALLEN
BLAKE
JAMES
MARTIN
TURNER
WARD
Comparison Operators
Operator Meaning
Equal to
Greater than
Less than
!= Not equal to
Comparison Operators
Operator Meaning
Example 1 - BETWEEN
ENAME SAL
JONES 2975
BLAKE 2850
CLARK 2450
SCOTT 3000
FORD 3000
Example 2 — IN
ENAME
ADAMS
CLARK
FORD
JONES
KING
MILLER
SCOTT
SMITH
This query could be equivalently written by using a string of ORS instead of the
IN operator. The IN operator is simply a shorthand way of comparing
multiple OR conditions
Example 3 — LIKE
The LIKE operator allows searches for matching string patterns. The percent
sign (%) is a wildcard for 0 to many characters, while the underscore (_) is for
a single character.
DISTINCT
• Compare the following two queries:-
SQL> SELECT DISTINCT job SQL> SELECT DISTINCT job, comm
2 FROM emp; 2 FROM emp;
JOB JOB COMM
ANALYST ANALYST
CLERK CLERK
MANAGER MANAGER
PRESIDENT PRESIDENT
SALESMAN SALESMAN
SALESMAN 300
SALESMAN 500
SALESMAN 1400
The DISTINCT clause shows only unique values for a given column or across
several columns
Select examples
In the first example the ename column is joined to the job column via the
concatenation operator (a double pipe I I ). You can concatenate many
columns or strings of text together. When columns or strings have been
concatenated together they are treated as a single column in the output of the
query.
Example Script
/*
turn spooling on to place the output into a file that can
later be run as a script
*/
SPOOL compile.sql
/*
set the SQL*Plus environment variables not to spool
output other than the script that is being generated
*/
SET FEEDBACK OFF
SET ECHO OFF
SET HEADING OFF
/*
The SELECT statement generates a script to compile
packages that are invalid by concatenating text strings
together with the owner and name of the object
*/
SELELCT 'ALTER PACKAGE 'IlownerIl f .'llobject_namell'
COMPILE;'
FROM DBA OBJECTS
WHERE objecttype='PACKAGE' AND status='INVALID';
SPOOL OFF
-- turns the spooling off
Example 1
COUNT(ENAME)
10
Example 2
no rows selected
The IS NULL operator is used to test for the existence of NULL values and
returns a result of ten rows. In comparison, the second example uses the
equal to (=) comparison operator and returns no rows. Any expression testing
for NULL values with an arithmetic comparison operators like those listed on
page 3-3-10 will always return no result, because any arithmetic expression
with a NULL in it equates to NULL.
Summary
• The SELECT statement has two mandatory clauses; SELECT
and FROM
• The WHERE predicate is used for restricting the data returned
• The output of a query can be sorted by the use of the ORDER
BY clause
• A NULL in any arithmetic expression returns a NULL
Built-1n Functions
Built-In Functions
• Oracle provides many built-in functions for use with SQL and
PL/SQL
• Single-row functions which return a row of output for every
row of input. An example of a single row function is the
UPPER function which places text in upper case
• Group functions which for multiple inputs give a single
output. An example of a group function is the SUM function
which can sum the values in a specified column
• Datatype conversion functions for switching datatypes
• Miscellaneous functions
Character Functions
Function Use
Character functions are single row functions because they have an output for
every row of input
Example — LOWER
LOWER(DNAME)
accounting
research
sales
operations
Example — SUBSTR
SUB
ACC
RES
SAL
OPE
Group Functions
Function Use
AVG and sum are for numeric data only. MAX and MIN are for any datatype
SQL> SELECT AVG (comm) , AVG (NVL ( comm , 0) ) , SUM (comm) /COUNT (*)
2 FROM emp;
The above query works because all the columns in the SELECT list are in
group functions.
The following query fails because the column deptno is in the SELECT list but
there is no GROUP BY clause
SUM(SAL) DEPTNO
8750 10
10875 20
9400 30
ccc &C r
When trying to restrict the output with a group function in the WHERE clause
the statement will fail.
Instead, place the group function in the HAVING clause as below:
SUM(SAL) DEPTNO
10875 20
It is not necessary to have a group function in the SELECT list to use the
HAVING clause:
JOB SAL
ANALYST 3000
SALESMAN 1250
TO_pATE(charf [fint])
TOCHAR(numberldate,[fint])
TONUMBER(charf [fmt])
The `fmt' is the format mask for the datatype conversion. The following table
shows some common elements:
Element Description
YYY or YY or Y Last three, two, or one digits of year
Y, YYY Year with comma in this position
IYYY, IYY, IY, I Four, three, two, or one digit year based
on the ISO standard
SYEAR or YEAR Year spelled out; S prefixes BC date
with -
Q Quarter of year
MM Month, two-digit value
MONTH Name of month padded with blanks to
length of nine characters
MON Name of month, three-letter
abbreviation
RM Roman numeral month
WW or W Week of year or month
DDD or DD or D Day of year, month, or week
DAY Name of day padded with blanks to
length of 9 characters
DY Name of day; three-letter abbreviation
fL
yyVy 14,7-1-1 f3 L,
Hire Date
NAME SALARY
ADAMS $1,100
ALLEN $1,600
JAMES $950
MARTIN $1,250
MILLER $1,300
SMITH $800
TURNER $1,500
WARD $1,250
Miscellaneous Functions
Compare the result of the following two SELECT statements, one using NVL
and the other not:
Example 1
AVG (COMM)
550
Example 2
157.142857
The results are different because different calculations are performed. There
are four rows with non NULL values in the emp table.
In the first example, the sum of the commissions are divided by four — the
other NULL values in the comm column are ignored.
In the second example, the sum of the commissions are divided by 14. A
zero is substituted to every row in the emp table that has a NULL value in the
comm column. This results in the sum of the commissions being divided by
every row in the table.
Example — DECODE
DECODE(JOB,'MANAGE
This is a clerk
This is the boss
This is an analyst
This is a clerk
This is an analyst
IF job='MANAGER' THEN
Output 'This is the boss'
ELSIF job='ANALYST' THEN
Output 'This is an analyst'
ELSE
Output 'This is a clerk'
END IF
Table Joins
t ie-.1,,t,Z.,,„ kf,., i
f ( ,,,,,,,,,11,,f( Sii,....4,,,, r '"?..; (..,, )4 i tl,ic (— L. -X ./... (ii' t',"..., , p , •
/5
c °
c\
k L
At
_ 44,1 e
1 4 4 cti.e
t 1c4-
'1
Equijoins
• Equijoins are the most common form of table joins.
• They are typically characterized by a primary key joined to the
foreign key.
SELECT emp.enamell' lives in 'Ildept.loc
FROM emp, dept
WHERE dept.deptno=emp.deptno;
The column names are prefixed by the table names in the following query. It
is only strictly necessary to prefix the column name by the table name when
ambiguity could result from the same column name appearing in multiple
tables. It is more efficient, however, to prefix the column name with the
source table.
EMP.ENAMEIPLIVESIN'IIDEPT.LOC
Table Aliases
• Table aliases appear in FROM clause and reduce typing (and
typos)
• You simply list the alias that you wish to use for the table
next to the table name in the FROM clause
Outer Joins
ALLEN 30 SALES
BLAKE 30 SALES
MARTIN 30 SALES
JAMES 30 SALES
TURNER 30 SALES
WARD 30 SALES
40 OPERATIONS
Red Rock Consulting
Inner Join
• An inner join is when you join a table to itself
• This is sometimes required when a table has a 'self-
referencing foreign key'. This is when a foreign key
references a primary key in the same table
• Can often bypass use of an inner join by using a sub-query
MANAGERS
Cartesian Product
56 rows selected.
UNION Example
yo.d._ ovvi,
sr r htt (Lir
cfc/
((t
3 )A1 C
c.(‘
tr,;re-
;
a'Itr;"
Summary
• Queries can select from multiple tables
• The most frequently used form of join is the equijoin, where a
pk=fk relationship is established in the WHERE clause
• Tables may also be joined using inner joins, outer joins and
Cartesian product
• The UNION, INTERSECT and MINUS operators allow you to
manipulate the results sets of two or more queries