Oracle8 SQL*Plus User's Guide

Table of Contents

Document Conventions

  1. Introduction
  2. Getting Started
  3. Oracle SQL*Plus Commands
  4. Using SQL to Manipulate Data
  5. Object-Relational Extension
  6. Trouble Shooting


Disclaimer
Copyright © 1998-2000 Dalhousie University
Last Updated: Mar, 1999 by Poh Chua  (poh.chua@dal.ca)


Document Conventions


1. Introduction

SQL*Plus is a command line interface that allows users to use Structured Query Language (SQL) to access data stored in the Oracle database. SQL (pronounced "sequel") was originally developed by IBM Corporation, Inc. for the relational database model proposed by Dr. E. F. Codd. It has since evolved and is accepted as the standard language for Relational Database Management System.

This document is intended for users who are new to Oracle and SQL language. Readers are expected to have a basic understanding of relational database model and some familiarity in unix environment.

2. Getting Started

2.1. Applying for an Oracle User Account

Oracle is available on GS.Dal.CA. Please follow the General Services Host - GS.Dal.CA procedure to obtain a username.

Users on GS are NOT automatically registered to use Oracle. You must make the request by indicating it on your username application form. If you already have your GS username and you are currently not an Oracle user, please email the Oracle Database Administrator now!

2.2. Host Login and Initial Oracle Setup Procedure

Most computer labs on campus provide telnet software for access to host "gs.dal.ca". You may also use your home computer with dial up capability for GS connection.

To setup your GS username to use Oracle, login to GS and at the $ prompt, enter:

. setup oracle8

(note there is a space before and after the word setup)
This is a one time procedure. Oracle will be automatically setup whenever you login.

2.3. New Database Request

Under normal circumstances, users who requested Oracle access will be registered to use the database named GS. Course instructors or individuals who have special needs may ask for separate databases during or after username applications.

For those who shared the same database, their information are strictly confidential. To allow others to view and/or modify the data, the owners must explicitly grant access permissions to one or more users.

2.4. Starting and Stopping Oracle SQL*Plus

To start SQL*Plus, enter the following command at the operating system prompt (i.e. "$") and press [RETURN]:

$ sqlplus username
Where username is your Oracle username assigned by the DBA.

Next Oracle will prompt you for your password. The initial password is the same as your Oracle username. Enter your password and press [Return]. If everything went well, SQL*Plus displays the SQL*Plus command prompt:

SQL>

The command prompt indicates that SQL*Plus is ready to accept your commands.

To leave SQL*Plus, enter the EXIT command at the SQL*Plus command prompt:

SQL> exit

2.5. Changing your Oracle Password

Each new Oracle user is assigned a default password. It is the same as the Oracle username. After login to SQL*Plus, probably the first task the user should do is to change the password for security reason.

To change your Oracle password, enter the following command at SQL*Plus prompt

SQL> alter user username identified by newpassword;
where username is your Oracle username and newpassword is your new password.

2.6. Entering SQL Commands

Here is a sample SQL command:

SQL> select empno, ename, job, sal from emp;
A semicolon (;) at the end of the SQL command tells SQL*Plus that you want to run the command.

If the data is shared by many users, Oracle may lock the data being used depending on circumstances. You should include the SQL COMMIT in your SQL statements at the end of logically complete units of work to release locks on the data. For example:

SQL> select empno, ename, job, sal from emp;

...query results here...

SQL> update emp set sal=sal*1.05;

37 rows updated.

SQL> commit;

Commit complete.

SQL>
For long SQL command, you can divide it into separate lines simply by pressing [RETURN] and continue your SQL command at the next line. SQL*Plus gives each line a number. For example:
SQL> select empno, ename, job, sal
  2  from emp
  3  where sal < 1000;

3. Oracle SQL*Plus Commands

3.1. The SQL Buffer

The area where SQL*Plus stores your most recently entered SQL command is called the SQL buffer. The command remains there until you enter another. The SQL buffer allows you to rerun, edit or save the current SQL command without re-typing. When you issue the command "edit" or simply "ed" without arguments, the SQL statement in the buffer will be saved to a file called AFIEDT.BUF (A FIle EDiTing BUFfer) and opened in your default editor.

3.2. Editing the SQL Command

In the previous section, we mentioned the EDIT command allows you to edit the SQL command with your default editor. In this section, we include a list of commands that allows you to edit and manipulate the SQL command directly from the SQL*Plus prompt:

CommandAbbreviationPurpose
APPEND textA textadds text at the end of a line
0 text0 textadds text before the first line
CHANGE /old/newC /old/newchanges old to new in a line
CHANGE /textC /textdeletes text from a line
CLEAR BUFFERCL BUFFdeletes all lines
DEL(none)deletes the current line
DEL n(none)deletes line n
DEL *(none)deletes the current line
DEL LAST(none)deletes the last line
DEL m n(none)deletes a range of lines (m to n)
INPUTIadds one or more lines
INPUT textI textadds a line consisting of text
LISTLlists all lines in the SQL buffer
LIST nL n or nlists line n
LIST *L *lists the current line
LIST LASTL LASTlists the last line
LIST m nL m nlists a range of lines (m to n)

3.3. Rerunning the SQL Command

You can use the RUN or slash (/) command to run the SQL command in the buffer. This is useful after you have made changes or correction to the SQL command:
SQL> run
or
SQL> /

3.4. Saving the SQL Command As A Command File

You can use the SAVE command to write the contents of SQL buffer to a file. See example below:
SQL> list
1   select empno, ename, job, sal2   from emp 
3*  where sal < 1000
SQL> save filename
where filename is the name of your output file. The default file extension is .sql

3.5. Running A Command File

You can run an existing command file from within SQL*Plus by using the START or @ ("at" sign) command. For example:
SQL> start filename
or 
SQL> @filename
The @ command can also be used to run a command file at the operating system prompt. Here is the example:
$ sqlplus [username[/password]] @filename
SQL*Plus will prompt you for your username and password if not specified.

3.6. Running A Nested Command File

A nested command file is a command file that contains one or more START command that run other command files. The @@ (double "at" sign) command allows you to run a nested command file. Basically, this command is identical to the @ command except that it looks for the specified command file in the same path as the command file from which it was called.

3.7. Capturing and Printing Query Results

You can use the SPOOL command to capture the query output to a file. Use the SPOOL OFF command to stop the capturing. For example:
SQL> spool assignment1
SQL> (your SQL command here)
SQL> (your SQL results)
SQL> spool off
Note that the default file extension for the spooled file is .lst.

Be aware that the SPOOL command automatically overwrite any existing file with the same filename.

You can tell whether the spooling is on or off simply by entering the SPOOL command without any argument.

To print the spooled file, use the following command at the operating system prompt:

$ lpr -J Abanner filename
where Abanner is the banner name of your printout and filename is the name of your spooled file.

You can pick up the printout at the machine room, basement of Killam Library.

If you do not wish to send the file to the central line printer, you can FTP it to another machine or download it to your pc and print it from there.

3.8. Running Host Commands

The HOST command allows you to run unix command from the SQL*Plus prompt. The following example list all the file with .sql extension in current directory:
SQL> host ls *.sql
You can exit to the shell prompt temproraly by issuing the HOST command without arguments. Type EXIT or Enter CTRL-d (i.e. press "d" while holding the CTRL key) to return to SQL*Plus.

3.9. Getting Help

The Oracle8 Server Version 8.0.3 On-line Generic Documentation contains a complete set of manuals on Oracle8 Server and related product components.

3.10. Basic SQL*Plus commands

This section provides a list of basic SQL*Plus commands. A more complehensive list can be found in the SQL*Plus online manual.

CommandDescription
ACC[EPT] variable [PROMPT text]Reads input from the user and stores it in a variable.
DEF[INE] [variable]|[variable = text]Defines memory variable.
DESC[RIBE] objectnameDisplays table or object attributes.
ED[IT] [filename[.ext]]Invokes the text editor for you to edit the contents of the SQL buffer or the specified file.
[EXIT|QUIT] [COMMIT|ROLLBACK]Terminates SQL*Plus and COMMITs or ROLLBACKs the changes if specified.
GET filename[.ext]Places the contents of the specified SQL file into the SQL buffer.
HO[ST] [command]Temporary exits to OS or executes an OS command.
L[IST] [n]Displays the nth line of the SQL statement in the SQL buffer. Current line will be displayed if n is ignored.
PROMPT [text]Displays text on screen.
R[UN]Executes the SQL statement in the buffer.
SAV[E] filename[.ext]Saves the contents of SQL buffer to a file.
SETSets the SQL*Plus environment eg. SET AUTOCOMMIT ON.
SHO[W]Shows SQL*Plus environment settings. eg. SHOW ALL.
SPO[OL] filename[.ext]Saves query results to a text file.
STA[RT] filename[.ext]Executes a SQL command file.

4. Using SQL to Manipulate Data

4.1. Basic SQL DDL Commands

DDL short for Data Definition Language allows you to define and alter database table definition.

4.1.1. The CREATE TABLE Command

4.1.2. The CREATE TABLE AS Command

4.1.3. Modify Table Definition

4.1.4. Delete A Table From The Database

4.1.5. Data Types

You can use both ANSI data types and Oracle8 datatypes to define your data. Oracle8 creates columns with Oracle8 datatypes based on the conversions defined in the following table:

ANSI SQL Datatype Oracle Datatype Description
CHARACTER(n),
CHAR(n)
CHAR(n) Fixed length character data of length n bytes. Maximum n is 2000. Default and minimum n is 1 byte. Values are padded with blanks to the specified length.

Examples

  • Storing "Joe" in a CHAR(10) datatype would result in Joe and seven blanks
CHARACTER VARYING(n),
CHAR VARYING(n)
VARCHAR2(n) Variable length character string having maximum length n bytes. Maximum n is 4000, and minimum is 1. You must specify n for a VARCHAR2
NUMERIC(p,s),
DECIMAL(p,s)
NUMBER(p,s) Number having precision p and scale s. The precision p can range from 1 to 38. The scale s can range from -84 to 127.

Examples

  • NUMBER(2) - Two digit before the decimal place and zero digits after
  • NUMBER(4,2) - Two digit before the decimal place and two digits after
  • NUMBER(6,-2) -Eight digits, with the last two digits always zero.
INTEGER, INT,
SMALLINT
NUMBER(38) Number with precision 38. This is the maximum digits allowed by the system with no digits after the decimal.
FLOAT(b),
DOUBLE PRECISION,
REAL
NUMBER The FLOAT datatype is a floating point number with a binary precision b. This default precision for this datatype is 126 binary, or 38 decimal. The DOUBLE PRECISION datatype is a floating point number with binary precision 126. The REAL datatype is a floating point number with a binary precision of 63, or 18 decimal.

DATE Valid date range from January 1, 4712 BC to December 31, 4712 AD.
LOB(size) There are three LOB or Large OBject data types. LOB data types can contain up to 4 GB of data.

  • CLOB - is used to store long variable-length character strings
  • BLOB - is used to store binary large objects, such as bitmaps of audio or video images
  • BFILE - is a database reference to an operating system file that is stored outside of Oracle
Note Oracle7 used LONG or LONG RAW data types to store very long strings or large binary objects of up to 2 GB of data.
ROWID Hexadecimal string representing the unique address of a row in its table. This datatype is primarily for values returned by the ROWID pseudocolumn.

4.2. Basic SQL DML Commands

DML short for Data Manipulation Language allows you to maintain and manipulate database data.

4.2.1. The SQL SELECT Command

The SQL SELECT command is used for retrieving data from one or more tables, views, or snapshots in the database.

4.2.2. The SQL INSERT Command

The SQL INSERT command allows you to add rows to a table or to a view's base table.

4.2.3. The SQL UPDATE Command

The SQL UPDATE command allows you to change existing values in a table or in a view's base table.

4.2.4. The SQL DELETE Command

The SQL DELETE command allows you to remove rows from a table or from a view's base table.

4.2.5. Search Conditions

This section explains the various search conditions supported by Oracle SQL. Search conditions are the search criteria you specified to qualify the selection of data. They are used in where and having clauses in your SQL statements.

More than one search conditions can be used in a SQL statement with the logical operators and, or, and not together with parentheses to indicate clauses [e.g. (deptno=1 and sal>30000) or (deptno=2 and sal>25000)].

A search condition must include at least one of the following predicates:

Predicate Functions and Examples
ComparisonSyntax:

= equal to
<> not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to

Example:

select ename from emp where sal >= 50000;

LikeSyntax:

columnname [not] like pattern

where pattern is a string constant and pattern matching characters are:

% (percent sign) matches 0 or more characters
_ (underscore) matches exactly one character

Example:

select * from emp where ename like 'S%';

BetweenSyntax:

y [not] between x and z

Example:

select * from emp
where sal between 25000 and 55000;

InSyntax:

y [not] in (x, ..., z)
y [not] in (subquery)

Examples:

  1. select *
    from emp
    where ename in ('Smith', 'Smyth');

  2. select * from dept
    where deptno not in
    (select distinct deptno from emp);
    Any-or-AllSyntax:

    = any|all(options|subquery)
    <> any|all(options|subquery)
    > any|all(options|subquery)
    >= any|all(options|subquery)
    < any|all(options|subquery)
    <= any|all(options|subquery)

    Examples:

    1. select * from emp
      where ename = any ('Smith', 'Smyth');

      Note: This example is equivalent to the first example for the operator "in".

    2. select * from dept
      where deptno <> any
      (select distinct deptno from emp);

      Note: This example is equivalent to the second example for the operator "in".

    ExistsSyntax:

    [not] exists (subquery)

    Example:

    select * from dept
    where not exists
    (select * from emp where deptno=dept.deptno);

    Note: This example is equivalent to the second example for the operator "in".

    Is NullSyntax:

    is [not] null

    Example:

    select * from emp
    where
    job is null;

    4.2.6. The SQL Group Functions

    Group functions operate on an entire column of values rather than a single value. The group functions sometimes called "aggregate functions" or "set functions".

    For instant, you can obtain the average salary of all employees in the emp table using the avg function or count the number of employees using the count function. You may use the group by clause in conjunction with the group functions in the SQL select statement to divide data into groups.

    Available functions:

    Function NameDescription
    countReturns the number of rows in the query
    sumReturns sum of values of n
    avgReturns average value of n
    maxReturns maximum value of expr
    minReturns minimum value of expr
    stddevReturns standard deviation of x, a number. Oracle8 calculates the standard deviation as the square root of the variance defined for the VARIANCE group function
    varianceReturns variance of x, a number. Oracle8 calculates the variance of x using this formula:

    where:

    xi is one of the elements of x.

    n is the number of elements in the set x. If n is 1, the variance is defined to be 0.

    Examples:

    select count(*)
    from emp
    where deptno=1

    select count(distinct job) "Jobs"
    from emp

    select avg(sal) "Average"
    from emp group by deptno

    select max(sal) "Maximum"
    from emp

    select min(hiredate) "Minimum Date"
    from emp

    select stddev(sal) "Deviation"
    from emp

    select sum(sal) "Total"
    from emp

    select variance(sal)"Variance"
    from emp

    4.2.7. Views

    A view is a logical table that based on existing database tables and/or other views. A view can be used to hide complex or confidential data. Frequently used queries can also be stored as views for easy access.

    4.3. Granting Permission

    The SQL GRANT statement allows the owner to grant tables, views or objects access permissions to one or more users. The following table lists some valid permissions for use with the GRANT statement:

    Permission Type Description
    selectRetrieve data from a table or view
    updateUpdate data in a table or view
    insertInsert data into a table or view
    deleteDelete data from a table or view
    allAll of the above privileges

    Some examples on how to grant table permissions are as follow:

    grant all on emp to james;

    grant select, update (ename, deptno, job, hiredate) on table emp to betsy;

    grant select on emp to public;

    The keyword public includes all users that have access to the database.

    For those who are permitted to access another user's data, they must prefix the tables, views or objects with the schema name in their SQL statements. For example:

    select * from schema_name.emp;

    where schema_name is the username of the individual who owns the table emp.

    To remove partial or all the access permissions on a particular table, view or object, use the SQL REVOKE statement. Here are some examples:

    revoke update on emp from betsy;

    revoke all on emp from betsy;

    5. Object-Relational Extension

    One of the highlights in Oracle8 is its new object-relational capabilities. In the subsequent sections, we will discuss how to apply this powerful feature to the relational data.

    5.1. Define Object Types

    Object type is a user-defined data type that contains attributes and methods. The attributes of the object type could be based on either an Oracle built-in data type or a user-defined data type. Methods are user-defined algorithms that automatically manipulate and alter the attributes. Simply put, the object type is like a template for use in other structures.

    5.2. Dropping Objects

    5.3. Create Column Objects

    A column in a relational table that is based on an object type is called an object column. Object columns can be created as part of the CREATE TABLE command or added with the ALTER TABLE command.

    5.4. Build Object Tables

    An object table is a table based on an object type. Each row in the table is called a row object and each column of the table corresponds to an attribute of the object type.

    5.4.1 Object Identifiers

    Object IDentifier (OID) is an unique identifier created for each row object in an object table. OIDs are unique within the database and are not reused even after the table is dropped.

    OID can be stored in a table that requires a pointer to a row object in an object table. It is the same idea as having a foreign key in the child table to point to a row in a parent table. The pointer or reference stored in the table is defined using the new built-in REF data type.

    5.5. Implement Object Methods

    Object methods or member methods are part of the object type definition and operate on the attributes of and object type. There are two types of object methods- the constructor method and the user-defined method.

    5.5.1 Constructor Methods

    Constructor method is created automatically whenever an object type is created. It has the same name as the object type. The purpose of the constructor method is to allow users to create an instance of the object type.

    5.5.2 User-defined Methods

    User-defined methods are PL/SQL functions that defined by the user during the object type creation. Creating user-defined methods involves two simple steps:

    1. Create object type definition, which includes the method specification

      • Syntax:

        MEMBER FUNCTION method_name RETURN datatype

        Note Multiple member methods are separated by commas.

      • Example:

        CREATE OR REPLACE TYPE address_type AS OBJECT
        (street VARCHAR2(25),
        city VARCHAR2(25),
        country VARCHAR2(25),
        postal_code CHAR(6),
        MEMBER FUNCTION get_location RETURN VARCHAR2,
        PRAGMA RESTRICT_REFERENCES (get_location, WNDS)) ;
        /

        Note that the "PRAGMA RESTRICT_REFERENCES (method_name, WNDS)" statement is included to ensure the method is free of side effect. Since most methods that will be used in SQL statements must be prevented from changing data, the writes no database state (WNDS) is specified in the above example.

    2. Create object type body, which includes the method code

      • Syntax:

        CREATE [OR REPLACE] TYPE BODY object_type_name AS
        MEMBER FUNCTION method_name RETURN datatype IS
        PL/SQL block

        Note that the object type body can be re-created at any time even if there are existing tables referencing the object type.

      • Example - the get_location method returns the concatenation of street and city separated by a comma.

        CREATE OR REPLACE TYPE BODY address_type AS
        MEMBER FUNCTION get_location RETURN VARCHAR2 IS
           BEGIN
             RETURN SELF.street || ', ' || SELF.city;
           END;
        END;
        /

        Note the optional keyword SELF is used to reference the object type attribute.

    5.5.3 Invoking Object Methods

    You invoke the method function in the SQL statement by referencing the object and method using the dot notation.

    5.5.4 Comparing Object

    There are three methods for comparing objects.

    1. Comparing values of each attribute (default method)

      • Example: - Check if 6225 University Ave, Canada, is in the company_address table.

        SELECT * FROM company_address ca
        WHERE VALUE(ca) = address_type('6225 University Ave', 'HALIFAX', 'CANADA', 'B3H4H8');

        Note Use the VALUE function on the object table and the constructor method for the input values.

    2. Using the MAP function

      The MAP function can be used to define an alternative way for comparing objects. Oracle automatically compares objects based on the return value. The return value must be a scalar data type such as NUMBER or VARCHAR2. Another restriction is that the MAP function cannot pass any parameters.

      • Syntax:

        MAP MEMBER FUNCTION method_name RETURN datatype

      • Example: - change the comparison of address objects to be based only on street and city.

        To do this, we must first redefine the object function with the MAP keyword. Also note that you must drop all referencing object tables and object types before you could change the definition.

        CREATE OR REPLACE TYPE address_type AS OBJECT
        (street VARCHAR2(25),
        city VARCHAR2(25),
        country VARCHAR2(25),
        postal_code CHAR(6),
        MAP MEMBER FUNCTION get_location RETURN VARCHAR2,
        PRAGMA RESTRICT_REFERENCES (get_location, WNDS, WNPS, RNDS, RNPS)) ;
        /

        Next, change the body of the function.

        CREATE OR REPLACE TYPE BODY address_type AS
          MAP MEMBER FUNCTION get_location RETURN VARCHAR2 IS
          BEGIN
            RETURN SELF.street || ', ' || SELF.city;
          END;
        END;
        /

        Now, try query following query:

        SELECT * FROM company_address ca
        WHERE VALUE(ca) = address_type('6225 University Ave', 'HALIFAX', 'dummy', 'dummy');

    3. Using the ORDER function

      The third way to compare objects is using the ORDER function. Similar to the MAP function, Oracle automatically compares objects based on the return value. For ORDER function, however, it must return an integer value and an object parameter is requried as input. As the name implies, the ORDER function is used when comparisons are often required for sorting.

      • Syntax:

        ORDER MEMBER FUNCTION method_name (parameter object_type_name) RETURN INTEGER

    5.5.5 Data Dictionary Views for Methods

    Oracle provides the data dictionary views for methods:

    5.6. Define VARRAYS

    VARRAY or Variable-size array is a new data type in Oracle8. It allows grouping of similar items into a collection. The size of the array is determined by the number of elements in the array. Each element has an index corresponding to its position in the array.

    5.6.1 VARRAYS Limitations

    The following are some limitations of VARRAY:

    VARRAY cannot be used with

    5.7. Build Object Views

    As an alternative to constructing object relational tables, Object Views can be used to make the relational tables look like object relational tables. The steps required to create object views are as follow:
    1. Create the object type to be used by the view.

    2. Create the object view that references the object type.

    6. Trouble Shooting

    6.1. The "ksh: sqlplus: not found" Error

    If you are getting the "ksh: sqlplus: not found" message while trying to run Oracle SQL*Plus, here are the tips to fix the problem:
    1. Make sure that the file .using_oracle8 exists in your login directory. If not, please refer to Section 2.2. Host Login and Initial Oracle Setup Procedure for details.

    2. Most likely your PATH statement in your .profile overwrites the Oracle PATH set by the system. Here is the correct way for setting the PATH in .profile:
        export PATH=$PATH:insert_user_path_here:
      
        For example:
      
        export PATH=$PATH:/home/m/myusername/bin: