651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g...

27
ORACLE SQL PRIMER Table of Contents (last page lists some useful UNIX commands) INTRODUCTION ACCESSING SQL-PLUS RUNNING SQL QUERIES Describe Command; Command Buffer Correcting Typos Saving Query Statements Editing Files CREATING AND MODIFYING TABLES Data Types Data Names; Further Create Table Pointers Modifying Tables GRANTING SECURITY PRIVILEGES Synonyms INSERTING, DELETING, UPDATING TABLES THE ORACLE DATA DICTIONARY PRINTING RESULTS (SPOOLING) OTHER SQL-PLUS COMMANDS UNIX COMMANDS APPENDIX A (sample tables) INTRODUCTION This document is intended to supplement the material in your database textbook on SQL. We will focus on the differences

Transcript of 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g...

Page 1: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

ORACLE SQL PRIMER

Table of Contents

(last page lists some useful UNIX commands)

INTRODUCTION

ACCESSING SQL-PLUS

RUNNING SQL QUERIES

Describe Command; Command Buffer Correcting Typos Saving Query Statements Editing Files

CREATING AND MODIFYING TABLES Data Types Data Names; Further Create Table Pointers Modifying Tables

GRANTING SECURITY PRIVILEGES Synonyms

INSERTING, DELETING, UPDATING TABLES

THE ORACLE DATA DICTIONARY

PRINTING RESULTS (SPOOLING)

OTHER SQL-PLUS COMMANDS

UNIX COMMANDS

APPENDIX A (sample tables)

INTRODUCTION

This document is intended to supplement the material in your database textbook on SQL. We will focus on the differences between the Oracle7 DBMS installed at UB and the more generalized textbook explanations. The document will illustrate the steps to create database tables, insert data, update data records, and other common database operations using Oracle. It will provide a few query examples, but your text will provide a more complete exposition of query formulation.

Page 2: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

SQL (Structured Query Language) is a database language used to formulate statements to be processed by a relational database management system (RDBMS). The most important RDBMS today in terms of market share (Oracle, Sybase, Informix, IBM's DB2, RDB) all use SQL. We use Oracle at the University of Baltimore, so this document will refer to the Oracle version of SQL throughout. However, the differences between Oracle SQL and the other products are mostly minor, so once you have learned this version it will be relatively easy to learn any of the other products. Incidentally, Oracle is the number one database package in market share, so learning how to use it will enhance your resume.

For illustrative purposes we will use the following simple 3-table database (called the SUPPLIER database):

SUPP (SNUM, SNAME, STATUS, CITY)

PROD (PNUM, PNAME, COLOR, WEIGHT, CITY)

SHIP (SNUM, PNUM, QTY)

Foreign key (SNUM) references SUPP

Foreign key (PNUM) references PROD

The SUPP table represents the suppliers for a company; PROD is the product table, and SHIP represents shipments. See Appendix A for some representative data from these tables.

ACCESSING SQL-PLUS

Accessing SQL-Plus

To access SQL-Plus, you must first: 1. Access UNIX2. Access Oracle

Accessing UNIXYou can access UNIX through putty shell

3. Connect to the internet. 

1. Click on putty.exe (downloadable free through following site)

http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

2. Type ids.ubalt.edu in the IP area and click open

Page 3: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

3. a UNIX shell will open:

login as: (The system prompts you for a username and password.)Enter the username and password supplied by your instructor.

7. The username is in the format ORDBxxx. The system will prompt you to change the password. Make sure you remember your new password so you can access UBE in the future.

8. login as: ORDBxxx (enter YOUR userid AS PROVIDED BY the instructor; ALL UPPER CASE)If not authorized to access this system, disconnect now.

YOU SHOULD HAVE NO EXPECTATIONS OF PRIVACY ON THIS SYSTEMBy continuing, you consent to your keystrokes and data contentbeing monitored.

8. ORDB000 (you will NOT see 000 but your own extension)@ids.ubalt.edu's password: (enter your password, as provided by instructor)

(first time when you log on you will be asked to RESET your password, please do that, it would be a good idea to set it to the password that I will provide for ORACLE.Last login: Thu Jan 13 18:35:33 2005 from ws22995If not authorized to access this system, disconnect now.

YOU SHOULD HAVE NO EXPECTATIONS OF PRIVACY ON THIS SYSTEMBy continuing, you consent to your keystrokes and data contentbeing monitored.

Disk quotas for ORDB000 (uid 200):Filesystem usage quota limit timeleft files quota limit timeleft/ 6 9216 10240 0 0 0ORDB000@ids ~ >

THIS LOGS YOU TO unix

Accessing OracleOracle has its own layer of security. Once you are logged on UNIX, you can access Oracle and SQL-Plus.To access Oracle: 

4. Access UNIX if you are not currently connected. 

Page 4: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

5. At the prompt, type sqlplus and press [ENTER].Note:  Commands are not case-sensitive unless otherwise noted.

6. Enter the username and password supplied by your instructor.

The system connects you to the Oracle database and SQL-Plus.

Tip:  The SQL> prompt indicates you're connected to SQL-Plus.

ORDB000@ids ~ > sqlplus (all small)

SQL*Plus: Release 10.1.0.2.0 - Production on Thu Jan 13 19:01:49 2005

Copyright (c) 1982, 2004, Oracle. All rights reserved.

Enter user-name: ordbxxx (same as login)Enter password: provided by instructor

Connected to:Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit ProductionWith the Partitioning, OLAP and Data Mining options

Note:

in all these instructions, unless otherwise noted it does not matter whether you type the command in lower case, upper case, or mixed case. Prompts and messages displayed by the computer will be shown in ordinary type. Whenever necessary to avoid confusion, we will show the commands for you to enter in bold type.

After successfully entering your SQL-Plus username and password, you will be connected to the database and to SQL-Plus. From that point on, the computer will use the following prompt:

SQL>

RUNNING SQL QUERIES

At this point, you should try some SQL statements and run a few simple queries till you get the hang of it. The instructor will have granted you access to the three SUPPLIER tables described above: SUPP, PROD, and SHIP.

For example, to list the numbers and names of all suppliers in London:

SQL> select snum, sname from supp where city = 'London';

Page 5: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

The query will run as soon as you type a semicolon and hit the Enter key. In Oracle SQL, you must use the semicolon to inform the system that your query statement is complete. If you type it this way: SQL> select snum, sname 2 from supp 3 where city = 'London' 4

The query will not run until you enter the semicolon. Try this for yourself and note what happens. The system keeps expecting additional words until the semicolon appears. Also note that the content of character fields (such as London in this example) require single quotation marks (the apostrophe) on either side. Do not include any extra spaces within the quotes; for example, 'London ' would not work, nor would ' London' or "London".

Also, this query will NOT run if supp table is NOT in your account. To use table from another account and they authorize your usage of their table, you will have to write a "qualifying" query. Assume supp table is in account ANIL and this account has given you permission to use supp table, your query will be

SQL> select snum, sname 2  from aggarwal.supp 3 where city = 'London';  

The Describe Command

If you want to know what the column names are for a particular table, or the formats of the columns, use the describe command. Describe is an SQL-Plus command; it is not part of standard SQL. Describe may be abbreviated as desc.

SQL> desc aggarwal.supp;

would produce:

Name                 Null?               Type SNUM               NO                 CHAR(2) SNAME             NO                 CHAR(10) STATUS                                    NUMBER CITY                                         CHAR(10)

The SQLPLUS Command Buffer

Oracle keeps the most recently executed SQL statement in a command buffer. If you want to execute the last statement again, you can type the / symbol after the prompt. The query is re- executed without the statement itself being displayed. The LIST command (abbreviated by the letter "l") will display the SQL statement currently held in the command buffer. RUN will display the SQL statement and then execute the query.

Page 6: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

Examples:

With the following query in the command buffer:

select snum, sname from aggarwal.supp where status = 20;

SQL> /

will produce

SNUM        SNAME S1               Smith S4               Clark

SQL> list (or simply l)

will produce

select snum, sname from aggarwal.supp where status = 20

SQL> run

will produce

select snum, sname from aggarwal.supp where status = 20

SNUM         SNAME

S1                Smith S4                Clark

Correcting Typos in SQL Plus

Most of us make typing errors when entering queries. When you try to run a query with an error in it, Oracle will display an error message. For example, if you type the following:

SQL> select from ship;

you will see the following message:

SELECT FROM SHIP                  *

Page 7: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

ERROR at line 1: ORA-0936: missing expression

The Oracle system will place the asterisk at the approximate point of the error. In this case you have omitted the column names from the SELECT clause. Let's assume that you intended to type select snum from ship;. You can correct the error with the CHANGE command. CHANGE may be abbreviated as the letter "c".

The query in the command buffer is "select from ship". It may be corrected as follows: c/select/select snum

A change command has three parts: the command to change (c) followed by a slash, then the part of the statement that is to be changed, another slash, and then the corrected portion. In this case we are saying that we want to insert "snum" after "select". However, this would not be the only way to do it. This would work equally well:

c/from/snum fromFor either of these, the system automatically displays the effect of the change:

1* SELECT SNUM FROM SHIP;

The 1* refers to Line 1 of the query; in this case, one line is all there is. To execute the corrected query, type / or RUN.

Many queries will be typed on more than one line. As explained in a previous section, you may use as many lines as you wish, ending with a semicolon. When you make a typing error in a multi-line query, however, you must inform the system of the line number you wish to change. In the following three-line query, there is an error in the third line:

SQL> select s.snum, sname 2 from supp, ship 3 where stats = 20 4 and supp.snum = ship.snum;

You meant to type status, not stats, in line 3.

Type the line number of the line that's in error (if you don't remember which line it was, type LIST (or L) to display the entire query from the command buffer).

SQL> 3

Oracle displays line 3 (i.e., makes line 3 current): 3     where stats=20

Now enter the change command:

Page 8: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

SQL> c/stats/status

If you want to add another line at the end of the query, or someplace in the middle, use the INPUT command (abbreviated "i"). For example, say that in the above query you want to add the STATUS column to the SELECT clause. You could do this with a CHANGE command in line 1, but it's often easier to add it on another line:

SQL> 1

Entering a "one" makes line one current. When inserting a new line, make the previous line the current one. The system responds:

1*         SELECT SNUM, SNAMEand you type

SQL> i , status

You're telling it to insert a line after line 1, and to put in a comma, followed by the word "status". SQL> LIST

1      SELECT SNUM, SNAME 2 ,    STATUS 3      FROM SUPP, SHIP 4      WHERE STATUS = 20 5      AND SUPP.SNUM=SHIP.SNUM

The DELETE command (abbreviated DEL) deletes the current line.

SQL> 2

2       , STATUS

SQL> del

SQL> list

1         SELECT SNUM, SNAME 2         FROM SUPP, SHIP 3         WHERE STATUS = 20 4          AND SUPP.SNUM=SHIP.SNUM

Line 2 has been removed and the query is again renumbered.

Saving Query Statements

Page 9: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

If you have spent a lot of time getting a complicated query just the way you want it and you don't want to have to retype it at a later time, you can save it by storing it in a separate file. For example, if you would like to save the query from the previous section, you can enter the following:

SQL> save selstat.sql

The Oracle system will create a file called SELSTAT.SQL and write your query into it. You don't have to call it SELSTAT; name it anything you want but give it a .SQL extension. When you look at your directory, you will see the file in there. If you want to run the query in a subsequent session, issue the START command:

SQL> start selstat.sql

Oracle will retrieve the file, place the contents in the command buffer (displacing whatever was in there), and run the query. Note that if you have used the extension .SQL in the filename, you do not have to type the extension in the START command. This works also:

SQL> start selstat

You may also, if you wish, replace the word START with the @ symbol:

SQL> @selstat

If you issue the SAVE command and it appears that the file already exists, Oracle will inform you of this. If you want to overwrite the contents of the file, add the word REPLACE to the SAVE command:

SQL> save selstat.sql replace

Editing Files When using Oracle you will often need to create a new file, or edit an existing one. It can be a pain to have to exit from SQL to go back to the UNIX, edit the file, then log in to Oracle again. You don't have to exit; you can use your "editor" (the software with which you edit files) while remaining in SQL. However, the first time you do so, you must first tell SQLPLUS your editor's name. The editor I use, and that I teach, is called EDT, but you may use any other one that's on the system that you prefer (for example, EVE).

You define the editor like this:

SQL> define _editor = "pico" That's an underline before the "e" in editor. There is also a space preceding the underline. Subsequently, you can edit a file right from SQL, using the word "edit": SQL> edit filename For example, if the filename is "activity.sql", you can enter the editor as follows:

Page 10: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

SQL> edit activity.sql Edited files can be executed in SQLPLUS as described above with the @ sign.

CREATING AND MODIFYING TABLES

The CREATE TABLE statement defines a table. A table definition consists of a list of definitions of columns that make up a row in the table. The following lines create a product (PROD) table for our example: SQL> CREATE TABLE prod 2         (pnum char(3) primary key, 3         pname varchar2(12) not null, 4         color varchar2(10), 5         weight number (3,1), 6         city varchar2(12) not null);

In this example, pnum is defined as a field which contains 3 characters or less. Pnum is also designated as the primary key for this table. Pname, color, and city are defined as type varchar2. Varchar2 is the best type to use for fields which have considerable variance in length, such as names of people or names of colors or cities. With char, if you insert only 2 characters in a 3- character field, Oracle fills in a blank for the extra space. With varchar2, only the characters you enter are stored, so this can save considerable storage space. Pname and city in this example may contain a maximum of 12 characters, and color a maximum of 10. Weight is defined as data type number. The (3,1) indicates that this field may contain no more than 3 numeric digits, and that one of the 3 digits is reserved for the right side of the decimal point. Therefore, there is room for only two digits to the left of the decimal. For example, an attempt to enter 246 would be rejected; 24.6 would be acceptable.

In defining a table, you must be very precise with spelling and punctuation. Always start with CREATE TABLE followed by the tablename. The spacing from line to line, however, is arbitrary. This would work just as well:

SQL> CREATE TABLE prod (pnum char (3) 2          primary key, pname 3          varchar2 (12) not null, color 4          varchar2 (10), weight number(3,1), city varchar2(12) not null); The first formulation is preferred because it is much easier to spot errors, but it makes no difference to the program.

Data Types The primary datatypes that you will be concerned with are as follows:

CHAR(size)   May contain any printable character such as 'A', '3', '&', or ' ' (blanks). It may be any length from zero characters up to the maximum designated by (size). For example, if you create a field of CHAR(5), you could insert 'Jones' into the field, but not 'Martin'. Maximum size: 255 characters. Default is 1 byte. Padded on right with blanks to

Page 11: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

full length of size. VARCHAR2(size) Variable length character string having a maximum of size bytes (up to 2000). NOT padded with blanks. NUMBER For a numeric column of up to 40 digits. May be used with or without a size designation. You may use this type for integer fields, or for fields in which you wish to insert the decimal point. NUMBER(size) For a NUMBER column of the specified size. NUMBER(size, d) For a NUMBER column of specified size with d digits after the decimal point. For example, NUMBER(5,2) could contain nothing larger than 999.99 without generating an error message. DATE The DATE data type is stored in a special internal ORACLE format that includes not just the month, day, and year, but also the hour, minute, and second. However, for most tables, you will not need to be concerned about the time. For inserting a date into a table, use the following format: '10-OCT-06'.

Data Names Data names in SQL (e.g., names of tables, columns, indexes, views, synonyms, tablespaces, etc.) must comply with the following rules: -- Must be from 1 to 30 characters long. -- Must begin with a letter. -- May contain only uppercase or lowercase letters (A,a), digits, dollar signs ($), the number sign     (#), and underscores (_). Embedded blanks are not permitted, nor any other special characters. -- Must not be the same as an ORACLE reserved word. There is a long list of these, including the      following: ALTER, AUDIT, BACKUP, CHANGE, CHARACTER, COLUMN, DECIMAL,      DATABASE, and lots more. If you get an error message for violating this rule, just name the      object something else.

Further CREATE TABLE Pointers Note the format of the CREATE TABLE statement very carefully. The statement isn't evaluated by the system until you enter the ;. Follow the rules very precisely in entering these elements; the system is not very forgiving of errors. The table name is given on the first line, without a comma, but must be followed by an open parenthesis. Make sure you have matched each "(" with a ")" and vice versa. The commas are important; the system knows that "primary key" refers to "pnum" because there was no intervening comma. The comma signifies that you are ready to start defining the next column name.

Another point on which your good judgment will be necessary is in the use of the NOT NULL qualifier in the tables. In Table PROD above, the designation "primary key" implies not null; the system will not allow null values in the primary key field(s). To put this another way, you cannot enter a record unless it has a primary key. Presumably also a product without a name would not make much sense, so "not null" is specified for "pname", and also for "city". In this case, it was assumed that some products may not have a color or weight. That may or may not make sense; in real life, we would not assume this; we would interview users to ascertain whether or not null values would be acceptable. In general, you want to avoid having a lot of nulls (fields containing no data,

Page 12: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

only blanks) cluttering up your database. For high integrity, you want to keep missing values to an absolute minimum. However, there are times when you want to insert a record for which some of the data is missing, and in that case it may make sense to allow the field to be null.

In our example database, the table SHIP has two foreign keys, snum and pnum. The primary key for this table is two columns: the combination of snum, pnum. A valid CREATE TABLE statement for this table would be as follows:

SQL> CREATE TABLE ship 2         (snum char(3) references supp, 3         (pnum char(3) references prod, 4         qty number not null, 5         primary key (snum, pnum));

The term "references supp" means that snum is a foreign key to the primary key in the table supp. It also means that if you attempt to enter a value in the snum column for ship that does not correspond to one already in supp, you will get an error message. The same goes for pnum in relation to the table prod. The combined primary key is designated as shown. Note that there must be a comma at the end of line 4 to signify the end of the definition for the column qty.

An integrity constraint is a rule that is enforced automatically by the DBMS. A primary key is an integrity constraint, and the Oracle system will not allow a user to insert a table record which duplicates the primary key of an existing record in the table. A foreign key is also an integrity constraint, and the system will not allow a record with a foreign key to be inserted if the corresponding primary key does not exist in the referenced table. Another type of constraint is the CHECK clause. You may formulate a check clause in a table to limit the column to certain values. For example, if you want to guard against a user entering a negative value in the qty column of the SHIP table, you could include the following column definition in the CREATE TABLE statement: qty number not null check (qty > 0), If you want qty to be above zero and less than 500, this might be the definition: qty number not null check (qty between 0 and 500), If you have a STUDENT table and wish to restrict the user to entering only certain values for the student's class, the definition for class could be: class varchar2(9) not null check (class in ('Freshman', 'Sophomore', 'Junior', 'Senior)),

Modifying Tables The ALTER TABLE statement changes an existing table definition. You can:

Add a new column to an existing table Increase or decrease the width of an existing column Specify constraints for an existing column

Page 13: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

However, you cannot change the name of a column.

To add a column called shipdate to the SHIP table: SQL> alter table ship add (shipdate date);

To increase the width of the pname column in PROD from 12 to 15 characters: SQL> alter table prod modify (pname varchar2(15)); You may DECREASE the width in the same way; however, the system will not allow you to decrease the width unless the table is empty (no records have been inserted).

To change pname to NULL when it has been defined as NOT NULL: SQL> alter table prod modify (pname varchar2(15) null);

To change color to NOT NULL when this was not specified in CREATE TABLE: SQL> alter table prod modify (color varchar2(10) not null); However, if a table is not empty you cannot change a column to NOT NULL unless every row has a value for that particular column.

DROP TABLE deletes the table definition specified. When the DROP TABLE statement executes, SQL deletes the table definition and the data stored in that table from the database.

SQL> DROP TABLE table_name; SQL> drop table prod; If you have created a table definition that you don't like, you may want to use this command so you can start again. However, be careful with this powerful command; you probably should not use it if you already have data in the table. All the data you have inserted will be lost.

GRANTING SECURITY PRIVILEGES

The information in databases can be extremely valuable to an organization, and it is important for the DBA to take security precautions to assure that users have access only to that data which is necessary them to carry out their work. Oracle provides extensive security features to safeguard information, from both unauthorized viewing and intentional or inadvertent damage. This security is provided by granting or revoking privileges on a person-by-person and privilege- by-privilege basis. This is in addition to (and independent of) any security your computer system already has.

Oracle7 uses the create user, create role, and grant commands to control data access. Any Oracle user is the owner of any tables, views, and other objects that he or she creates. An Oracle role is a set of privileges for a particular type of user (for example, a particular department). Specific privileges can be granted to roles and then the roles can be assigned to the appropriate users.

Page 14: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

Students in UB database classes will not have the power to create new users or to create roles. These actions will be performed by your instructor. However, you should be able to use the grant command to grant others privileges on tables that you create. A user can grant the following privileges:

  ..Insert, update, and delete on the user's own tables and views. Update may be on the entire    table, or may be restricted to specific columns. ..Alteration of the user's tables. ..Select (read-only) privileges on tables and views.

Assume that user George has created a table called CUSTOMER. He wishes to give user Mary read-only privileges to this table: SQL> grant select on customer to Mary;

If George wishes Mary to be able to grant read-only access to the table to other users, he may add the words with grant option to the command: SQL> grant select on customer to Mary with grant option;

Similarly, to grant Mary the right to insert data records into the table and to update the records: SQL> grant insert, update on customer to Mary;

However, when Mary uses the CUSTOMER table in an SQL command, she must qualify it with the username of the owner. If she enters: SQL> select * from customer; an error message will be generated; Oracle will say the table does not exist. This is the correct form: SQL> select * from George.customer;

If she wishes, Mary may create a view from the granted table: SQL> create view customer as select * from george.customer;

After this view is created, selection from the view will produce exactly the same results as selecting from george.customer: SQL> select * from customer;

Synonyms Users who have been granted privileges on another's tables may also create a synonym for a table. Say that Mary issues the following command: SQL> create synonym mycust for george.customer; Now, she can access the CUSTOMER table as follows: SQL> select * from mycust;

INSERTING, DELETING, UPDATING TABLES

The INSERT statement stores values in rows of a table. The following example inserts a record into our SUPP table: SQL> insert into supp values ('S7', 'Kelly', 30, 'London');

Page 15: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

Note that you must use single quotes for alphanumeric fields. A date must be in single quotation marks and in the default Oracle date format (e.g., '21-mar-94'). You may insert a null value, as follows: SQL> insert into supp values ('S7','Kelly', null, 'London'); This example assumes that the STATUS column has not been defined as NOT NULL. Enter the values for the columns in the same sequence as the tables.

Removing a row or rows from a table requires the delete command. This is a very powerful command, so if you use it, use great caution. In particular, note that the where clause is essential to removing only the rows yo intend. Delete without a where will empty the table completely. SQL> delete from supp where city = 'London'; will delete all those suppliers whose CITY is London. SQL> delete from supp; would delete all the rows in the entire table.

Update requires setting specific values for each column you wish to change, and specifying which row or rows you wish to change by using a carefully constructed where clause: SQL> update supp set status = 30 where city = 'London';

The insert, delete, and update commands do not take effect immediately. You can reverse or rollback the work you've done. The process of committing or rolling back work is controlled by two SQLPLUS commands, commit and rollback. Until you commit, only you can see how your work affects the tables. Anyone else with access to these tables will continue to get the old information. You will see new information whenever you select from the table. Your work is, in effect, in a staging area, which you interact with until you commit. SQL> commit;

You can do quite a large number of inserts, updates, and deletes, and still undo the work (return the tables to the way they were originally) by issuing this command: SQL> rollback; This will undo anything you've entered since the last commit.

When you do updates or deletes, be very careful that you have done what you intended to do before committing. Experiment with select before actually making the change to the database. A recovery is possible, so long as a commit has not occurred. Run select queries before and after the delete or update to see if the result is what you expected to take place; if it is, then issue the commit.

THE ORACLE DATA DICTIONARY

The data dictionary stores all the information that is used to manage the objects in the database. Although it is usually the domain of DBAs, the dictionary is a source of valuable information for developers and end users as well. It contains hundreds of tables, but there are only a few which will be of great use to you as a student:

Page 16: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

SQL> select table_name from user_tables; will provide the names of the tables you have created. Since you will be using this query frequently, it would save you time if you save it under a shorter name, such as tabs. To do this, first type the query, so that it is in the buffer: SQL> save tabs The system will respond that the file TABS has been created. When you look at your directory ($dir) you will see the file stored there. After that, any time you want to determine the names of the tables you have created: SQL> start tabs       or SQL> @tabs will run it.

After you have created other types of objects, such as views and synonyms, a more useful query is the following: SQL> select object_name, object_type from user_objects; You could save this under a short name such as obj.

PRINTING YOUR QUERIES AND QUERY RESULTS (SPOOLING)

In the early days of computers most file storage was done on spools of either magnetic wire or tape. Writing information into a file and spooling a file were virtually synonymous. The term has survived, and spooling now generally refers to any process of moving information from one place to another. For our purposes, this will generally mean saving everything that appears on the screen into a file, which can then be edited, displayed, or printed.

Specifying SPOOL filename will create an operating system-dependent file; filename can contain the full pathname of the file and extension. If no extension is given, the file suffix LST will be appended (filename.LST).

SQL> spool activity tells SQL to take all of the output from SQLPLUS and write it to the file named ACTIVITY.LST. You can give the file any name you want, preferably something relevant to the task being performed. For example, you could use HOMEWKC or QUERY6.HWC.

When you are finished spooling, type: SQL> spool off

You must then figure out how to print it. This will vary depending on whether you are working at home with your own printer, in the lab downstairs in the Business Center, in Charles Hall, etc. There are so many variations that no instruction will be provided here,

Page 17: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

but if you have problems printing your instructor will help you determine the best method for printing.

OTHER SQLPLUS COMMANDS

There are some other very useful commands. Most of these have to be set each time you start an Oracle session; they are lost when you log out.

If your output contains too many lines to fit on one screen, it can be frustrating because it scrolls down the screen too fast for you to read. Try these two commands in SQLPLUS: SQL> set pagesize 24 SQL> set pause on The first command will set the system to display 24 lines of output at a time. The second tells it to stop and wait for you to hit Enter before it displays a new page. That way you can view a large amount of output one screen at a time. These commands will remain in effect for the rest of your session or until you change them. If you decide you don't want the pauses, you can SQL> set pause off

You can specify the width and output format of columns, and make your output look much neater. These commands modify the way the output looks, both on the screen and when printed, but they have no effect on the data in storage. To illustrate what we can do, in the SUPP table there is a column named SNAME. Suppose you want the column heading to read Supplier Name. Try the following command: SQL> col sname heading 'Supplier Name' Start with the keyword column or its abbreviated version col. Use the official name of the column. Type in the key word heading and then the heading you want within single quotes. The query select sname from supp; would produce the following heading:       Supplier N       -------------- This is not quite what we wanted. Note that there are only 10 characters printed (including the blank). We need 13. Also note that the command describe supp shows the column SNAME as being 10 characters wide. That is why the last 3 characters get cut off; we haven't told the system to give us more space for reporting purposes. Let's try this: SQL> col sname format a13 The A stands for alphanumeric. select sname from supp now produces what we want:        Supplier Name        -------------------

We could have done the whole thing in the first command: SQL> col sname heading 'Supplier Name' format a13

We can also format a numeric column. Assume you have a column named AMT in Table X that contains monetary data such as: 842561  937.5     6217    354.92 The query select amt from x; would produce:

Page 18: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

         AMT          -------         842561         937.5         6217         354.92 The command: SQL> col amt heading 'Amount' format 999,999.99 would give this output from the above:        Amount     -------------        842,561.00               937.50            6,217.00               354.92 vertically aligned on the decimal point and with commas inserted. The number of nines (or nines plus zeros) determines the maximum digits that can be displayed. 999,999 would display up to six digits of integer data. $999,999.99 would place a dollar sign in front of every number.

remark (or rem) tells SQLPLUS that the words to follow are to be treated as comments, not instructions. The system ignores anything on a line that begins with these letters, allowing you to add explanations to any start file you create.

UNIX CommandsUnix commands can also be used in ORACLE with a preceding !

To get a list of your files in your directory

SQL>!ls

This will provide a list of all your files

To see the contents of a specific file

SQL>!cat <filename>

SQL>! cat query1.sql;

Will give the content of file query1

Note: If you notice any errors in this document: typos, statements that don't make sense, or instructions that do not work as described here, please notify Dr. Aggarwal.

APPENDIX A

Page 19: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

Representative data for the SUPP, PROD, and SHIP tables. Be sure to keep reminding yourself that these are not realistic tables; they are for illustrative purposes only. In the real world, a table often has hundreds of thousands, even millions, of rows, and they might have 40 or 50 columns. The content of a table may change rapidly.

SUPP

SNUM  SNAME STATUS  CITY

S1         Smith       20            London

S2         Jones       10            Paris

S4         Blake       30            Paris

S3         Clark       20            London

S7          Adams    30           Athens

PROD

PNUM PNAME COLOR WEIGHT CITY

P1 Nut Red 12 London

P3 Screw Blue 17 Rome

P2 Bolt Green 17 Paris

P6 Cog Red 19 London

P4 Screw Red 14 London

P5 Cam Blue 12 Paris

SHIP

Page 20: 651ORA - ubalt.eduhome.ubalt.edu/NTSBAGGA/web/651ORA_fall05.doc · Web viewOracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production With the Partitioning, OLAP

SNUM    PNUM QTY

S1          P1         300

S3          P1         250

S3          P3         500

S2          P1         150

S5           P5         425

Note: each of these tables has additional rows in the version you can access on UBE. .