Docsity

Mini User's Guide for SQL* Plus - Lecture Notes | EECS 484, Study notes of Database Management Systems (DBMS)

Toggle sidebar
bg1
EECS 484
10/3/2005 1
Mini User's Guide for SQL*Plus
T. J. Teorey
Table of Contents
Oracle/logging-in 1 Nested subqueries 5
SQL create table/naming rules 2 Complex functions 6
Update commands 3 Save a query/perm table 6
Select commands 3 Special commands 6
Set operations 4 SQL views 9
Built-in functions 4 Index 10
Oracle
Oracle 8.1.6 resides on a Sun Sparc10 node. However, you do not need to login directly to this machine, but
think of it as a database server to be accessed from another machine, for example, canoe.engin.umich.edu.
Logging in to UNIX and Oracle SQL*Plus
login: <your Unix login-id>
password: <your Unix login-password>
your-unix-node% source /usr/caen/oracle/local/muscle
your-unix-node% sqlplus
Enter user-name: <your-oracle-id>
Enter password: <your-oracle-password>
/*You are now in SQL*Plus and can start issuing SQL*Plus commands*/
SQL> select * from employee; /*example of an sqlplus command*/
SQL> grant connect to your-oracle-id identified by your-new-password; /*change password*/
Input and Output Files for Oracle
To save the transcript of an sqlplus session or part of a session:
SQL> set echo on; /*displays SQL code with results of the query*/
SQL> spool <filename>; /*filename will be appended with .1st if a postfix is not provided*/
SQL> spool off; /*will turn off the transcript spooling. You can now print the file with the
instructions provided below*/
To read in a file:
SQL> start <filename>;
or SQL> @<filename>;
where filename must be a OpSys file ending with .sql (the .sql may or may not be supplied to
Oracle, but must be part of the name of the file).
Print Oracle Results
To print on a Sun or IBM the users can say: lpr -P<printer_name> <filename>
printer_names (2340eecss2,2341eecsh1,4327eecss1,4327eecss2,4440eecss1,4440eecsm1)
HP: lp -d<printer_name> <filename>
Access from any computer:
1. To any UNIX machine, by typing "telnet <node_name>"
2. To any UNIX machine from a Merit terminal (where you see the "Which Host?"prompt), by doing a
"telnet <host>@engin.umich.edu"
Note: use "telnet hostinfo" to see a selection of free nodes.
Oracle SQL*Plus Programming Examples
Naming rules:
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Mini User's Guide for SQL* Plus - Lecture Notes | EECS 484 and more Study notes Database Management Systems (DBMS) in PDF only on Docsity!

Mini User's Guide for SQL*Plus

T. J. Teorey

Table of Contents

Oracle/logging-in 1 Nested subqueries 5 SQL create table/naming rules 2 Complex functions 6 Update commands 3 Save a query/perm table 6 Select commands 3 Special commands 6 Set operations 4 SQL views 9 Built-in functions 4 Index 10

Oracle

Oracle 8.1.6 resides on a Sun Sparc10 node. However, you do not need to login directly to this machine, but think of it as a database server to be accessed from another machine, for example, canoe.engin.umich.edu.

Logging in to UNIX and Oracle SQL*Plus

login: password: your-unix-node% source /usr/caen/oracle/local/muscle your-unix-node% sqlplus Enter user-name: <your-oracle-id> Enter password: <your-oracle-password>

/You are now in SQLPlus and can start issuing SQLPlus commands/

SQL> select * from employee; /example of an sqlplus command/ SQL> grant connect to your-oracle-id identified by your-new-password; /change password/

Input and Output Files for Oracle

To save the transcript of an sqlplus session or part of a session: SQL> set echo on; /displays SQL code with results of the query/ SQL> spool ; /filename will be appended with .1st if a postfix is not provided/ SQL> spool off; /will turn off the transcript spooling. You can now print the file with the instructions provided below/ To read in a file: SQL> start ; or SQL> @; where filename must be a OpSys file ending with .sql (the .sql may or may not be supplied to Oracle, but must be part of the name of the file).

Print Oracle Results

To print on a Sun or IBM the users can say: lpr -P<printer_name> printer_names (2340eecss2,2341eecsh1,4327eecss1,4327eecss2,4440eecss1,4440eecsm1) HP: lp -d<printer_name>

Access from any computer:

  1. To any UNIX machine, by typing "telnet <node_name>"
  2. To any UNIX machine from a Merit terminal (where you see the "Which Host?"prompt), by doing a "telnet @engin.umich.edu" Note: use "telnet hostinfo" to see a selection of free nodes.

Oracle SQL*Plus Programming Examples

Naming rules:

1-30 characters long (a-z, 0-9,_,$,#), begin with a letter No quotation marks No duplicates of Oracle reserved words, no duplicate of another Oracle object of the same type

Basic example: suppliers, parts, and shipments. create table supplier (snum number not null, sname char(12), /max is 240 characters/ city char(12), status number, primary key (snum)); /must be defined as a primary key before it is defined as a foreign key/ create table part (pnum number not null, pname char(10), length number, weight number, primary key (pnum)); /cannot have both "unique" and primary key/ create table shipment (snum number not null, pnum number not null, qty number, shipdate date not null, primary key (snum, pnum,shipdate), foreign key (snum) references supplier, foreign key (pnum) references part);

Syntax Rules

  1. Semicolon needed, no continuation character needed.
  2. not => !, ~(hat), not(.....)
  3. Constraints on create table not null - null not allowed for this column (attribute) unique - attribute may not have duplicate values primary key - explicitly designates simple or composite primary key foreign key - explicitly specifies referential integrity check - specifies range constraints or specific values (see 5-39)
  4. Logical operators used with "where" clause: and, or, not, !=, ()
  5. Comparison operators: (),=,!=,~=,<,<=,>,>= in - equal to any member of, same as "=any" not in - same as "!= all" => false of any member of set (select...) is null any - same as "in" all - compares a value to every value returned by a list
  6. Set operators union - combines queries to display any row in each subquery intersect - combines queries to display distinct rows common to all subqueries minus - combines queries to return all distinct rows returned by the first query but not the second
  7. Order by: asc, desc
  8. Basic definitions create table - defines a table alter table - add a new column, lengthen the width of a column /enlargements only/. drop table - destroys an existing base table create view, drop view create index, drop index..........create index x on t (p,q desc, r); create integrity, drop integrity
  9. Data types:

where snum = 3;

Built-in functions

/display the total number of suppliers/** select count(*) from supplier;

/display the total number of suppliers actually shipping parts/** select count (distinct snum) from shipment;

/display the average quantity of a shipment of part number 31/** select avg (qty) from shipment where pnum = 31;

/order by attribute names -- note that asc is the default/** select pnum, snum, qty from shipment order by pnum asc, snum desc;

/order by column number as specified in the select line/** select pnum, snum, qty from shipment order by 1, 2;

/for each part shipped, display the part number, the total shipment quantity, and the count of orders for each part; note that pnum in the select line must be in a "group by" command/** select pnum, sum(qty), count(qty) from shipment group by pnum; /note: the group by orders items ascending by default/

/display part numbers for all parts supplied by more than one supplier/** select pnum from shipment group by pnum having count(distinct snum) >1;

/group by primary, secondary columns/** select pnum, snum, max(qty) from shipment group by pnum,snum;

/find greatest and least values among attributes within each row, for all rows/** select greatest(empno,mgrno), ename from emp;

Nested subqueries

/display supplier names who supply part 32.....and equivalent query/** select s.sname select s.sname from supplier s from supplier s, shipment sh where s.snum in where s.snum = sh.snum (select snum and sh.pnum = 32; from shipment sh where sh.pnum = 32); /note indentation for nested query/

/display supplier names who supply at least one part with weight over 20.....&...equiv query/** select s.sname select s.sname from supplier s from supplier s, shipment sh, part p where s.snum in where s.snum = sh.snum (select sh.snum and sh.pnum = p.pnum from shipment sh and p.weight > 20; where sh.pnum = any (select p.pnum from part p where p.weight > 20));

/which suppliers are currently not shipping any parts with weight over 20?* select s.sname from supplier s where s.snum not in (select sh.snum from shipment sh, part p where sh.pnum = p.pnum and p.weight > 20);

SQL> run; /for && - redoes query with same value as before/** Note: & means prompt with value, not saved; && means prompt with value, value is saved.

  1. Setting up a report title, suppress the title, and set up special column headings:

SQL> ttitle [right|left] 'This is a Title of a Report' ; /default is center – persists until you execute "ttitle off"/ SQL>** column schema_column_name heading “ new_column_name “;

/This will produce special column names as specified in quotes, but does not persist. Quote SQL>* select ename "Employee Name", sal "Employee Salary" from emp; SQL> select ename empnane, sal empsalary from emp;

  1. Report formatting:

SQL> break on deptno skip 1; /do not repeat deptno, skip a line between deptno's/ SQL>** break on deptno on mgr skip 1; / do not repeat deptno or mgr, skip a line/ SQL>** run; /execute the previous select with the new breaks/**

/Note: you need to leave a blank line between the end of the query and the "run". This will cause echoing of the query. /

SQL> clear break; SQL> clear column; /resets break and column settings/**

SQL> set pagesize 54; /overrides default of 14 lines/page/**

  1. Data Formats: set column settings to override defaults, in-line format specifications

SQL> column avg(sal.monsal) format $99,999.99; SQL> column deptname format A6; SQL> column deptno format 99999; SQL> ..........where to_char(shipdate, 'yy') = 94..........etc. SQL> select to_char(monsalary, '$99,999.99').......etc. SQL> alter session set NLS_DATE_FORMAT = ‘DD-MON-YYYY’; /display 4-digit year/

  1. Recursive hierarchy access in SQLPlus (top-down hierarchy) SQL> select lpad(' ',2level)||ename organization_chart from emp connect by prior empno = mgrno start with ename = 'King'; Note: a bottom-up hierarchy can be obtained by reversing the attributes after "connect by prior" and spec
  2. Partial matching (see also SOUNDEX for words that sound like something else) /* Look for names with "a" as the second letter and any string afterwards */ SQL> select ename from emp where ename like '_a%';
  3. Size check -- determine the count of rows satisfying the query before displaying the results select count(*) from shipment where pnum = 31; Size check -- limit display of rows before displaying the results of the whole query. select snum, pnum from shipment where pnum = 31 and rownum <= 15;
  4. Create sequence command to set up artificial primary key, max. number is 10e*27 -1.

SQL> create sequence myseq increment by 1 start with 1; /defaults incr to 1 start with 1/ SQL>** create table mytable (myseq, attri1....., attr2 ....., attr3); SQL> insert into mytable values (myseq.nextval, value for attr1, .........) SQL> alter sequence mseq increment by 5;

  1. Create index commands for B+-tree

SQL> create [unique] index indexname on supplier(snum [asc|desc]); /unique=> hashing/ SQL>** create unique index indexname on supplier(snum); /unique index on primary key/ SQL> create index indexname on shipment (shipdate); /non-unique index on non-key/ SQL> create index index2 on shipment (pnum, shipdate); /non-unique concatenated index/

  1. Check clause in create table commands.

check (status>10), check (status between 10 and 40), check (city in ('Athens','London'), check (city != 'Paris' or status = 20);

  1. SQL editing line-by-line

SQL> select * from supplier 2 where snum = 14 3 and sname = 'Smith';

no rows selected

SQL> 2 where snum = 1 SQL> run; 1 select * from supplier 2 where snum = 1 3* and sname = 'Smith'

SNUM SNAME CITY STATUS

1 Smith London 20

SQL Views

view -- a named, derived (virtual) table in SQL base table -- actual tables used in the original schema definition motivation for views (1) simplicity -- simplifies complex queries often used, or accessed by novice SQL users (2) security -- provides different views of the same data (3) data independence -- view queries constant even though the base table schemas are changed query on a view -- treats the view as if it were a real table recursive definitions -- a view may contain other views

Index

  • alter table -
  • and -
  • available tables -
  • avg -
  • break on -
  • change password -
  • check -
  • clear breaks -
  • clear column -
  • column format command -
  • complex functions -
  • computations -
  • counseling (Oracle SQL*Plus) -
  • count -
  • create index -
  • create sequence -
  • create table - 2,
  • delete -
  • desc table -
  • distinct -
  • editing line-by-line in SQL*Plus -
  • greatest - 5,
  • group by - 4,
  • group functions ( max, min, avg, sum ) -
  • having -
  • help commands -
  • input and output files (Oracle) -
  • insert -
  • intersect -
  • least - 5,
  • logging in (UNIX, Oracle) -
  • lpad function (hierarchies) -
  • max (min) function -
  • months_between function- minus - 4 (not listed, but check union for format)
  • multiple invocations of a table -
  • naming rules -
  • nested subqueries -
  • nvl function -
  • order by -
  • pagesize -
  • partial matching -
  • permission (read-only) -
  • print results (Oracle) -
  • privileges in tables -
  • prompts -
  • renaming tables -
  • report titles -
  • save a query result in a table -
  • select - 3-
    • select * -
  • set operations ( union, intersect, minus ) -
  • set pagesize -
  • size check -
  • SOUNDEX -
  • subqueries -
  • sum function -
  • syntax rules for SQL*Plus - 2,
  • ttitle -
  • union -
  • update -
  • views -
  • view update -
  • where -