Oracle SQL

July 24, 2019 | Author: knsanji | Category: Database Schema, Sql, Databases, Table (Database), Database Index
Share Embed Donate


Short Description

Download Oracle SQL...

Description

Oracle SQL

CONTENTS ................................................................................................ ............................................................... ............................... ..........................2 ........................2 CONTENTS................................................................ ............................................................. .................................. ............................... ......................3 ....................3 INTRODUCTORY CONCEPTS .............................................................

.................................................................. 3 THE D ATABASE O BJECTS ................................................................ ATABASE BJECT AMING ULES ................................ ................................ .................................................4 D O N R ........................................................................................4 D ATATYPES................................................................ TH E DATA DATA DEFINITION COMMA COMMANDS

........................... .......... ...... 8 FOR TABLES ............................... .............................

CREATING A TABLE ................................ ...........................................................................................................8 ................................................................. 9 CONSTRAINTS ON TABLES................................................................ .........................................................................................................12 D ROPPING A TABLE ................................ .........................................................................................................13 ALTERING LTERING A TABLE ................................ ...............................................................................14 SAMPLE TABLES ................................................................

.............................. ..............................................................15 ............................................................15 QUERYING THE TABLES TABLES............................ ..................................

..............................................................................15 CONDITIONAL RETRIEVAL OF ROWS ................................ ..............................................................................17 SQL FUNCTIONS................................................................ G ROUP (OR AGGREGATE ) FUNCTIONS ................................ ...........................................................................17 ..........................................................................20 SINGLE ROW ( OR SCALAR) FUNCTIONS................................ ...............................................................................27 JOINS TO Q UERY MULTIPLE TABLES................................ ..............................................................................29 SET O PERATORS ................................................................ N ESTED Q UERIES ................................ ............................................................................................................30 ............................................................ ........33 ..... 33 DATA MAN MAN IPULATION COMMAND COMMAND S ............................... ..............................................................

................................................................33 33 THE INSERT COMMAND ................................................................ THE DELETE COMMAND ................................................................ ...............................................................33 33 THE UPDATE COMMAND ................................................................ ...............................................................33 33 ...................................................35 TH E TRANSA TRANSACTION CTION CONTROL COMMAND COMMAND S ............................... .....................................................35

...............................................................35 35 THE COMMIT COMMAND ................................................................ ..........................................................................................35 35 THE ROLLBACK COMMAND ................................ ............................................................ .........................37 .....................37 WORKING WITH WITH OTH ER SCHE MA OBJECTS OBJECTS ............................................................ SEQUENCES................................................................ ............................................................................... ....... ............... .......37 37 ............................................................................................................... ....... ............... .........38 38 SYNONYMS ................................ ...............................................................................................................................39 39 VIEWS................................ ...........................................................................................................................41 41 INDEXES................................ CLUSTERS ................................................................ .........................................................................................42 42

Infosys

ORACLE 8i

Introductory Concepts ? ? ? ?

SQL (Structured (Struct ured Query Language) is a standard RDBMS language. Oracle SQL is is the set of commands that all pr ograms and users must must use to access and modify the data within the Oracle Database. For executing SQL queries in the user schema, he/she must be granted some type of  system privi privileges leges by DBA. The SQL statements can be be broadly classi classifi fied ed into three categ ories: Definition on Language (DDL) - Used to create, alter, or drop dro p objects objects (e.g., tao Data Definiti bles, indexes, synonym synonyms, s, views, views, clusters, etc.) in the database o Data Manipulation Manipulation Language (DML) - Used to query, insert insert,, delete and update of  data stored in the database. o Data Control Language (DCL) - Used for controll contro llin ing g data stored sto red in the dat abase.

The Database Objects ? ?

? ?

?

The database objects are entities stored store d in in the database. These objects may be either schema schema objects objects , or non-schema non-schema objects objects . Schema objects are objects belonging to a particular schema. A schema is made up of  a collection of logical structures of data, or schema objects. A schema is owned by a database user and has the same same na me as that user (e.g., scott, trng01, t rng01, etc.). Each E ach user owns a single schema. SQL is used to create and manipulate the schema objects. Some schema objects are listed: o Clusters o Database Links o Database Triggers o Indexes o Packages o Sequences o Stored Functions o Stored Procedures o Synonyms o Tables o Views Other types of objects objects are also also stored in the database and can be be created and manip manip ulated with SQL, but are not contained in a schema. These are  non-schema objects , and some of them are listed blow: o directories o profiles o roles o rollback segments o tablespaces

o

users

Database Object Naming Rules ? ? ? ? ? ? ?

Maximum Maximum character length length can be 30 (Except for database names names which which are li mited to 8 characters). Must not contain a question mark. Case insensitive. insensitive. Must begin with an alphabet. May only contain the characters a -z, A-Z, 0-9, _, $ and #. Must not duplicate duplicate an Oracle Reserved word. Must not duplicate duplicate another database object belongin belonging g to that user. Object Name

Valid/Invalid

Reason

employee 1_test check Spp&prts Pass/fail

valid invalid invalid invali invalid d invali invalid d invali invalid d

Begins with a number ORACLE reserved word Use of “ &” not all allowed Use of “/” not allowed allowed

Datatypes Internal Datatype

Description

VARCHAR2(size)

Variable length character string having maximum length size bytes. Maximum size is 4000, and minimum is 1. You must specify size for a VARCHAR2.

NUMBER(p,s)

Number having precision  p and scale s. Character data of variable variable length up to 2 gigabytes, or 31 2 -1 bytes. Valid Valid date range from January 1, 4712 BC to Dec ember ember 31, 4712 AD. AD. Stores time time too. Raw binary data of length size bytes. Maximum size is 2000 bytes. You must specify size for a RAW value. This datatype datat ype is used to store binary data. Raw binary binary data of variable variable length length up to 2 giga g iga bytes.

LONG DATE RAW(size)

LONG RAW

Infosys

ROWID

CHAR(size)

CLOB

ORACLE 8i

Hexadecimal string representing the unique address of a row in its table. This datatype is primarily for values r eturned by the ROWID pseudocolumn. Fixed length character data of length size bytes. Maximum size is 2000 bytes. Default and minimum size is 1 byte. A character large object containing single byte characters. Maximum size is 4 gigabytes. A binary large object. Maximum size is 4 gigabytes. Contains a locator to a large binary file stored ou tside the database. Enables byte stream I/O access to external LOBs residing on the database server.

BLOB BFILE

Character Datatypes ?

?

?

CHAR and VARCHAR2 are the character datatypes that can be used to store and ma-

nipulate text data in a table column. CHAR specifies a fixed length character string (e.g., CHAR(10)) for a defined column. In case you store a string that is smaller than the column length, Oracle blank pads the value to the column length. The VARCHAR2 specifies the maximum number of bytes of data that it can hold in a column. Oracle stores each value in the column exactly as specified (without any blank-padding).

Number Datatype ? ?

The NUMBER datatype is used to store zero, positive and negative f ixed and floating point numbers. You can specify a fixed poi nt number with: NUMBER(p,s)

?

You specify an integer with: NUMBER (p)

?

You specify a floating point number with: NUMBER

LONG Datatype ?

LONG is used to store large text strings, up to 2GB in size.

?

There are certain restrictions when you use a LONG column: o A table cannot contain more than one LONG column. o LONG columns cannot appear in integrity constraints (except for NULL and NOT NULL constraints). o LONG columns cannot be indexed. o A stored function cannot return a LONG value.

o

?

LONG columns cannot appear in certain parts of SQL statements: WHERE, GROUP BY, ORDER BY, in SELECT statements, SQL functions such as SUBSTR or INSTR, expressions or conditions

Due to such restrictions, it is recommended that you use CLOB datatype to store large character data instead of the LONG datatype.

DATE Datatype ?

? ?

The DATE datatype is used to store the date and time information. For each DATE value the following information is stored: o century o year o month o day o hour o minute o second The function TO_DATE can be used to convert a string (or numeric) value to date format. This function is discusses later. You can get the current date and time using the function SYSDATE (e.g., SELECT SYSDATE from DUAL;)

RAW and LONG RAW Datatypes ? ? ?

The RAW and LONG RAW datatypes are used for raw binary data that is not to be interpreted by Oracle. Examples of such data include pictures, sound, documents, etc. LONG RAW data cannot be indexed, but RAW data can be indexed. It is recommended that you use BLOB datatype for binary data ins tead of RAW datatypes.

Large Object (LOB) Datatypes ? ? ?

? ?

The Large Object (LOB) datatypes can store up to 4 GB of unstructured data such as text, image, video, documents, etc. BLOB, CLOB , and BFILE are the three types of LOBs. BLOB and CLOB are called inter nal LOBs as they store data within the database. BFILE is called external LOB as the corresponding data is stored external to the dat abase, in the OS files. An Oracle-supplied package, DBMS_LOB, is used to work with the LOB data. Any number of columns in t able can be of LOB type (unlike the LONG or LONG RAW types)

ROWID Datatype

Infosys

ORACLE 8i

?

ROWID (represented as a hex string) represents the address of a ro w in a table in the database. You can view this address by querying the pseudocolumn ROWID in a table (e.g., SELECT ROWID FROM emp;).

?

An Oracle-supplied package DBMS_ROWID let you interpret the meaning of the hex address string of the ROWID.

The Data Def inition Commands f or Tables ? ? ? ? ?

Here we look at the DDL commands to work with one of the database objects – tables. Table can be created with the CREATE TABLE command. Various integrity co nstraints let you impose restrictions on the data that gets into the tables, according to the business rules. The structure of the table can be altered using the ALTER TABLE comm and. The same command can be used to add or drop the constraints on the table. You can remove a table from the database with the DROP TABLE command.

Creating a Table Tables are created using the CREATE TABLE command, and owned by the user who cr eates them. ?

Syntax CREATE TABLE table ({column datatype [DEFAULT expr  ] [constraint]} [,{column datatype [DEFAULT expr  ] [constraint]}]...) [CLUSTER cluster (column [, column] ...)] [AS query  ]

o

DEFAULT specifies a value to be assigned to the column if a row is inserted wit h-

out a value for this column. o CLUSTER includes this table in the named cluster (this is discusses later in a separate section) Example: CREATE TABLE products ( productno NUMBER(4), productname VARCHAR2(20), quantityonhand NUMBER (4));

Infosys

ORACLE 8i

Constraints on Tables ? ? ?

Constraints limit the values entered into the columns of the table , thereby ensuring the integrity of the data in the database. The business rules are translated as constraints on the tables (e.g., each employee number should be unique, the valid product categories can be A, B, or C only, etc.) Depending on the placement of the constraint, a constraint can be termed a column constraint, or a table constraint: o a column constraint : Constraint specified as part of the column defin ition: o a table constraint: Constraint specified towards the end of the CREATE TABLE statement

Types of Constraints Constraint

Description

NULL | NOT NULL UNIQUE

Specifies if a column may or may not support NULL values . Forces values of a column (or com bination of columns) to be unique. The unique key made up of a single column can contain nulls. Identifies a column (or combination of columns) as a primary key. A primary key value cannot appear in more than one row in the table, and it canno t be null either (it is equivalent to UNIQUE NOT NULL). A table can have only one primary key. Also called a referential integrity constraint, designates a co lumn (or combination of columns) as a foreign key to a specified primary or unique ke y, called the referenced key. In this rel ationship, the table contai ning the foreign key is called the child table and the table co ntaining the referenced key is called the parent table. Specifies a condition that the column (or combination of co lumns) must satisfy for the row to exist in the table.

PRIMARY KEY

FOREIGN KEY

CHECK

Example 1: NOT NULL constraints CREATE TABLE products ( productno NUMBER(4) NOT NULL, productname VARCHAR2(20) CONSTRAINT NNL_pname NOT NULL, quantityonhand NUMBER (4));

 Named and unnamed constraints : ? In the example above , the first NOT NULL constraint an unnamed constraint, where as the second NOT NULL constraint is given a nam e NNL_pname. The

? ?

unnamed co nstraints will automatically be assigned system generated names (of  the format SYS_Cxxx where xxx is a unique number) by Oracle. Naming the constraints will help manage the constraints better. The information about the constrain ts will be stored in the data dictionary table user_constraints. To view the constraints, issue a query like the one given below: SELECT TABLE_NAME, CONSTRAINT_NAME, CONSTRAINT_TYPE FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'PRODUCTS';

Example 2: UNIQUE constraints

CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(10) loc VARCHAR2(10) ); /* column constraint */

CONSTRAINT unq_dname UNIQUE,

CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(10), loc VARCHAR2(10), CONSTRAINT unq_dname UNIQUE (dname) ); /* table constraint */

Example 3: PRIMARY KEY constraint CREATE TABLE dept (deptno NUMBER(2) CONSTRAINT pk_dept PRIMARY KEY, dname VARCHAR2(10) CONSTRAINT unq_dname UNIQUE, loc VARCHAR2(10) ); /* column constraints */

CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(10), loc VARCHAR2(10), CONSTRAINT pk_dept PRIMARY KEY (deptno), CONSTRAINT unq_dname UNIQUE (dname) ); /* table constraints */

Infosys

ORACLE 8i

Example 4: FOREIGN KEY constraint CREATE TABLE emp (empno NUMBER(4), ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), hiredate DATE DEFAULT SYSDATE, sal NUMBER(7,2), comm NUMBER(7,2), deptno NUMBER(2) CONSTRAINT fk_deptno REFERENCES dept(deptno), grade CHAR(1) ); /* column constraint */

CREATE TABLE emp (empno NUMBER(4), ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), hiredate DATE, sal NUMBER(7,2), comm NUMBER(7,2), deptno NUMBER(2), grade CHAR(1), CONSTRAINT fk_deptno FOREIGN KEY (deptno) REFERENCES dept(deptno) ); /* table constraint */

 Note: ?

?

?

Before you define a referential integrity constraint in the child table, the refe renced UNIQUE or PRIMARY KEY constraint on the parent table must already be defined . For the example above, dept table should have deptno designated as PRIMARY KEY already. Having a foreign key allows you to maintain referential integrity of your data. For example, having declared a foreign key deptno in emp table, if you try to insert a row in table emp with a deptno value 50, this deptno should be present in the parent table dept already; else the insert fails. The ON DELETE CASCADE option with foreign key: You cannot delete the pa rent table row in case there are referencing child table rows. With ON DELETE CASCADE option, Oracle permits deletions of referenced key values in the pa rent table and automatically deletes dependent rows in the child table to maintain re ferential integrity:

CREATE TABLE emp (empno NUMBER(4), ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), hiredate DATE, sal NUMBER(7,2), comm NUMBER(7,2), deptno NUMBER(2) CONSTRAINT fk_deptno REFERENCES dept(deptno) ON DELETE CASCADE, grade CHAR(1) );

Example 5: CHECK constraints CREATE TABLE emp (empno NUMBER(4), ename VARCHAR2(10), job VARCHAR2(9) CONSTRAINT chk_job CHECK (job IN ('CLERK', 'SALESMAN','ANALYST', 'PRESIDENT')) , mgr NUMBER(4), hiredate DATE, sal NUMBER(7,2), comm NUMBER(7,2) CONSTRAINT chk_comm CHECK (comm BETWEEN 100 AND 1000), deptno NUMBER(2) CONSTRAINT fk_deptno REFERENCES dept(deptno) ON DELETE CASCADE, grade CHAR(1) CONSTRAINT chk_totsal CHECK (sal + comm , =, 1500 ORDER BY ename;

To list all the managers in department 20 SELECT * FROM emp WHERE job='MANAGER' AND deptno=20;

To list emp loyee details whose salary is between 1000 and 2000 SELECT * FROM emp WHERE sal >= 1000 AND sal 2; Dept Employees ---------- ---------20 4 30 3

 Note: The selected columns in the query (involving a GROUP BY clause) must form the list of columns spe cified in the GROUP BY clause or should be group functions.

Single Row ( or Scalar) Functions N u m b e r F u n c t io n s ABS(value) CEIL(value) COS(value) COSH(value) EXP(value) FLOOR(value) LN(value) LOG(value) MOD(value)

POWER(value, exponent) ROUND(value, precision) SIGN(value) SIN(value) SINH(value) SQRT(value) TAN(value) TANH(value) TRUNC(value, precision)

Examples: Number Functions SELECT ABS(-15) “Absolute” FROM DUAL; Absolute ---------15 SELECT FLOOR(15.7) “Floor” FROM DUAL; Floor ---------15 SELECT POWER(3,2) “Raised” FROM DUAL; Raised ---------9

SELECT CEIL(15.7) “Ceiling” FROM DUAL; Ceiling ---------16 SELECT MOD(11,4) FROM DUAL; MOD(11,4) ---------3 SELECT ROUND(15.193,1) “Round” FROM DUAL; Round ---------15.2

Infosys

ORACLE 8i

SELECT ROUND(15.193,-1) “Round” FROM DUAL; Round ---------20 SELECT TRUNC(15.79,1) “Truncate” FROM DUAL; Truncate ---------15.7

SELECT SIGN(-20) “Sign” FROM DUAL; Sign ----------1 SELECT TRUNC(15.79,-1) “Truncate” FROM DUAL; Truncate ---------10

S t r i n g F u n c t io n s

Function

Description

String || String

Concatenates two strings Returns ASCII value of the character Returns character corresponding to the ASCII integer value Concatenates two strings Capitalizes the first letter of the string Returns an integer indicating the pos ition of the character in string that is the first character of  this occurrence Returns the length of the string Converts all characters to lower case Returns string right-padded to length n with the sequence of characters in set Removes characters from the left of  sring  , with all the leftmost characters that appear in set removed Returns string left-padded to length n with the sequence of characters in set Removes characters from the right of  sring  , with all the leftmost characters that appear in set removed Returns a string containing the phonetic repr esentation of string . This function allows you to compare words that are spelled d ifferently, but sound alike in English. Returns the count characters starting from start  in the string Converts all characters to upper case

ASCII(string) CHR(integer) CONCAT(string1, string2) INITCAP(string) INSTR(string, set[,start[,occurrence]])

LENGTH(string) LOWER(string) LPAD(string, n[,’set’]) LTRIM(string[,’set’])

RPAD(string, n[,’set’]) RTRIM(string[,’set’])

SOUNDEX(string)

SUBSTR(string, start[, count]) UPPER(string)

Examples : String Functions SELECT ename || ', ' || job FROM emp WHERE deptno=10;

SELECT ASCII(‘A’), ASCII(‘B’) FROM DUAL;

ENAME||','||JOB --------------------CLARK, MANAGER MILLER, CLERK SELECT LOWER(ename)"Lower", UPPER(ename) "Upper", INITCAP(LOWER(ename)) "Initcap" FROM emp WHERE deptno=20; Lower Upper Initcap ---------- ---------- ---------jones JONES Jones scott SCOTT Scott adams ADAMS Adams ford FORD Ford SELECT RPAD(ename, 20, '.'), deptno FROM emp WHERE deptno=20; RPAD(ENAME,20,'.') DEPTNO -------------------- ---------JONES............... 20 SCOTT............... 20 ADAMS............... 20 FORD................ 20 SELECT SUBSTR(hiredate, 4) FROM emp WHERE deptno=10;

ASCII('A') ASCII('B') ---------- ---------65 66

SELECT ename, LENGTH(ename) FROM emp WHERE deptno=20; ENAME LENGTH(ENAME) ---------- ------------JONES 5 SCOTT 5 ADAMS 5 FORD 4 SELECT LPAD(ename, 15), sal FROM emp WHERE deptno=20; LPAD(ENAME,15) SAL --------------- ---------JONES 2975 SCOTT 5000 ADAMS 1100 FORD 5000 SELECT ename, INSTR(ename, 'I') "I Posn." FROM emp WHERE deptno=10;

SUBSTR ENAME I Posn. --------------- ---------JUN-81 CLARK 0 JAN-82 MILLER 2 SELECT loc FROM dept WHERE SOUNDEX(loc)=SOUNDEX('Sidney'); --both Sidney and Sydney would match

G e n e r a l Fu n c t i o n s

Function

Description

GREATEST (expr [,expr]…)

Returns the greatest of the list of expre ssions. The expression can be numeric, character, or date. Returns the least of the list of expressions . The expression can be numeric, character, or date. If expr1 is null, returns expr2; if expr1 is not null, returns expr1 If the value is if1 then the result of the DECODE is then1; if it is if2 then the result is then2, and so on; if  the value equals none of the ifs, then the result is else

LEAST (expr [,expr]…) NVL (expr1, expr2) DECODE (value, if1, then1 [, if2, then2]... else)

Infosys

ORACLE 8i

Examples: General Functions SELECT LEAST

('HARRY', 'HARRIOT', 'HAROLD') "Least" FROM DUAL;

Least -----HAROLD SELECT

GREATEST (23, 645, 123) "Greatest" FROM DUAL;

Greatest ---------645

SELECT ename, sal + comm "totsal", sal + NVL(comm, 0) "to tsal" FROM emp WHERE deptno=30; ENAME totsal totsal ---------- ---------- ---------WARD 1750 1750 BLAKE 2850 TURNER 1500 1500 SELECT ename, NVL(TO_CHAR(comm), 'No Commission') "COMMISSION" FROM emp WHERE deptno = 30; ENAME ---------WARD BLAKE TURNER

COMMISSION --------------------500 No Commission 0

SELECT ename, DECODE(comm, null, 'NOT Eligib le', 0, 'Eligible, but 0', comm) "Commission" FROM emp WHERE deptno=30; ENAME ---------WARD BLAKE TURNER

Commission -----------------------500 NOT Eligible Eligible, but 0

SELECT ename, DECODE(deptno, 10, 'ACCOUNTING', 20, 'RESEARCH', 30, 'SALES', 40, 'OPERATION', 'NONE') "Department" FROM emp WHERE job='CLERK'; ENAME ---------ADAMS MILLER

Department ---------RESEARCH ACCOUNTING

Date Functions

Function ADD_MONTHS(date,n) LAST_DAY(date) MONTHS_BETWEEN(date1, date2) NEXT_DAY(date, ‘day’) TO_CHAR(date, ‘format’)

TO_DATE(string, ‘format’)

Description Adds n months to the date

Returns the date of the last day of the month that contains date Returns number of months between dates date1 and date2 Returns the date of the first weekday named by day that is later than the date date Converts date of DATE datatype to a value of  VARCHAR2 datatype in the format specified by the date format format. If you omit format, date is converted to a VARCHAR2 value in the default date format. Converts string of CHAR or VARCHAR2 datatype to a value of DATE datatype, in the date format specified by format. If you omit format, string  must be in the default date format.

 Date Formats (With both TO_CHAR and TO_DATE) Format

 Description Example/ 

MM RM MON MONTH DDD DD D DY DAY YYYY SYYYY YYY YY Y YEAR Q WW W J HH HH12 HH24 MI SS

12 XII DEC DECEMBER 354 23 6 (day of the week, where Sunday is 1) FRI FRIDAY 1982 -1000 982 82 2 NINETEEN-FORTY-SIX 3 (Number of quarter) 46 3 Julian days since Dec 31, 4713 BC  11 Same as HH  17 58 43

Infosys

SSSS / , - : . A.M P.M AM or PM B.C A.D BC or AD

ORACLE 8i

43000 (0-83699) Punctuation for TO_CHAR

 Date Formats (Only with TO_CHAR) Format

Example/   Description

“string” fm TH SP SPTH THSP

“is” Suppresses padding of Month or Day in format DdTH or DDTH gives: 24th or 24TH DDSP, DdSP, or ddSP gives: THREE, Three, or three DdSPTH gives: Third Same as SPTH 

Examples : Date Functions

To get current date SELECT SYSDATE FROM Dual; SYSDATE --------12-DEC-02

To get a date 5 months back  SELECT SYSDATE "Today", ADD_MONTHS(SYSDATE, -5) "Result" FROM DUAL; Today Result --------- --------12-DEC-02 12-JUL-02

To get the date of next Friday SELECT SYSDATE, NEXT_DAY(SYSDATE, 'THURSDAY') FROM DUAL; SYSDATE NEXT_DAY --------- --------12-DEC-02 19-DEC-02

To get the last of the month SELECT SYSDATE "Today",

LAST_DAY(SYSDATE) "MonthEnd" FROM DUAL;

Today Month End --------- --------12-DEC-02 31-DEC-02

To get a date that is 1st of the month 6 months from now

SELECT SYSDATE TODAY, LAST_DAY(ADD_MONTHS(SYSDATE, 6))+1"REVIEW ON" FROM DUAL; TODAY REVIEW ON --------- --------12-DEC-02 01-JUL-03

To get years of experience of employees in department 20 SELECT ename "Name", hiredate "Joined", ROUND(MONTHS_BETWEEN(SYSDATE, hiredate)/12) "Experience" FROM emp WHERE deptno=20; Name ---------JONES SCOTT ADAMS FORD

Joined Experience --------- ---------02-APR-81 22 19-APR-87 16 23-MAY-87 16 03-DEC-81 21

To get the dates in words SELECT hiredate, TO_CHAR(hiredate,'DD, Month, Year' ) "In Words" FROM emp WHERE deptno=10; HIREDATE --------09-JUN-81 23-JAN-82

In Words ---------------------------------09, June , Nineteen Eighty-One 23, January , Nineteen Eighty-Two

SELECT hiredate, TO_CHAR(hiredate, 'fmMonth, ddTH, YYYY') "In Words" FROM emp WHERE deptno=10; HIREDATE --------09-JUN-81 23-JAN-82

In Words --------------------June, 9th, 1981 January, 23rd, 1982

To get the current time SELECT TO_CHAR(SYSDATE, 'HH:MI:SS') "Time Now" FROM DUAL; Time Now -------12:20:08

To get the day name of a particular date SELECT TO_DATE('29-Aug-68') "Date", TO_CHAR(TO_DATE('29-Aug-68'), 'DAY') "D ay" FROM DUAL; Date Day --------- --------29-AUG-68 THURSDAY

Infosys

ORACLE 8i

Joins to Query Multiple Tables ? ?

Joins are powerful relational operators that combine data from multiple tables into a single result table. There are different types of joins : o Cartesian Joins o Equi Joins o Self Joins o Outer Joins

Cartesian Joins ? ? ?

In this join the tables are joined without any WHERE clause ; each row of one table matches every row of the other table. It is also known as Natural Join. Examples: SELECT supp_name, po_status FROM suppliertab, orderfile; /* List all the information courses offered by them */ SELECT * FROM

about

the

departments

and

department, course;

Equi Joins ? ? ?

When two tables are joined together using equality of values in one or more columns they make an equi join. Table prefixes are used to prevent ambiguity and the where clause is used to specify which columns are to be joined. Example: /*

List the lecturers' name and their department name

*/

SELECT lecturer.c_Lect_Name, department.c_Dept_Name FROM lecturer, department WHERE lecturer.i_Dept_No = department.i_Dept_No ORDER BY lecturer.i_Dept_No;

Outer Joins ? ? ?

When two tables are joined, only those that satisfy the given criteria are retrieved by the query. If the user wants to check which were the rows that did not have a corresponding match and still view the data with N ULL values outer joins are made use of. Examples: List suppliers and their order status (also list the supplier who have not placed the orders */ /*

SELECT supp_name, po_num, po_status FROM suppliertab, orderfile WHERE orderfile.supp_code(+)= suppliertab.supp_code;

 Note: In the above example , the (+) is placed on the side of the table whose co lumns ? do not have a corresponding match in the other table. Also note that you cannot have (+) o perator for both the joined tables. ?

List the lecturers name and their department’s name (list those d epartment also which does not have any employee */ /*

SELECT lecturer.c_Lect_Name, department.c_Dept_Name FROM lecturer, department WHERE lecturer.i_Dept_No =(+) department.i_Dept_No ORDER BY lecturer.i_Dept_No;

Self Joins ? ?

When one row of a table is joined with another of the same table you perform a SELF JOIN. Example: List the name of each employee along with his/her manager from emp table */ /*

SELECT worker.ename, manager.ename FROM emp worker, emp manager WHERE worker.mgr = manager.empno;

In the above example, since both the employee and his/her manager are part of the same table a self joi n is made use of.

Infosys

ORACLE 8i

 Note: To distinguish the columns of the copy of the same table , table aliases are used. In JOINS when the table name has to be written to specify columns more than once then it is better to use aliases in place of writing big table name s.

Set Operators ? ?

Set operators combine 2 or more queries into a single result. The data type of the corresponding columns must be the same. The different set operators: o o o

UNION INTERSECT MINUS

UNION ? ? ?

This operator is useful when it is required to draw info rmation from more than one table that have the same structure. It returns rows of the first query plus the rows of the second query after eliminating duplicate rows. Example: List the employees from account and research tables whose salary is greater than 2000 */ /*

SELECT ename, sal FROM account WHERE sal > 2000 UNION SELECT ename , sal FROM research WHERE sal > 2000;

INTERSECT ?

INTERSECT returns only those rows that are common to bo th queries.

?

Example:

List the jobs that are common in research, accounts and sales d epartment */ /*

SELECT job FROM research INTERSECT SELECT job FROM accounts INTERSECT SELECT job FROM sales;

 MINUS ?

MINUS returns rows that are unique to the first query.

?

Example: /*

List the jobs which are done in accounts only and not in sales

*/

SELECT job FROM account MINUS SELECT job FROM sales;

.

Nested Queries ?

? ? ?

In this type of query the result of one query is dynamically substituted in the cond ition (WHERE clause) of another query. In nested queries, the sub query within the WHERE clause is evaluated first. The r eturn value is then substituted in the condition of the outer query. Oracle supports infinite level of nesting. The general syntax for a nested or sub query is : SELECT col1 [, col2]... FROM table1 WHERE column operator (SELECT column FROM table2 WHERE condition);

Infosys

?

ORACLE 8i

Examples: /*

To list the names of employees drawing the highest salary */ 

SELECT ename, sal FROM emp WHERE sal = (SELECT MAX (sal) FROM emp); ENAME SAL ---------- ---------SCOTT 5000 FORD 5000

 Note: When using relational operators with subqueries, ensure that the sub query returns a single row output. For comparison with a set of rows returned by the subquery, use the IN operator.

To list all the managers in the emp table who have more than 1 person reporting to him/her */  /*

SELECT empno FROM emp WHERE empno IN (SELECT mgr FROM emp GROUP BY mgr HAVING COUNT(*) > 1); EMPNO ---------7566 7698

Correlated Subqueries ? ?

SQL sub queries that perform the subquery over and over again, once for each row of  the outer query are called correlated subqueries. Example: List all items whos e quantity is greater than the average transaction qua ntity for that item */  /*

SELECT item_code, trans_qty FROM trans_file tfile WHERE trans_qty > ( SELECT AVG(trans_qty) FROM trans_file WHERE tfile.item_code = trans_file.item_code) ORDER BY item_code;

 Note: While referring to the outer query , alias is mandatory in the inner query. Using the EXISTS operator in subqueries ? ?

EXISTS is a special operator that returns TRUE if a subquery returns at least one row. Examples:  /* To list the employee details only if more than 3 employees are present in dept 20 */  SELECT * FROM emp WHERE deptno = 20 AND EXISTS (SELECT COUNT(*) FROM emp WHERE deptno = 20 GROUP BY deptno HAVING COUNT (*) > 3 );

 /* To list out the department details in which there are any employees */  SELECT dname, deptno FROM dept WHERE EXISTS (SELECT * from emp WHERE dept.deptno = emp.deptno); DNAME DEPTNO -------------------- ---------Accounting 10 Research 20 Sales 30

Infosys

ORACLE 8i

Data Manipulation Commands The DML commands INSERT, UPDATE, and DELETE are discussed in this section.

The INSERT command ?

INSERT statement is used to insert values into the table.

?

Syntax: INSERT INTO table [ ( column [, column ]… ) ] { VALUES ( expression [, expression ]… ) | query }

? ? ? ?

The INSERT with a VALUES clause inserts a single row into the table The INSERT with a query is used to add all the rows returned by a query at once. All data types to be included in quote s(' ') , except numeric data types. Examples: INSERT INTO dept VALUES (60, 'Education', ' Boston'); INSERT INTO emp (empno, ename, deptno) VALUES (8000, 'John', 20); --rest of the columns will take a null or default value

The DELETE Command ? ?

Using the DELETE statement row (s) can be deleted from a table. Syntax: DELETE FROM table [WHERE condition];

?

Examples: DELETE FROM emp; -- deletes all rows DELETE FROM emp WHERE empno=8000;

The UPDATE Command ?

The UPDATE statement is used to change existing values in a specified table.

?

Syntax:

UPDATE table SET {column = expression [, column = expression]... | ( column [, column]…) = (subquery ) } [WHERE condition];

 Note: Update without a WHERE clause will update all the rows in a table. ?

Example: To modify the salary and dep artment number of SMITH UPDATE emp SET sal = sal + 100, deptno = 30 WHERE ename = 'SMITH';

Infosys

ORACLE 8i

The Transaction Control Commands ? ? ?

A transaction (or a logical unit of work) is a sequence of SQL statements that Oracle treats as a single unit. The Transaction Control commands manage changes made by insert, update or d elete commands. The transaction control commands are: o o

?

COMMIT ROLLBACK

A transaction begins with the first executable SQL statement after a COMMIT, ROLLBACK or connection to the database. A transaction ends with a COMMIT, ROLLBACK or disconnection (intentional or unintentional) from the d atabase.

The COMMIT Command ?

COMMIT is used to end the current transaction and make permanent all changes done

?

in the transaction. This comma nd also releases the transaction's locks. Example:

?

INSERT INTO dept VALUES (60, 'Education', 'London'); COMMIT;

Upon commit, the inserted row resides permanently in the database .

The ROLLBACK Command ? ?

A ROLLBACK undoes all the changes in the current transaction, and ends the transa ction. It also releases the transaction's locks. Example: DELETE FROM emp; ROLLBACK;

ROLLBACK with SAVEPOINT ?

Using the ROLLBACK command with the TO SAVEPOINT clause performs the fo llowing o perations: o Rolls back just the portion of the transaction after the savepoint. o Erases all savepoints created after that savepoint. o Releases all the locks obtained since the savepoint.

?

Example : UPDATE emp SET sal = sal + 100 WHERE deptno = 10; SAVEPOINT s1; DELETE FROM emp WHERE empno = 8000; ROLLBACK TO SAVEPOINT s1;

In the above example, only the DELETE statement will be rolled back. The UPDATE is neither committed nor rolled back at this point.

Infosys

ORACLE 8i

Working with Other Schema Ob jects ?

Some of the database schema objects that we will work with are: o Sequences o Synonyms o Views o Indexes o Clusters

Sequences ?

? ?

Sequences are used to generate sequential numbers, helpful in multi -user environments to generate and return unique se quential numbers, and to generate unique int egers for use as primary keys. Sequence generators are objects that are stored as part of the database. Syntax: CREATE SEQUENCE seqname [INCREMENT BY n] [START WITH m] [MAXVALUE integer | NOMAXVALUE ] [MINVALUE integer | NOMINVALUE ] [CYCLE | NOCYCLE ] [CACHE integer | NOCACHE ]

 Note: The default INCREMENT BY is 1. A positive number will cause incrementing up and ? a negative number incrementing down. The default for MINVALUE for ascending sequences is 1. ? The default for MAXVALUE for descending sequences is -1. ? The default START WITH is MAXVALUE for descending sequences and MINVALUE ? for ascending; use START WITH to override this default. To restart a sequence, specify CYCLE. ? ? CACHE allows a preallocated set of sequence numbers to be kept in memory. The d efault is 20. ? To use the contents of a sequence use seq_name.CURRVAL or seq_name.NEXTVAL. ?

seqname.CURRVAL returns the current value of the sequence.

?

seqname.NEXTVAL returns the next value of the sequence. Also increments the

value.

Examples: CREATE SEQUENCE dept_seq START WITH 1 INCREMENT BY 1;

To use the sequence: INSERT INTO dept (deptno, dname, loc) VALUES (dept_seq.NEXTVAL, 'Education', 'Fremont');

SELECT dept_seq.CURRVAL FROM DUAL; SELECT dept_seq.NEXTVAL FROM DUAL;

 DUAL is Oracle supplied table that is made up of one column and one row. This table is available to all users by default.

Synonyms

?

A synonym is just another name for a database object. Synonyms do not require additional storage other than its definition in the data di ctionary. Synonyms are used: o For security reasons to mask the owner and name of the object o To simplify SQL statements. o To provide transparency to user from remote databases.

?

Whenever a user execute the query for example,

? ?

SELECT * FROM table_name;

Oracle interprets it as SELECT * FROM owner.table_name;

Infosys

ORACLE 8i

If the user is not the owner of the table then he has to use owner.table_name. In order to hide the actual owner as well as table_name synonyms can be used as fo llows: CREATE PUBLIC SYNONYM syn_name FOR owner.table_name;

Example: Creation and use of Synonyms CREATE PUBLIC SYNONYM pucust FOR scott.customer; SELECT * FROM pucust; INSERT INTO pucust(...) VALUES(...)

The PUBLIC option indicates that any user can access the synonym.

 Views ? ? ? ? ? ? ?

A view is a logical table. It does not contain any data itself; it draws data from other tables and views. The tables on which a view is based are called  base tables. Views are constructed with queries. A view takes the output of a query and treats it as a table; hence, a view can also be thought of as a “stored query” or a “virtual table”. You can use the normal querying on the views as though views were tables the mselves. Insert, update, and delete to the base tables through the view is subject to certain r estrictions. All operations performed on a view actually affect data in the base tables of the view. Views can used to for various reasons like: o Store complex queries o Provide security to base tables by exposing only certain portions of table data through views o Isolate applications from changes in definitions of base tables

Creating Views

The CREATE VIEW DDL command is used to create a view, that mentions a query based on which the view is created (in the absence of  aliases, the view column names are same as that mentioned in the query) : CREATE [OR REPLACE] VIEW view  [ ( alias [, alias ]… ) ] AS query  [WITH CHECK OPTION] [WITH READ ONLY]

WITH READ ONLY option specifies that no deletes, inserts, or updates to the base table

can be pe rformed through the view. WITH CHECK OPTION specifies that inserts and updates performed through the view must result in rows that the view query can select Examples of Views

Suppose you would like to expose only part of the emp table. You can do so by creating a view that selects certain columns from the table, and using (or granting privileges on, to other users) this view, as shown below. Table EMP EMPNO ENAME 7329 SMITH 7499 ALLEN 7521 WARD 7566 JONES

JOB CLERK SALESMAN SALESMAN MANAGER

MGR 7902 7698 7698 7839

HIREDATE 17-DEC-87 20-FEB-88 22-FEB-88 02-APR-88

EMPNO 7329 7499 7521 7566

JOB CLERK SALESMAN SALESMAN MANAGER

MGR 7902 7698 7698 7839

DEPTNO 20 30 30 20

ENAME SMITH ALLEN WARD JONES

SAL 300.00 300.00 5.00

COMM 80 600 250 975

DEPTNO 20 30 30 20

 View STAFF

The above view is created with the DDL: CREATE VIEW staff AS SELECT empno, ename, job, manager, deptno FROM emp;

You can then use the view as a normal table: SELECT * FROM Staff; INSERT INTO staff VALUES (8000, 'John', 'SALESMAN', 7839, 20);

If you did not want any insert or update to the base table through this view , create the view with WITH READ ONLY option: CREATE VIEW staff AS SELECT empno, ename, job, manager, deptno FROM emp WITH READ ONLY;

Infosys

ORACLE 8i

If you want to create a view that exposes only the clerks in the emp table, create a view as follows: CREATE VIEW clerk (id_number, person, department, position) AS SELECT empno, ename, deptno,job FROM emp WHERE job = 'CLERK' WITH CHECK OPTION;

The WITH CHECK OPTION specifies that inserts and updates performed through the view must result in rows that the view query can select. In this example any row other than the one having job='CLERK' cannot be inserted into the table.  Note: You cannot perform inserts, updates or deletes for a view if the view query co ntains: o  joins o set operators o group functions o GROUP BY clause o the DISTINCT operator

Indexes ?

? ?

?

The data in the tables are not sto red in any particular order of any column. Hence, when you access the table data, it is sequential access. This can pose a performance problem if the table is huge. You can use  Indexes to provide random access to data, there by enhancing perfor mance due to faster access to the data. Indexes are stored separately from the actual data. The index is made up of the co lumn on which you are indexing, and the physical address ( ROWID) of the row with that column value. Indexes are referred to whenever the indexed c olumns are referenced in the WHERE clause. o E.g., if the query SELECT ename, sal FROM emp WHERE ename = 'SMITH' is issued, and if there is an index on ename already, the index will be first searched to find the location of the row with specified ename value, and

?

?

then the row is fetched from the table. With every data manipulation, the appropriate indexes are automatically updated. o E.g., if there is an insert into the table, the corresponding indexes are also updated to reflect the new rows. Indexes are created using the CREATE INDEX DDL command: CREATE INDEX index_name ON table_name(column_name);

Example CREATE INDEX idx_ename ON emp(ename);

When you create an index: Oracle gets and sorts the columns to be indexed, ? Stores the ROWID along with the index value for each row , and ? Loads the index from the bottom up. ?  Note: ? Oracle, by default, creates indexes for columns defined as PRIMARY key or UNIQUE key, at the time of table creation . ? Internally, Oracle uses B*Trees to manage the indexes. Composite Indexes

A Composite index is one that is created on multiple columns in a table. as concatenated index.

It is also known

CREATE INDEX index_name ON table_name( col1, col2, col3);

Example CREATE INDEX ordcust ON orders(custcode,ordno)

Clusters ? ?

?

A Cluster is a group of tables that share the same data blocks, because they share the same columns and are often used together. If multiple tables are clustered together, they should have commo n column(s), called the cluster key. E.g., emp and dept tables can be clustered together based on the cluster key deptno that is common to both the tables. Advantages of using clusters: o Disk I/O is reduced and access time improves for joins of clustered ta bles. o Each cluster key is stored only once in the cluster and the cluster index, no matter how many rows of different tables contain the value.

Creating a Cluster ?

To create a cluster: o First create the cluster using the CREATE CLUSTER command

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF