Anda di halaman 1dari 12

What is an Oracle database?

Oracle is an object-relational hybrid database - a relational database with added objectoriented features - and, since Oracle 10g, a grid-enabled database - the ability to scale across multiple inexpensive servers to provide more processing resources. Each release of the Oracle database brings new features to improve scalability, reliability, performance and availability. We'll be examining some of these new features in later Oracle tutorials.

Oracle SQL Tutorial


SQL*Plus schemata data types DML & DDL examples editing commands using external files the dual pseudo-table introduction to transactions optional exercise references.

Introduction
During this tutorial you will build on your databases knowledge by learning the fundamentals of Oracle, one of the most widely used database management system in industry.

SQL*Plus
SQL*Plus is Oracle's command-line interpreter. You may launch SQL*Plus by issuing the sqlplus command in UNIX or using the `start' menu in Windows. In the `start' menu, SQL*Plus is listed under programs > oracle > application development > SQL Plus. You will be prompted for your username and password. If you haven't got an account, you can try to use scott for the username, and tiger for the password. You will learn at a later stage how to change your password. The last piece of information required by SQL*Plus is the name of the database you want to use (called host string). You are now connected to a shared database, on which you have an account (called a schema ).

Basic SQL
Table 1 outlines the main Oracle SQL data types, together with their MySQL equivalent. Note is the VARCHAR2 type, so called for historical reasons. The NUMBER(p,s) type takes two arguments; precision and scale. The precision of a number its number of significant decimal digits, and its scale is the number of digits after the decimal point.

Table 1: The main SQL data types. Type description Oracle SQL MySQL SQL

variable-length char. string VARCHAR2(l)1 VARCHAR(l) fixed-length char. string number currency date
1 2

CHAR(l)

CHAR(l)

NUMBER(p,s)2 NUMERIC(p,s) NUMBER(10,2) NUMERIC(10,2) DATE DATE

length. precision, scale.

You should now be able to create a few tables and populate them.
CREATE TABLE books ( title VARCHAR2(60), author VARCHAR2(60), isbn NUMBER(10,0) CONSTRAINT pk_books PRIMARY KEY, pub_date DATE DEFAULT SYSDATE ) / CREATE TABLE book_reviews ( isbn NUMBER(10,0) CONSTRAINT fk_books_booksrev REFERENCES books(isbn), reviewer VARCHAR2(30), comments VARCHAR2(150) ) /

Note the use of the SYSDATE function that returns the system's current date in the DEFAULT clause above. The `/' character terminates an SQL statement and submits it to SQL*Plus. You should be already familiar with the syntax of the primary key and referential integrity constraints. They function in Oracle in a similar fashion as in MySQL. pk_books and fk_books_booksrev are constraint names. Now check the schema of the tables you have just created using the desc <table_name> command (same command as in MySQL). Next, we want to insert some data into books and books_reviews:
INSERT INTO books VALUES ( 'The Importance of Being Earnest', 'Oscar Wilde', -- this is a comment

9876543210, '14-FEB-1895' ) / INSERT INTO book_reviews VALUES ( 9876543210, 'Alice', 'Excellent work, humorous and witty.' ) /

As shown above, the date format expected by Oracle is DD-MMM-YYYY or DDMMM-YY. The double hyphen sequence `- -' introduces a comment.

Editing Commands
Editing SQL*Plus' buffer.
As you may already have experienced, you cannot recall statements after they have been submitted to SQL*Plus. The ed command allows you to edit the SQL*Plus buffer in the system's default editor. After saving your changes, submit the statement with a `/'. Be aware that only the last statement submitted to SQL*Plus may be edited.

Using command files.


A practical approach to avoid inadvertently losing your SQL work is to use command files. 1. type in your SQL statements in your favourite editor. 2. save the file with the .sql extension in your home directory (e.g. myfile.sql) make sure that you get the correct extension, as some editors will attempt to append a .txt extension. 3. type in @myfile at the SQL*Plus command prompt to execute your SQL statement(s).

QL Tutorial, Part 2
SQL*Plus schemata data types DML & DDL examples editing commands using external files the dual pseudo-table introduction to transactions optional exercise references.

More Oracle SQL


You are now armed to attempt some more complex SQL expressions.

The dual pseudo-table.


Oracle insists that all SELECT statements be of the form ``SELECT <attribute> FROM <table>''even when the returned value does not depend on data stored in the database. The DUAL pseudo-table was introduced to allow such statements.
SELECT 'Hello' FROM DUAL / SELECT SYSDATE FROM DUAL / -- shows 'Hello' -- shows the date

Sequence numbers.
A SEQUENCE is an Oracle object that generates integers according to a specific pattern. Sequence numbers are commonly utilised to supply auto-generated primary keys. The default behaviour of a SEQUENCE is to increment its current value by one to get the next. You may already have used sequences in MySQL, using the AUTO_INCREMENT attributes. Note however the two differences with Oracle's sequences:
y y

in MySQL, numeric fields using AUTO_INCREMENT need to be declared as such, in Oracle sequences are separate entities MySQL increments the sequence when required, you do not have to do it explicitly

The following code creates a SEQUENCE that we will then use to insert some more values in the books table.
CREATE SEQUENCE book_seq / INSERT INTO books VALUES ( 'Oliver Twist', 'Charles Dickens', book_seq.NEXTVAL, '12-SEP-1839' ) SELECT book_seq.CURRVAL FROM DUAL / SELECT book_seq.NEXTVAL FROM DUAL /

-- shows the current value -- displays the next value

Apart from the the Oracle peculiarities we have already discussed, you can re-use most of your knowledge of SQL. You may want for example to experiment with the UPDATE and DELETE statements.

Introduction to Transactions
Transaction management is a broad topic to which you have been introduced in the database lectures. You should refer to your notes for a more detailed coverage of the subject, as we will here just remind a few points. A transaction is a logical unit of work , that could be for example the placement of an order. On completion, a transaction needs to be either confirmed making all the changes permanentor cancelled returning

the database into the state it was before starting the transaction. These two actions are performed in SQL by issuing one of the two commands COMMIT or ROLLBACK. To experiment with transactions, you will need to work in pairs (say Alice and Bob) and allow the other student to read the data in your books table. So Alice will need to enter:
GRANT SELECT ON books TO bob /

and Bob to enter:


GRANT SELECT ON books TO alice /

Now Alice should enter some data in her books table. Bob can then attempt to view the newly inserted data by typing:
SELECT * FROM alice.books /

Note how you can prefix the table name with its schema to reference other students' tables. Can Bob view the changes Alice has made? What happens if Alice COMMITs the transaction? Try also with ROLLBACK. Try to relate your observations with your understanding of transactions.

PL/SQL Tutorial
Need for PL/SQL declarative vs. procedural anonymous blocks debugging a first program code compilation code execution procedures & functions PL/SQL in SQL SQL in PL/SQL cursors & loops operators & built-in functions reference tables.

Introduction
PL/SQL is a database-oriented programming language that extends Oracle SQL with procedural capabilities. We will review in this lab the fundamental features of the language and learn how to integrate it with SQL to help solve database problems.

Need for PL/SQL


SQL statements are defined in term of constraints we wish to fix on the result of a query. Such a language is commonly referred to as declarative. This contrasts with the so called procedural languages where a program specifies a list of operations to be performed sequentially to achieve the desired result. PL/SQL adds selective (i.e. if...then...else...) and iterative constructs (i.e. loops) to SQL. PL/SQL is most useful to write triggers and stored procedures. Stored procedures are units of procedural code stored in a compiled form within the database.

PL/SQL Fundamentals
PL/SQL programs are organised in functions, procedures and packages (somewhat similar to Java packages). There is a limited support for object-oriented programming. PL/SQL is based on the Ada programming language, and as such it shares many elements of its syntax with Pascal. Your first example in PL/SQL will be an anonymous block that is a short program that is ran once, but that is neither named nor stored persistently in the database.
SQL> SET SERVEROUTPUT ON SQL> BEGIN 2 dbms_output.put_line('Welcome to PL/SQL'); 3 END; 4 /

y y y y

SET SERVEROUTPUT ON is the SQL*Plus command to activate the console output.

You only need to issue this command once in a SQL*Plus session. the keywords BEGIN...END define a scope and are equivalent to the curly braces in Java {...} a semi-column character (;) marks the end of a statement the put_line function (in the built-in package dbms_output) displays a string in the SQL*Plus console.

You are referred to Table 2 for a list of operators, and to Table 3 for some useful built-in functions.

Compiling your code.


PL/SQL code is compiled by submitting it to SQL*Plus. Remember that it is advisable to type your program in an external editor, as you have done with SQL (see Introduction to Oracle).

Debugging.
Unless your program is an anonymous block, your errors will not be reported. Instead, SQL*Plus will display the message ``warning: procedure created with compilation errors''. You will then need to type:
SQL> SHOW ERRORS

to see your errors listed. If yo do not understand the error message and you are using Oracle on UNIX, you may be able to get a more detailed description using the oerr utility, otherwise use Oracle's documentation (see References section). For example, if Oracle reports ``error PLS-00103'', you should type:
oerr PLS 00103

at the UNIX command prompt (i.e. not in SQL*Plus).

Executing PL/SQL
If you have submitted the program above to Oracle, you have probably noticed that it is executed straight away. This is the case for anonymous blocks, but not for procedures and functions. The simplest way to run a function (e.g. sysdate) is to call it from within an SQL statement:
SQL> SELECT sysdate FROM DUAL 2 /

Next, we will rewrite the anonymous block above as a procedure. Note that we now use the user function to greet the user.
CREATE OR REPLACE PROCEDURE welcome IS user_name VARCHAR2(8) := user; BEGIN -- `BEGIN' ex dbms_output.put_line('Welcome to PL/SQL, ' || user_name || '!'); END; /

Make sure you understand the changes made in the code:


y y y

A variable user_name of type VARCHAR2 is declared 2 user_name is initialised using the user built-in function ``:='' is the assignment operator (see. Table 2)

Once you have compiled the procedure, execute it using the EXEC command.
SQL> EXEC welcome

Both procedures and functions should remind you of Java methods. The similarities and differences between them are outlined in Table 1.

Table 1: Functions, procedures and Java methods compared.


Function Parameters Returns value Procedure Java Method

input, output input, output input yes no no optional

Can be called within SQL yes

PL/SQL Tutorial, Part 2


Need for PL/SQL declarative vs. procedural anonymous blocks debugging a first program code compilation code execution procedures & functions PL/SQL in SQL SQL in PL/SQL cursors & loops operators & built-in functions reference tables.

Embedding SQL in PL/SQL


PL/SQL alone does not allow us to query a database, and use the resulting data in our program. However, any SQL (i.e. DML) may be embedded in PL/SQL code. In particular, there exists a form of the ``SELECT'' statement for assigning the result of a query to a variable. Note the following code requires the books and book_reviews tables that you should have created during the first Oracle tutorial.
1 2 3 4 5 6 7 8 9 10 11 12 12 14 15 16 17 18 19 CREATE OR REPLACE PROCEDURE count_reviews (author_param VARCHAR2) IS review_count NUMBER; BEGIN SELECT COUNT(*) INTO review_count FROM book_reviews r, books b WHERE b.isbn = r.isbn AND author = author_param; IF review_count > 1 THEN dbms_output.put_line('There are ' || review_count || ' reviews.'); ELSIF review_count = 1 THEN dbms_output.put_line('There is 1 review.'); ELSE dbms_output.put_line('There is no review.'); END IF; END; /

Note in the code above how:


y y y

the procedure takes one parameter author_param of type VARCHAR2 a value from an SQL query is assigned to a PL/SQL variable (i.e. review_count) using SELECT...INTO... (line 6) a value from a PL/SQL variable is used in an SQL statement (line 8)

Try the programs with different authors:


EXEC count_reviews('Oscar Wilde') EXEC count_reviews('Charles Dickens')

Working with Cursors

The last program we are going to write will display the number of reviews relevant to each author. Notice that the query may now return multiple rows. However, a SELECT...INTO... statement can only retrieve data from (at most) one tuple into individual variables. Cursors3 provide a means to retrieve multiple rows into a buffer (when you OPEN the cursor) that can then be traversed sequentially (FETCH) to retrieve individual rowsuntil there is no more data (cur_revs%NOTFOUND becomes true).
CREATE OR REPLACE PROCEDURE count_by_author IS auth VARCHAR2(30); cnt NUMBER; CURSOR cur_revs IS SELECT author, COUNT(author) AS revs_cnt FROM books b, book_reviews r WHERE b.isbn = r.isbn GROUP BY author; BEGIN OPEN cur_revs; LOOP FETCH cur_revs INTO auth, cnt; EXIT WHEN cur_revs%NOTFOUND; IF cnt = 1 THEN dbms_output.put_line('1 review for ' || auth); ELSE dbms_output.put_line(cnt || ' reviews for ' || auth); END IF; END LOOP; CLOSE CUR_REVS; END; /

Execute count_by_author, adding more data to the tables if necessary.

Table 2: PL/SQL operators.


Operator Description + - / * arithmetic = != or <> || := equality inequality string concatenation assignment

Table 3: Some Oracle built-in functions. You are referred to Oracles's documentation (see References section) for specific usage examples.
Function String Functions upper(s), lower(s) initcap(s) ltrim(s), rtrim(s) substr(s,start,len) length(s) Date Functions sysdate current date (on Oracle server) convert string s to upper/lower-case capitalise first letter of each word remove blank char. from left/right sub-string of length len from position start length of s Description

to_date(date, format) date formatting Number Functions round(x) mod(n,p) abs(x) dbms_random.random() Type Conversion Functions to_char() to_date() to_number() Miscellaneous Functions user current Oracle user convert to string convert to date convert to number round real number x to integer n modulus p absolute value of x generate a random integer

Data Dictionary Tutorial


Data dictionary metadata system & object privileges dictionary structure ``user'' tables - ``all'' tables ``dba'' tables ``v$'' tables frequently used tables usage examples exercises using the dictionary in PL/SQL programs optional exercise.

Introduction
This document presents Oracle's data dictionary, also called the system catalogue. The data dictionary is the repository of all the meta-data relevant to the objects stored in the databaseand also of information concerning the DBMS itself.

Dictionary Content
Defining metadata.
The term metadata is often defined as data about data. That is, data that provides information about the tables, views, constraints, stored procedures, etc. stored within the database. If we take a table as an example, the dictionary will store information such as:
y y y y y

its name when it was created and when it was last accessed the names and data types of its attributes (i.e. structural information) its owner, who may read and write to it (i.e. security information) where the data is stored (i.e. physical information)

Security in Oracle.
Oracle defines two categories of privileges: object privileges and system privileges. Both categories are granted and revoked using the GRANT and REVOKE SQL constructs: GRANT <object_privilege> ON <object> TO <user> and GRANT <system_privilege> TO <user>. You have already used the former (see Introduction to Oracle.) System privileges mainly specify the types of objects a user is allowed to manipulate (tables,...) and what (s)he can do with them. Object privileges define the access rights at the objects level (and even at the attribute level for tables).

Dictionary Structure
The data dictionary is implemented in Oracle as a set of read-only tables and views.

Figure 1: Hierachical structure of the data dictionary. Figure 1 presents the two-level structure of the dictionary. At the root of the tree is the dictionary table, that features two attributes: table_name and comments. The comment field presents an informal description of the corresponding dictionary table. For instance, we can request information about the dictionary table:
SQL> SELECT comments 2 FROM dictionary WHERE table_name='DICTIONARY' 3 /

and get:
Description of data dictionary tables and views

As an exercise, write a query to find out how many tables make up the data dictionary. The second level of the dictionary is divided into four categories of tables. ``User'' tables describe the objects you own. They are only accessible to you. ``All'' tables describe the objects of all the users, and are accessible to all the users. ``DBA'' tables contain information only relevant and accessible to database administrators. And last, ``V$'' tables reflect the internal state of the DBMS and are mainly useful to DBAs for performance audit and optimisation. You should refer to Figure 1 for a list of commonly-used dictionary tables. Also, remember that you can obtain the schema of any table with the desc command1

Anda mungkin juga menyukai