0% found this document useful (0 votes)
46 views12 pages

PL/SQL. in This Tutorial, You Will Interact With Oracle Database, Thru SQL Plus, by Issuing A

This document provides an overview of interacting with an Oracle database using SQL*Plus, Oracle's command line interface. It discusses how to log in to SQL*Plus, change passwords, create and manipulate tables using SQL commands like CREATE TABLE, INSERT, UPDATE, DELETE, and SELECT. It also covers committing transactions to save changes, rolling back to undo changes, and dropping tables. The document provides examples of each command and exercises for the user to practice creating a table and inserting, updating, deleting, and selecting records in Oracle.

Uploaded by

umagomathy
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views12 pages

PL/SQL. in This Tutorial, You Will Interact With Oracle Database, Thru SQL Plus, by Issuing A

This document provides an overview of interacting with an Oracle database using SQL*Plus, Oracle's command line interface. It discusses how to log in to SQL*Plus, change passwords, create and manipulate tables using SQL commands like CREATE TABLE, INSERT, UPDATE, DELETE, and SELECT. It also covers committing transactions to save changes, rolling back to undo changes, and dropping tables. The document provides examples of each command and exercises for the user to practice creating a table and inserting, updating, deleting, and selecting records in Oracle.

Uploaded by

umagomathy
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Overview

Oracle is one the most popular Relational Database Management System (RDBMS).  Some other
famous RDBMS includes Microsoft SQL Server, Sybase, MySQL, PostgreSQL, etc. 
Essentially, all the aforementioned RDBMS employs Structural Query Language (SQL) as their
query interface.  Users usually issue their queries by SQL through a "client".  Different RDBMS
offer different forms of clients.  For example, MS SQL Server offers a GUI interface for user to
type in their SQL language, and their queries would be executed after pressing the "Execute"
button on the client.  Oracle provides both GUI client and command-line client.  In this lesson,
we will study the command-line client, SQL*Plus.  In addition,  Oracle extends the standard
SQL  (e.g. select * from table) with its application-specific commands (e.g. checking how many
table you have been created in your Oracle account) into a Oracle specific language called
PL/SQL.  In this tutorial, you will interact with Oracle database, thru SQL*Plus, by issuing a
number of PL/SQL queries.

Logging In to Oracle [FOR ECOM-ICOM LAB ONLY]

Microsoft Windows

Under Windows environment, the Oracle client is called SQL*Plus.


Steps:

1.    Click Start, and then click Run.


2.    Type sqlplus, and fill in the username, password, and database name
3.    After you log in to SQL*Plus, you see the following message:
Connected to:
Oracle9i Enterprise Edition Release 9.1.7.0.0 - Production
JServer Release 9.1.7.0.0 - Production
      and you should receive the prompt:
SQL>

Changing Your Password

In response to the SQL> prompt, type

     alter user <yourName> identified by <newPassword>;


where <yourName> is again your login name, and <newPassword> is the password you would
like to use in the future. This command, like all other SQL commands, should be terminated with
a semicolon.

Creating Tables
In SQL*Plus we can execute any SQL command. One simple type of command creates a table
(relation). The form is

     CREATE TABLE <tableName> (

         <list of attributes and their types>

     );

You may enter text on one line or on several lines. If your command runs over several lines, you
will be prompted with line numbers until you type the semicolon that ends any command.
(Warning: An empty line terminates the command but does not execute it; see editing
commands in the buffer.) An example table-creation command is:

     CREATE TABLE test (

         i int,

         s char(10)

     );

Note that SQL is case insensitive, so CREATE TABLE TEST and create table test are the
same. This command creates a table named test with two attributes. The first attribute, named
i, is an integer, and the second, named s, is a character string of length (up to) 10.

Exercise 1:

Create a relation Student that suitable for the following instance:


 

SID NAME JOB Salary STREAM START_AT


1  Ben Kao  Associate Professor  7000  E  01-Sep-1995
2  Eric Lo Teaching Assistant 1000  E 01-Oct-2003
3  Hammer Lecturer 7000  E 11-Feb-2000
4  Angela Castro Program Manager 6000  I 12-Dec-1999
5  Steven Chu Project Assistant 7000  I 13-Dec-2002

Note: No need to insert the data yet!

Inserting Tuples

Having created a table, we can insert tuples into it. The simplest way to insert is with the INSERT
command:
INSERT INTO <tableName>

         VALUES( <list of values for attributes, in order> );


For instance, we can insert the tuple (10, 'hi world') into relation test by
     INSERT INTO test VALUES(10, 'hi world');
Exercise 2:
Insert the records as stated into Exercise 1 into the student table.

Trick: Try to insert a record into test with the following SQL:

INSERT INTO test VALUES(11, 'ha 'world');

Updating Tuples

Tuples can be updated by the UPDATE command:

      UPDATE <tableName>

         SET <Attribute>=<Expression/Value>

WHERE <Predicate>;

For example, we can update the tuple (10, 'hi world') in relation test by

     UPDATE test SET s='bye world' WHERE i=10;


Exercise 3:

Update the record of 'Eric Lo' in relation Student such that his salary change to 1234

Deleting Tuples

Having insert / update a tuple, we can delete it as well. The simplest way to delete is with the
DELETE command:

      DELETE FROM <tableName> [WHERE <condition>];


<condition> is an optional statement and is used to identify a single record when necessary.

For example, you can delete the record with i=10 in table test with the the following SQL:

     DELETE FROM test WHERE i=10;

Exercise 4:
Delete the record of 'Eric Lo' in relation Student.

Trick: Does that record really deleted successfully?  Let's check it out by using SELECT
command (we will cover it in next section).

Retrieving Tuples

We can see the tuples in a relation with the command:

SELECT <attributes-separated-by-comma>/<wildcard>

FROM <tableName>;
For instance, after the above CREATE, INSERT, DELETE and UPDATE statements, the
command
     SELECT * FROM test;
produces the result
              I S

     ---------- ----------

             11 ha 'world

Exercise 5:

Select ALL records from relation Student.

Question: Do data values also case insensitive? i.e., can a student with name "Hammer" be
retrieved by the following SQL or not?

     SeLecT name from StudenT where name ='hammer';

Let's check it out by yourself!

Trick: Does the record of  'Eric Lo' exist when you do exercise 5?  If yes, congratulation! You
"seems" that you have deleted that tuple successfully...  Now, please open a new SQL*Plus, and
redo exercise 5 to see if the record 'Eric Lo' still be there?  What happen?

Commit and Rollback

An automatic commit occurs under the following circumstance:


 DDL statement is issued
 Normal exit from SQL*Plus, without explicitly issuing COMMIT or ROLLBACK

An automatic rollback occurs under an abnormal termination of SQL*Plus or a system failure.

It provides a good back-door for you to revert the changes you have done on the data.  Therefore,
unless you have issued COMMIT, the changed data would not be visible to any other session
except your own. Conversely, you can rollback all the changes by issuing the ROLLBACK
command.

Exercise 6:

Issue the COMMIT command in the SQL*Plus that you have done insert/delete/update before,
and see if the effects is now visible by the new SQL*Plus?

Dropping Tables

To remove a table from your database, execute

     DROP TABLE <tableName>;


We suggest you execute
     DROP TABLE test;

Caution: Table dropping is a DML statement, which is an action that you cannot rollback.  Since
dropping a table will also delete all data in that table, issue the DROP TABLE command with
cares.

Getting Information About Your Database

The system keeps information about your own database in certain system tables. The most
important for now is USER_TABLES. You can recall the names of your tables by issuing the query:

     SELECT TABLE_NAME

     FROM USER_TABLES;


More information about your tables is available from USER_TABLES. To see all the attributes of
USER_TABLES, try:
     SELECT *

     FROM USER_TABLES;


It is also possible to recall the attributes of a table once you know its name. Issue the command:
     DESCRIBE <tableName>;
to view the schema of  <tableName>;

Quitting SQL*Plus

To leave SQL*Plus, type

     quit;
in response to the SQL> prompt.

Executing SQL From a File

Instead of executing SQL commands typed at a terminal, it is often more convenient to type the
SQL command(s) into a file and cause the file to be executed. There are two ways to do so.

The first is to provide your login name, password and the name of the file in the command line
with which you open SQL*Plus. The form of the command is:

     SQL*Plus <yourName>/<yourPassword> @<fileName>


For instance, if user scott, whose password is tiger, wishes to execute the file foo.sql, then
he would execute the SQL in foo.sql by:
     SQL*Plus scott/tiger @foo
Notice that this mode presents a risk that scott's password will be discovered, so it should be
used carefully. Also note that since scott did not specify an extension for the file name "foo",
SQL*Plus implicitly assumes the default extension ".sql". Therefore, it is a good idea to give
every command file an extension, and specify the complete file name with the extension after the
"@".

A second, safer way, is for sally to log in to SQL*Plus as usual. He then types, in response to
the SQL> prompt:

     @foo.sql
and the file foo.sql's contents will be executed.

Editing Commands in the Buffer

If you end a command without a semicolon, but with an empty new line, the command goes into
a buffer. You may execute the command in the buffer by either the command RUN or a single
slash (/).

You may also edit the command in the buffer before you execute it. Here are some useful editing
commands. They are shown in upper case but may be either upper or lower.
 
L[IST] Lists the command buffer, and makes the last line in the buffer the "current" line

L[IST] n Prints line n of the command buffer, and makes line n the current line

L[IST] m n Prints lines m through n, and makes line n the current line

I[NPUT] Enters a mode that allows you to input text following the current line; you must
terminate the sequence of new lines with a pair of "returns"

I[NPUT] text Inserts a line consisting of text

C[HANGE] /old/new Replaces the text "old" by "new" in the current line

C[HANGE] / text / Delete text from the current line

A[PPEND] text Appends "text" to the end of the current line

DEL Deletes the current line

DEL n Deletes line n

DEL m n Deletes lines m to n inclusive

CL[EAR] BUFF[ER] Deletes all lines from the SQL buffer>

R[UN] or / Displays and runs the current SQL statement in the buffer

n Specifies the line to make the current line

n text Replaces line n with text

0 text Inserts a line before line 1

SAV[E]
filename[.ext] Saves current contents of SQL buffer to a file. The default extension is .sql.

GET filename[.ext] Writes the contents of a previously saved file to the SQL buffer. The default
extension for the filename is .sql.

STA[RT]
filename[.ext] Runs a previously saved command file

ED[IT] Invokes the editor and saves the buffer contents to a file named afiedt.buf

ED[IT]
[filename[.ext]] Invokes the editor to edit contents of a saved file

Recording Your Session


You can use the spool command within SQL*Plus to dump your terminal output.  At the SQL>
prompt, you type:

    spool foo;


and a file called foo.lst will appear in your current directory and will hold everything typed,
until you exit SQL*Plus or type:
    spool off;

Help and Other Hints

In response to the SQL> prompt, type help followed by a keyword. If you are lucky, the keyword
will be one of those for which help exists, and you will get a (somewhat) helpful message,
usually ending in an example or two. To see all the possible commands, for each of which help is
available, type

    help commands;


The output from help, and in general, the results of many SQL commands, can be too long to
display on a screen. You can use
    set pause on;
to activate the paging feature.  When this feature is activated, output will pause at the end of each
screen until you hit the "return" key. To turn this feature off, use
    set pause off;

Data Types

Here is part of the data types that are supported by Oracle.


 

Data Type Description


VARCHAR2 Variable-length character data (a maximum size must be specified: Minimum size is 1; maximum
(size) size is 4000)
CHAR Fixed-length character data of length size bytes (default and minimum size is 1; maximum size is
[(size)] 2000)
NUMBER Number having precision p and scale s (The precision is the total number of decimal digits, and the
[(p,s)] scale is the number of digits to the right of the decimal point; the precision can range from 1 to 38
and the scale can range from -84 to 127)
DATE Date and time values to the nearest second between January 1, 4712 B.C., and December 31, 9999
A.D.

Joining Tables
As mentioned in the lectures, joining is an essential step to retrieve information across different
tables.  In SQL, there is no operator dedicated for joining.  Therefore, in order to join on two
tables, you have do a Cartesian product on two tables and then specifying the conditions.

For example, you have another two tables table1 and table2 which is created by the
following SQL:

     CREATE TABLE table1 (


         i int,
         s char(20)
     );

     CREATE TABLE table2 (


         i int,
         s char(20)
     );

Now, type 'ed' and open a text file to insert the following tuples into  table1 and table2:

         INSERT INTO table1 VALUES(1, 'table1one');


         INSERT INTO table1 VALUES(2, 'table1two');
         INSERT INTO table1 VALUES(3, 'table1three');
         INSERT INTO table1 VALUES(4, 'table1four');
         INSERT INTO table2 VALUES(4, 'table2four');
         INSERT INTO table2 VALUES(5, 'table2five');
         INSERT INTO table2 VALUES(6, 'table2six')
/

Then, you have join the two tables with the following SQL:

          SELECT * FROM  table1 t1, table2 t2


    WHERE t1.i = t2.i;

Exercise 6: (A mini quiz)

1) Create another table call Streams with the following values:

Stream_Code Stream_Name
E Ecom
I Icom

2) Join the table Student and Streams to list the information the

 sid
 name
 job
 salary
 stream

   of students with salary > 6500

Functions

Oracle offers some numeric and string functions for users to display the result in a more
desirable format.  For example, the SUBSTR(A, 1, 4) function returns the first four
characters for every data value.  Therefore, the SQL:

        SELECT SUBSTR(Stream_Name, 1,3) as XXX FROM Streams;

will the result like this:

        XXX

     ----------

Eco

Ico

The following table gives you an overview of a subset of functions Oracle provided:

Numeric/Alphabetic Function Purpose Example


Rounds the column <column> ROUND(45.926,2) gives
Numeric ROUND(<column>,n)
to n decimal places 45.93
Truncates values to specified TRUNC(45.926,2) gives
Numeric TRUNC(<column>,n)
decimal 45.91
Returns the reminder of m
Numeric MOD(m,n) MOD(1600,300) gives 100
divided by n
Alphabetic LOWER(column) Converts to lower case
Alphabetic UPPER(column) Converts to upper case
Returns the substring starts from SUBSTR('Eric Lo', 2, 4)
Alphabetic SUBSTR(column,m,n))
m to n gives 'ric'
CONCAT(column1,
Alphabetic String concatenation
column2)
Alphabetic LENGTH(column) Shows the length of a string

Aggregate Functions and Group-By Clause


We would demonstrate the aggregate functions and group-by clause by a number of SQL
queries.

1.  Find the average salary of students in Ecom Stream

     SELECT AVG(Salary) FROM Student WHERE Stream = 'I';

2.  Find the average salary of students in each Stream

     SELECT Stream, AVG(Salary) FROM Student GROUP BY Stream;

3.  Find the total number of students

     SELECT COUNT(*) FROM Student;

4.  Find the total number of student in each Stream

     SELECT COUNT(*), StrEAM FROM Student GROUP BY Stream;

5.  Find the total number of student in each Stream that have more than 2 students

     SELECT COUNT(*) FROM Student GROUP BY Stream HAVING COUNT(*)


> 2;

Creating Tables with Keys

To create a table that declares attribute a to be a primary key:

     CREATE TABLE <tableName> (..., a <type> PRIMARY KEY,


b, ...);

To create a table that declares the set of attributes (a,b,c) to be a primary key:

     CREATE TABLE <tableName> (<attrs and their types>, PRIMARY


KEY (a,b,c));

Creating Index

In fact, a unique key is created automatically when you define a PRIMARY KEY in table
definition.

To create an index on or more columns explicitly, you can:


     CREATE INDEX <index> on <table> (column 1, ..., column n);

Summary

During this session, astute students may notice that some queries are highlighted in blue, and
some queries are highlighted in green.  In fact, only the green queries are in the SQL standard. 
This is because different vendors may implement the standard differently.  For example, Oracle
implement the SUBSTRING function with the name "SUBSTR" instead of "SUBSTRING". 
Other than having different naming convention between implementation and specification, some
vendors may even skip some operators.  For example, Oracle does not implement the
union/intersection/except operators.  On the other hand, the queries in blue are PL/SQL, a
language that incorporate the SQL and oracle commands together.  Luckily, what you have learnt
in lectures is the core of SQL specification and supported by most DBMS.

Cheer!

You might also like