Disclaimer
Copyright © 1998-2000 Dalhousie
University
Last Updated: Mar, 1999 by Poh Chua (poh.chua@dal.ca)
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:
(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 usernameWhere 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.
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.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:
Command | Abbreviation | Purpose |
APPEND text | A text | adds text at the end of a line |
0 text | 0 text | adds text before the first line |
CHANGE /old/new | C /old/new | changes old to new in a line |
CHANGE /text | C /text | deletes text from a line |
CLEAR BUFFER | CL BUFF | deletes 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) |
INPUT | I | adds one or more lines |
INPUT text | I text | adds a line consisting of text |
LIST | L | lists all lines in the SQL buffer |
LIST n | L n or n | lists line n |
LIST * | L * | lists the current line |
LIST LAST | L LAST | lists the last line |
LIST m n | L m n | lists a range of lines (m to n) |
SQL> run or SQL> /
SQL> list 1 select empno, ename, job, sal2 from emp 3* where sal < 1000 SQL> save filenamewhere filename is the name of your output file. The default file extension is .sql
SQL> start filename or SQL> @filenameThe @ command can also be used to run a command file at the operating system prompt. Here is the example:
$ sqlplus [username[/password]] @filenameSQL*Plus will prompt you for your username and password if not specified.
SQL> spool assignment1 SQL> (your SQL command here) SQL> (your SQL results) SQL> spool offNote 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 filenamewhere 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 *.sqlYou 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.
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.
Command | Description | |
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] objectname | Displays 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. | |
SET | Sets 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
create table tablename
(columnname datatype
[not null][default expr][column_constraint]
{, columnname datatype
[not null][default expr][column_constraint]}
[table_constraint{, table_constraint}]);
drop table dept; create table dept ( deptno number(2) not null, dname varchar2(20) not null, primary key (deptno)); drop table emp; create table emp ( empno number(4) not null, ename varchar2(25), job varchar2(9), hiredate date, sal float check(sal >= 0.00), deptno number(2), primary key (empno), foreign key (deptno) references dept);
4.1.2. The CREATE TABLE AS Command
create table tablename
[(columnname format {, columnname format})] as
select...;
Create a new table with all employees who now earn more that $50,000.
create table overpaid as
select * from emp where sal > 50000;
commit;
describe emp;
alter table emp
add (bonus number(5,2));
alter table emp
modify (deptno number(2) not null);
select *
from user_tables;
drop table tablename;
drop table overpaid;
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
| ||||||||||||||||||
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
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.
|
| ROWID
| Hexadecimal string representing the unique address of a row in its table. This datatype is primarily for values returned by the ROWID pseudocolumn.
| |
insert into tablename [column {,column}]
values (expression {,expression})
insert into dept (deptno,dname)
values (1,'Marketing');
or
insert into dept
values (1,'Marketing');
update tablename [corr_name]
from tablename [corr_name] {, tablename [corr_name]}
set columnname=expression {, columnname=expression}
[where search_condition]
update emp
set sal = 23000
where empno = 784;
commit;
Update emp e
from dept d
set sal = e.sal * 1.10
where e.deptno = d.deptno
and d.dname = 'Marketing';
commit;
delete from tablename [corr_name]
[where search_condition]
delete from emp
where empno = 98;
commit;
delete from temp_emp;
commit;
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 |
Comparison | Syntax: = equal to
Example: select ename from emp where sal >= 50000; |
Like | Syntax: columnname [not] like pattern where pattern is a string constant and pattern matching characters are:
% (percent sign) matches 0 or more characters
select * from emp where ename like 'S%'; |
Between | Syntax: y [not] between x and z
Example:
select * from emp |
In | Syntax: y [not] in (x, ..., z)
Examples:
|
Any-or-All | Syntax: = any|all(options|subquery)
Examples:
|
Exists | Syntax: [not] exists (subquery)
Example:
select * from dept Note: This example is equivalent to the second example for the operator "in". |
Is Null | Syntax: is [not] null
Example:
select * from emp |
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 Name | Description |
count | Returns the number of rows in the query |
sum | Returns sum of values of n |
avg | Returns average value of n |
max | Returns maximum value of expr |
min | Returns minimum value of expr |
stddev | Returns standard deviation of x, a number. Oracle8 calculates the standard deviation as the square root of the variance defined for the VARIANCE group function |
variance | Returns 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:
create [or replace] view viewname
[(column_name{, column_name})] AS subquery;
create or replace view overpaid_view
as select * from emp where sal > 50000;
desc overpaid_view;
select * from overpaid_view;
drop view overpaid_view;
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 |
select | Retrieve data from a table or view |
update | Update data in a table or view |
insert | Insert data into a table or view |
delete | Delete data from a table or view |
all | All of the above privileges |
Some examples on how to grant table permissions are as follow:
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:
To remove partial or all the access permissions on a particular table, view or object, use the SQL REVOKE statement. Here are some examples:
CREATE [OR REPLACE] TYPE object_type_name AS OBJECT
Note Both semicolon and slash are required to create an object
CREATE OR REPLACE TYPE address_type AS OBJECT
CREATE OR REPLACE TYPE company_type AS OBJECT
Note address in company_type inherits the definition from address_type
SELECT type_name, attributes, methods FROM user_types;
DESC address_type;
DROP TYPE object_type_name [FORCE];
Note use the FORCE keyword to remove the object type and all its references in dependent object types.
DROP TYPE address_type FORCE;
Note The FORCE keyword also removes the address attribute from company_type
column_name built-in datatype | object_type_name NOT NULL
create table company (
Note If you tried the example in previous section and the address_type was dropped, you must recreate the address_type before you try to create the company table.
INSERT INTO company (company_name, address)
SELECT company_name, address FROM company;
CREATE TABLE table_name OF object_type;
Note The object type must be defined first.
CREATE TABLE company_address OF address_type;
INSERT INTO company_address
VALUES (address_type('6225 University Ave', 'HALIFAX', 'CANADA', 'B3H4H8'));
DESC company_address
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.
column_name REF object_type [SCOPE IS object_table_name]
Note the optional SCOPE clause limits the reference to a specific object table.
ALTER TABLE company
UPDATE company
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.
INSERT INTO company (company_name, address)
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:
MEMBER FUNCTION method_name RETURN datatype
Note Multiple member methods are separated by commas.
CREATE OR REPLACE TYPE address_type AS OBJECT
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.
CREATE [OR REPLACE] TYPE BODY object_type_name AS
Note that the object type body can be re-created at any time even if there are existing tables referencing the object type.
CREATE OR REPLACE TYPE BODY address_type AS
Note the optional keyword SELF is used to reference the object type attribute.
You invoke the method function in the SQL statement by referencing the object and method using the dot notation.
table_alias.method(parameters)
Note that parameters must be separated by commas.
SELECT ca.get_location() address
Note that parentheses are required for the method even if no parameters are being passed.
There are three methods for comparing objects.
SELECT * FROM company_address ca
Note Use the VALUE function on the object table and the constructor method for the input values.
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.
MAP MEMBER FUNCTION method_name RETURN datatype
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
Next, change the body of the function.
CREATE OR REPLACE TYPE BODY address_type AS
Now, try query following query:
SELECT * FROM company_address ca
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.
ORDER MEMBER FUNCTION method_name (parameter object_type_name) RETURN INTEGER
SELECT type_name, method_name, method_type FROM user_type_methods;
CREATE TYPE varray_type_name AS VARRAY(size) OF datatype;
Note: The size parameter specified the maximum number of elements in a VARRAY. The datatype must be of scalar data type such as number or varchar2.
CREATE TYPE phone_varray_type AS VARRAY(5) OF VARCHAR2(15);
ALTER TABLE emp
Note:When you create a table column based on a VARRAY type, the VARRAY data are stored in the same segment as the table if the size is less than 4k bytes. Otherwise, there are stored in a separate BLOB.
INSERT INTO emp (empno, ename, job, hiredate, sal, deptno, tel_no) VALUES
SELECT ename, tel_no FROM emp;
Note: that VARRAY is treated as a single unit in SQL as such individual VARRAY elements cannot be queried using SQL directly.
UPDATE emp
Note: You must update all the elements in VARRAYS because VARRAY is treated as a single unit in SQL.
VARRAY cannot be used with
CREATE OR REPLACE TYPE dept_type AS OBJECT
CREATE OR REPLACE VIEW emp_view
Note: Assuming that the "dept" and "emp" table exist.
CREATE OR REPLACE VIEW dept_view
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.
(attribute_name datatype,
attribute_name datatype);
/
(street VARCHAR2(25),
city VARCHAR2(25),
country VARCHAR2(20),
postal_code CHAR(6));
/
(company_name VARCHAR2(25),
address address_type);
/
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.
company_name varchar2(25),
address address_type);
VALUES ('ABC', address_type('6225 University Ave', 'HALIFAX', 'CANADA', 'B3H4H8'));
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
ADD ( mailing_address REF address_type SCOPE IS company_address );
SET mailing_address =
(SELECT REF(ca)
FROM company_address ca
WHERE city = 'HALIFAX')
WHERE company_name = 'ABC';
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
VALUES ('XYZ', address_type('5 Main Street', 'HALIFAX', 'CANADA', 'B3J5M7'));
5.5.2 User-defined Methods
(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)) ;
/
MEMBER FUNCTION method_name RETURN datatype IS
PL/SQL block
MEMBER FUNCTION get_location RETURN VARCHAR2 IS
BEGIN
RETURN SELF.street || ', ' || SELF.city;
END;
END;
/
5.5.3 Invoking Object Methods
FROM company_address ca;
5.5.4 Comparing Object
WHERE VALUE(ca) = address_type('6225 University Ave', 'HALIFAX', 'CANADA', 'B3H4H8');
(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)) ;
/
MAP MEMBER FUNCTION get_location RETURN VARCHAR2 IS
BEGIN
RETURN SELF.street || ', ' || SELF.city;
END;
END;
/
WHERE VALUE(ca) = address_type('6225 University Ave', 'HALIFAX', 'dummy', 'dummy');
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.
/
ADD (tel_no phone_varray_type);
(1234, 'David', 'Manager', '1-Feb-1999', 50000, 1
, phone_varray_type('(902)444-4444', '(902)444-5555'));
SET tel_no = phone_varray_type('(902)444-4444', null))
WHERE empno=1234;
5.6.1 VARRAYS Limitations
The following are some limitations of VARRAY:
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:
(deptno number(2),
dname VARCHAR2(20));
/
AS SELECT e.ename, dept_type(d.deptno, d.dname)
dept
FROM emp e, dept d
WHERE e.deptno = d.deptno;
OF dept_type WITH OBJECT OID(deptno)
AS SELECT deptno, dname
FROM dept;
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:
export PATH=$PATH:insert_user_path_here:
For example:
export PATH=$PATH:/home/m/myusername/bin: