Using Oracle
Oracle Resides on Certain CPUs Computers in the GradLab Computers in ICL4 Hilly.cs.rit.edu Holly.cs.rit.edu Queeg.cs.rit.edu Log into one of these machines to work on Oracle
Set up Oracle Environment Variables source /usr/local/bin/coraenv –(if using bash, file is oraenv ) ORACLE_SID –Oracle system identifier ORACLE_HOME –Top level directory of the Oracle system hierarchy PATH –Path to ORACLE_HOME/bin Insert batch version of coraenv at the end of your.cshrc file: –The batch version is on our ClassNotes page in file oracleEnv –Example.cshrc file is on our ClassNotes page in file example.cshrc
Starting sqlplus SQL*Plus: Release Production on Tue Dec 16 14:56: Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved. Enter password: Connected to: Oracle9i Release bit Production JServer Release Production SQL>
Change your password SQL> password Changing password for chr Old password: New password: Retype new password: Password changed SQL>
Executing a file of SQL fileOfCommands.sql fileOfCommands SQL> run fileOfCommands.sql
“Getting” a file of SQL SQL> get q76.sql 1 select s.name from sailors s 2 where not exists 3 (select s2.name from sailors s2 4 where s.rating > s2.rating 5* and s2.age < 21) SQL> list 1 select s.name from sailors s 2 where not exists 3 (select s2.name from sailors s2 4 where s.rating > s2.rating 5* and s2.age < 21) SQL> / NAME Jones Moby SQL>
Editing the sqlplus buffer LIST shows the command buffer, and makes the last line in the buffer the "current" line LIST n prints line n of the command buffer, and makes line n the current line LIST m n prints lines m through n, and makes line n the current line INPUT 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" CHANGE /old/new replaces the text "old" by "new" in the current line APPEND textappends "text" to the end of the current line DELdeletes the current line
Using an editor to modify the sqlplus buffer Default editor is vi : SQL> edit Use a different editor of your choice: SQL> DEFINE _EDITOR = "emacs" SQL> edit
Recording a sqlplus session SQL> spool fileForRecording.txt SQL> select * from BasicCustomerData; NAME ARE PHONE Chris Wilkens David Smith Donald G. Gray Fred Smathers Jack Jones Jeffrey Janes Lynda Johnson Mary Beth Frederick rows selected. SQL> spool off SQL>
Issuing a Unix command from within sqlplus SQL> !cat fileForRecording.txt SQL> select * from BasicCustomerData; NAME ARE PHONE Chris Wilkens David Smith Donald G. Gray Fred Smathers Jack Jones Jeffrey Janes Lynda Johnson Mary Beth Frederick rows selected. SQL> spool off SQL>
sqlplus help SQL> help topics … SQL> help index … SQL> set pause on SQL> help column COLUMN Specifies display attributes for a given column, such as: - column heading text - column heading alignment - data format - column data wrapping Also lists the current display attributes for a single column or all columns. …
Accessing DB metadata SQL> select table_name from user_tables; TABLE_NAME ARTIST ART_CUSTOMER CUSTOMER CUSTOMER_ARTIST_INT INVENTORY MDC_CUSTOMER MDC_ORDER_ITEM MDC_SALES_ORDER MDC_SERVICE MI_PURCHASE MI_SHIPMENT
Accessing DB metadata (cont.) SQL> describe artist; Name Null? Type ARTISTID NOT NULL NUMBER(9) NAME NOT NULL CHAR(25) NATIONALITY CHAR(30) BIRTHDATE NUMBER(4) DECEASEDDATE NUMBER(4) SQL>
Help with Oracle errors
Setting linesize (default = 80) SQL> select * from artist; ARTISTID NAME NATIONALITY BIRTHDATE DECEASEDDATE Miro Spanish Kandinsky Russian SQL> set linesize 150; SQL> select * from artist; ARTISTID NAME NATIONALITY BIRTHDATE DECEASEDDATE Miro Spanish Kandinsky Russian
Setting pagesize (default = 24 lines) Turns off all headings, titles and page-breaks: SQL> set pagesize 0 Sets pagesize to 50 lines per page: SQL> set pagesize 50
Setting column format SQL> column nationality format A8; SQL> select * from artist; ARTISTID NAME NATIONAL BIRTHDATE DECEASEDDATE Miro Spanish Kandinsky Russian
Setting personal defaults with login.sql Contents of file login.sql in sqlplus starting directory: set pagesize 0 set linesize 190 define _editor=vi set serveroutput on
Most common Oracle data types Varchar2 –Same as Varchar Char Number( precision, scale ) –Precision = no. of digits –Scale = no. of digits to right of decimal Date –DD-Mon-YY default format –TO_DATE( ’02/12/1948’, ‘MM/DD/YYYY’ )
CREATE TABLE CREATE TABLE SAILORS (SailorID NUMBER(4) Not Null, Name Char(20) Not Null, Rating NUMBER(2), Age NUMBER(3), CONSTRAINT SailorsPK PRIMARY KEY (SailorID)); CREATE TABLE SAILORS (SailorID NUMBER(4) Not Null CONSTRAINT SailorsPK PRIMARY KEY, Name Char(20) Not Null, Rating NUMBER(2), Age NUMBER(3), ); Using table-level constraints: Using column-level constraints:
Adding constraints to tables ALTER TABLE SAILORS ADD CONSTRAINT SailorsAK UNIQUE Name; Viewing constraints SELECT CONSTRAINT_NAME, TABLE_NAME FROM USER_CONSTRAINTS ORDER BY TABLE_NAME; SELECT CONSTRAINT_NAME, COLUMN_NAME FROM USER_CONS_COLUMNS WHERE TABLE_NAME = ‘Sailors’;
Creating an Oracle Sequence (for use as surrogate key) DROP SEQUENCE CustomerSeq; DROP SEQUENCE ArtistSeq; DROP SEQUENCE WorkSeq; DROP SEQUENCE TransSeq; CREATE SEQUENCE CustomerSeq START WITH 1000; CREATE SEQUENCE ArtistSeq START WITH 1; CREATE SEQUENCE WorkSeq START WITH 500; CREATE SEQUENCE TransSeq INCREMENT BY 10 START WITH 100;
Adding data to tables Insert Into TRANSACTION Values (TransSeq.nextval, '27-FEB-1974', 8750, '18-MAR-1974', 18500, 20000, 1003, 500); Insert Into ARTIST Values (ArtistSeq.nextval, 'Klee', 'German', 1900, null); Insert Into ARTIST Values( ArtistSeq.nextval, &name, &nationality, &birthdate, &deceaseddate); Enter value for name: Magoo Enter value for nationality: Russian Enter value for birthdate: 1939 Enter value for deceaseddate: NULL / Using substitution variables (&)
25 A note on Oracle’s table ‘DUAL’ DUAL is a table owned by SYS that has only 1 row, and only 1 column called ‘dummy’. The single field contains the single character X. To understand the SQL, note the following: SQL> select * from tab1; ENO Now if you select an expression, say 1, from tab1 SQL> select 1 from tab1; If you select an expression a+b from tab1 SQL> select 'a+b' from tab1; 'A+ --- a+b a+b a+b Since DUAL has only 1 row, we can conveniently Use it to return single values: SQL> select SYSDATE from DUAL; SYSDATE APR-05 SQL> select 25000*.25 from DUAL; 25000* SQL> select CustomerID.nextVal from DUAL; NEXTVAL Adapted from Indira Aramandla on
Single-row Character Functions UPPER(‘Reynolds’) ‘REYNOLDS’ LOWER(‘Reynolds’) ‘reynolds’ INITCAP(‘carl reynolds’) ‘Carl Reynolds’ SELECT name FROM Customer WHERE UPPER(state) = ‘NY’; SUBSTR(‘Carl Henry’, 7, 4) ‘enry’ INSTR(‘Reynolds’, ‘o’) 5 TRIM(‘o’ FROM ‘oh no’) ‘h n’ LTRIM(‘ ’, ‘0’) ‘47.45’ RTRIM(‘foo’, ‘o’) ‘f’ LPAD(‘Main Point’, 12, ‘*’) ‘**Main Point’ RPAD(‘Carl’, 10, ‘ ‘) || ‘R’ ‘Carl R’ REPLACE(‘Carl Henry Reynolds’, ‘Henry’, ‘H’) ‘Carl H Reynolds’ SQL> select RPAD('Carl', 10, ' ') || 'R' from dual; RPAD('CARL' Carl R
Single-row Numeric Functions ROUND(3.141, 2) 3.14 CEIL(3.141) 4 FLOOR(3.141) 3 TRUNC(99.999, 1) 99.9 POWER(5, 3) 125 ABS(-14) 14 MOD(12, 5) 2 SIGN(-48.4) -1 SIGN(15) 1 SIGN(0) 0 SQL> select ceil(3.141) from dual; CEIL(3.141)
Date Functions EXTRACT(year|month|day FROM date) EXTRACT(year FROM SYSDATE) 2006 Date1 – Date2 Number of days between SQL> select to_date('12-dec-05') - to_date('31-oct-05') from dual; TO_DATE('12-DEC-05')-TO_DATE('31-OCT-05') ROUND(date, ‘MONTH’|’YEAR’) SQL> select sysdate, round(sysdate,'month') from dual; SYSDATE ROUND(SYS JAN FEB-06
Displaying dates TO_CHAR(number|date, ‘format’) 1 select sysdate, to_char(sysdate, 'Q') as quarter, 2 to_char(sysdate, 'DAY') as day, 3 to_char(sysdate, 'DDTH') as th, 4* to_char(sysdate, 'DDD') as DOY from dual SQL> / SYSDATE Q DAY TH DOY JAN-06 1 WEDNESDAY 18TH 018
Dealing with NULL values NVL(column, replacementValue) NVL(payoff, 0) NVL(hire_date, ’01-JAN-2006’) NVL2(column, ifNotNull, ifNull) SQL> select name, nvl2(deceaseddate, 'dead', 'alive') from artist; NAME NVL2( Miro dead Kandinsky dead Frings dead Klee alive Moos alive
Creating Aliases for Long Names CREATE SYNONYM FOR ; CREATE SYNONYM customer FOR jbr2389.customer; Now: SELECT * FROM customer Simpler than other form: SELECT * FROM jbr2389.customer DROP SYNONYM ; DROP SYNONYM customer;
Remember: Set serveroutput on With serveroutput off (default): With serveroutput on: Was it successful or not?!?!?! SQL> Execute Record_Sale( 'Dick Cheney', 'Cezanne', 'kindergarten', '8', 3550, :vReturn); PL/SQL procedure successfully completed. SQL> Execute Record_Sale( 'Dick Cheney', 'Cezanne', 'kindergarten', '8', 3550, :vReturn); Entered stored procedure Looking up CustomerID Looking up ArtistID Finding Work record Finding Transaction record Testing to see if a Transaction record was found No valid Transaction record exists. Transaction not completed. PL/SQL procedure successfully completed.