Rakesh Chakrabarti

emailtorakesh@gmail.com

Oracle 10g (grid computing) SQL

Introduction:
Computaire -> to Compute/calculate Data Computer Information Large amount of Inter related Data – database DBMS: Database management System ANSI defn. of DBMS - Readymade s/w allows you to insert update delete and process Ms Excel dBASE foxbase Foxpro Clipper Database Dataflex Dataease Advance Revelation Quattro pro etc. Oracle RDMS relational +OODBMS Object Oriented= ORDBMS RDBMS examples: /Informix (fastest), Oracle (most popular 53% market share of world RDBMS market Client/Server environment / 74% market share of world RDBMS market internet environment Best s/w tools, mix programming is easy) /Sybase (NY Stock Exchange downwards), MS SQL server (upcoming Limitation Windows Domain) /Ingres, Progress (character based only on DOS and UNIX) /CICS, TELON, IDMS, IBM DB2 (Mainframe like ATM machine) /MS Access Vatcom SQL Paradox (PC based not for n/w) /MySQL (Sun Microsystems Weak RDBMS more than 2lakh records not in one table) etc.

DBMS Diff RDBMS 1. Nomenclature Field Column / Attribute Record Row / Tuple / Entity File table/relation/entity class
2. DBMS Relationship between two files maintained programmatically RDBMS Relationship between two tables maintained at the time of table creation 3. DBMS High network traffic RDBMS Low network traffic 4. DBMS processing at Client end RDBMS processing at Server end 5. DBMS Client Server architecture not supported RDBMS Most RDBMS support Client Server architecture

6. DBMS file level locking RDBMS row level locking [Oracle 10g automatic row level locking] New version of Oracle cell level locking 7. DBMS Distributed databases not supported RDBMS Most RDBMS support Distributed database [Largest Distributed databases in Oracle Yahoo! 20000 Oracle Linux Server in Silicon Valley and in Australia] 8. DBMS No Security RDBMS Multiple level of Security [Oracle Server Database crated in another Partition of HDD] Level: logging in [username/password] /command [DBA restriction on using Commands (134 command in Oracle 10g)] /object [Grant Permissions on Owner Object]

Oracle Tools/Oracle Products • SQL o Structured Query Language o Common to all database o Conforms to ANSI standards. And ISO standard o Initially by IBM 1978-79 Now controlled by ANSI o Sequel o Commands (12 commands)  Create drop alter  Insert update delete  Select  Grant revoke  Rollback commit savepoint • SQL*Plus/iSQL*Plus o Extension to SQL o To remove the limitations of SQL Commands (54 commands) o Character based Reporting tool (ERPs) o Oracle Client s/w o Interface with the database for running SQL and SQL*Plus commands • PL/SQL o Procedural language o Programming language of Oracle o 4 GL (as C++ supports OOPS Exception Error handlers Encapsulation) • Oracle Forms (Oracle Forms 10g) o Creating data entry screens • Oracle Reports (Oracle Reports 10g free of cost) o Creating reportsfont color web XML HTML/DHTML • Oracle Menus o Popup, full screen, toolbars, pull down, bar menu etc. • Oracle Graphics o Pie charts, bar graphics (TV channel share election sport rating)

Ids o Integrated Development Suite [forms+reports+menus+graphics] o Front end no I in market Exp (export utility used for taking Backups of table data) Imp (Import utility used for restoring from Backups of table data) Oraterm Sql*loader OEM Oracle Case Designer 2000 Pro*c Pro*c++ Pro*java Oracle Applications [] Oracle Financial (Oracle Financial 11i) o ERP enterprise wide Resource Planning S/W o readymade for financial applications [no 1 is SAP] o customization can be done as source code is all ready given Oracle Manufacturing (Oracle Manufacturing 11i) o ERP enterprise wide Resource Planning S/W o readymade for Manufacturing Industry (no I JD Edwards [taken by Oracle]) o customization can be done as source code is all ready given Oracle Hrms (Oracle HRMS 11i) o ERP enterprise wide Resource Planning S/W o readymade for HRD (no I Peoplesoft [taken by Oracle] ) o customization can be done as source code is all ready given Oracle Crm (Oracle CRM 11i) o ERP enterprise wide Resource Planning S/W o readymade for CRM no I Siebel systems [taken by Oracle]) o customization can be done as source code is all ready given

• • • • • • • • • • • •

SQL o o o o o o o Structured Query Language Standard Query Language Common to all database Conforms to ANSI standards. And ISO standard Initially by IBM 1978-79 Now controlled by ANSI Commands (12 commands) Execution is top to bottom left to right

DDL DML DCL DQL DTL

data data data data data

definition language [Create drop alter] manipulation language [Insert update delete] control language [Grant Revoke] query language [select] transactional language [Rollback commit savepoint]

Rules of table names/ column names: o Must be 1-30 characters long. Object names or Qualifier are case insensitive EMP or emp same

o o o o Data type: CHAR

Should not be an Oracle Server reserved word. Must contain only A-Z, a-z, 0-9, _, $, and #. [avoid $ and # can’t work in other RDBMS] Must begin with a letter/Alphabet (use descriptive name) Must not a duplicate name of another object owned by same user.

(ALLOWS ANY CHARACTER VALUE, 1-2000) TAKER Char instead of Varchar2 for better search Padded by spaces if all fields not inserted NUMBER (ALLOWS ANY NUMBER 1.0*10-130 T0 9.9*+125) If number(7,2) input 100.555 it assumes as rounding takes place as 100.56 DATE (1/1/10000 BC – 31/12/10000 AD) • [VALID DATE BETWEEN January 1, 4712 B.C. TO December 31, 9999 A.D.] • ARITHMETIC OF DATA IS POSSIBLE • Italian calendar Julian Date • British calendar Georgian Date (allowed date in oracle) • 5th Oct 1582 AD to 14th Oct 1582 AD not exist in oracle • Date and time stored together • DEFAULT DAY 01 MONTH (current month) century current AD time 00:00:00 • *year can’t be default VARCHAR (ALLOWS ANY CHARACTER VALUE, 1-4000) Older version of oracle 1 In 10g for VARCHAR backward compatibility VARCHAR2 (ALLOWS ANY CHARACTER VALUE, 1-4000) oracle 7 string comparison can done in VARCHAR2 as >=’A’ LONG 2 GB of character RAW 2000 bytes of binary data Multimedia barcodes small pictures signatures thumb impressions LONG RAW 2 GB of binary data photo music sound video Max 1000 columns per table Only 1 column either long or long raw in 1 table [Recommended 1 columned table with 1 long column] TABLE: EMP COLUMN: EMPNO CHAR (4) ENAME VARCHAR2 (25) SALARY NUMBER (7, 2) CITY varchar2(15) DOB date Create table EMP { EMPNO CHAR (4), ENAME VARCHAR2 (25), SALARY NUMBER (7, 2), CITY varchar2(15), DOB date }; 1. INSERT INTO EMP VALUES ( ‘1’, ‘Amit’, 5000, ‘Bombay’, ’10-JAN-1975’ ); *2. INSERT INTO EMP (EMPNO, ENAME, SALARY, CITY, DOB) VALUES(‘2’, ‘Ravi’, 5000, ‘Jack’, ’19-JAN-1975’); 3. INSERT INTO EMP (EMPNO, SALARY) VALUES(‘0’,15000);

4. INSERT INTO EMP VALUES(‘0’,’Rakesh’,null, null, null); * Recommended Null values same for “char varchar2 date number” Null value in middle takes 1 byte (in case char also 1 bytes) If ending columns have null then 0 bytes for that field Query Select * from emp * meta character [all columns] Login: Hoststring server ip or machine name Dbname Protocol Port no Where clause Oracle searches on the media like HDD then sends to Server RAM then sends to Client RAM Relational Operator as precednce 1. GREATER THAN > 2. GREATER THAN EQUAL TO >= 3. LESS THAN < 4. LESS THAN EQUAL TO <= 5. NOT EQUAL TO <> / ^= /! = 6. EQUAL TO = BETWEEN A AND B ONLY 2 VALUES mutually inclusive Not between A AND B ONLY 2 VALUES mutually exclusive IN (SET) LIST OF VALUES discrete LIKE A CHARACTER PATTERN IS NULL LOGICAL CONDITION 1. AND 2. OR 3. NOT PRECEDENCE OF OPERATOR 1. Arithmetic [ARTIHMETIC EXPRESSIONS/OPERATOR BY PRECEDENCE ( ) ** * / + -] () ** /*+- sql ** Exponentiation sal**3 sal**(1/3) 2. Concatenation 3. Comparison Cond. 4. Is [not] null, like, [not] in 5. [Not] between 6. NOT LOGICAL CONDITION 7. AND LOGICAL CONDITION 8. OR LOGICAL CONDITION Select Sal*12 from emp; // sal*12 Computed Table/virtual column/fake column Alias Select Sal*12 “ANNUAL” from emp; Select Sal*12 ANNUAL from emp; /faster than < = >

Make alias case sensitive as in “ ” or long character “ ” Distinct | unique Select unique|Distinct ename, job from emp; combination Order by clause desc Sorting select * from emp where ename >=’A’ and ename <’B’ Wildcards % DENOTES 0 OR MANY CHARACTER | _ DENOTES 1 CHARACTER [underscore] ‘\_P%’ ESCAPE ’\’ [HERE ESCAPE CHARACTER \ ] =any(10,20) ~ in faster <>all(10,20) ~ not in faster • • • • in any <any less than the maximum >any more than the maximum =any as IN all <all more than the maximum >all less than the maximum <>ALL as NOT IN not operator can be use with in any all

Update Delete delete from emp; ANSI delete emp; delete emp; Drop All DDLs are autocommit Commit rollback Transaction Control DML commands Savepoint (Commit/rollback/savepoint savepoint_name /rollback to savepoint_name) Exit; command in SQL*Plus then it automatically commit All pending transactions Any other case improper exit power failure n/w failure Creating second savepoint earlier savepoint is deleted Creating second savepoint earlier savepoint is in the memory. Savepoint sequentially first s2 then s1; CREATE table new_emp ( employee_id NUMBER, name VARCHAR2(30)); INSERT INTO new_emp SELECT employee_id , last_name from employees; Savepoint s1; UPDATE new_emp set name = UPPER(name); Savepoint s2; update new_emp set name = lower(name) where employee_id =180; Rollback to s2; Delete from new_emp where employee_id =180; Rollback to s1; Query in table view committed data of all users and uncommitted data of your transactions Whether the other users view only committed data of all users in database Delete command Marked for deletion Locks: • Prevent destructive interaction between concurrent transactions • Require no user action Record locking in Oracle is Automatic • only in update or delete • Other user only view those data • Held when transaction in progress locks only user modified data

• •

To avoid a wait lock the record manually.(Pessimistic Locking) Explicit locking User puts manual lock o Select * from table_name [where clause] for update [nowait/wait timeN]; o Select * from emp for update wait 60; o Provide rollback or commit to unlock

Select * from tab; tab [system table/data dictionary/database catalog] 352 system table in Oracle 10g in 9i 326 SQL*Plus command password[pass][;] describe [desc] tab_name [;] SQL Buffer temporary text file EXECUTE / Run[r] (list and execute) afiedt abbreviation of list[l] what is in the buffer SQL> 1 2* SQL> 2* SQL> SQL> 1 2* SQL> 1* SQL> SQL> 1 2* SQL> 1* SQL> SQL> 1 2 3* SQL> 2 SQL> SQL> 1 2* L SELECT * FROM EMP; * buffer emp L2 FROM EMP; C/ EMP/DEPT C CHANGE L SELECT ENAME FROM EMP; * buffer emp L1 SELECT ENAME A ,SAL A APPEND L SELECT ENAME, SAL FROM EMP; L1 SELECT ENAME,SAL I ,DEPTNO I insert L SELECT ENAME, SAL ,deptno FROM EMP; L2 ,deptno DEL del delete L SELECT ENAME, SAL FROM EMP; Change password /bin/afiedt.buf last SQL command 6 people founded Oracle Corp. list the buffer contents

Save the buffer as file

SQL> save \path\]file_name[.extn] SQL> save [\path \]file_name[.extn] replace //default location is /bin/file_name.sql //default extension .sql To Run the saved file SQL>@[\filepath\]filename[.extn] Saved file Load in the buffer SQL> get [\ path \]file_name[.extn] SQL> Define_editor = [notepad/textpad/wordpad/vi/edit.com] System editor for Oracle in windows notepad in unix vi for user_session only To make changes permanent modify the startup file for SQL*Plus C:\oracle\product\10.2.0\client_1\sqlplus\admin\glogin.sql --- Copyright (c) 1988, 2004, Oracle Corporation. All Rights Reserved. --- NAME -- glogin.sql --- DESCRIPTION -- SQL*Plus global login "site profile" file --- Add any SQL*Plus commands here that are to be executed when a -- user starts SQL*Plus, or uses the SQL*Plus CONNECT command --- USAGE -- This script is automatically run --- Used by Trusted Oracle COLUMN ROWLABEL FORMAT A15 -- Used for the SHOW ERRORS command COLUMN LINE/COL FORMAT A8 COLUMN ERROR FORMAT A65 WORD_WRAPPED -- Used for the SHOW SGA command COLUMN name_col_plus_show_sga FORMAT a24 COLUMN units_col_plus_show_sga FORMAT a15 -- Defaults for SHOW PARAMETERS COLUMN name_col_plus_show_param FORMAT a36 HEADING NAME COLUMN value_col_plus_show_param FORMAT a30 HEADING VALUE -- Defaults for SHOW RECYCLEBIN COLUMN origname_plus_show_recyc FORMAT a16 HEADING 'ORIGINAL NAME' COLUMN objectname_plus_show_recyc FORMAT a30 HEADING 'RECYCLEBIN NAME' COLUMN objtype_plus_show_recyc FORMAT a12 HEADING 'OBJECT TYPE' COLUMN droptime_plus_show_recyc FORMAT a19 HEADING 'DROP TIME' -- Defaults for SET AUTOTRACE EXPLAIN report -- These column definitions are only used when SQL*Plus -- is connected to Oracle 9.2 or earlier. COLUMN id_plus_exp FORMAT 990 HEADING i COLUMN parent_id_plus_exp FORMAT 990 HEADING p COLUMN plan_plus_exp FORMAT a60 COLUMN object_node_plus_exp FORMAT a8 COLUMN other_tag_plus_exp FORMAT a29 COLUMN other_plus_exp FORMAT a44 -- Default for XQUERY COLUMN result_plus_xquery HEADING 'Result Sequence' -- MODIFY HERE Define_editor = notepad

-- Copyright (c) 1988, 2004, Oracle Corporation. All Rights Reserved. ************************************ Edit [ed] [\path \]file_name[.extn] afiedt.buf set set set set [afiedt.buf]

only one SQL command don’t delete / don’t put ; max 50000 max 50000

feedback off/on pagesize [14] linesize [80] verify on/off

Substitution variables: &v_name pre processor before compilation ‘&v_name’ &v_name = CLERK|&v_name = ‘CLERK’ && Accept v_name datatype prompt ‘text’ Accept v_name number [prompt ‘Please give a deptno:’] Prompt text Prompt Welcome Define/undefined v_name [= 10] Select * from emp where deptno = &v_name; Set sqlprompt ‘iflex>’ Multiple lines give a hyphen in SQL plus SQL> desc – > emp iSQL*Plus http://trainer:5560/isqlplus/ Help index Help [topic] @ @@ / ACCEPT APPEND ARCHIVE LOG ATTRIBUTE BREAK BTITLE CHANGE CLEAR COLUMN COMPUTE CONNECT SQL functions Single row functions Char functions Concatenation operator || fname||lname Concat(fname,lname) only 2 parameter Nested function 255 func. In Oracle 9i but in 10g no limit Upper (1 parameter) case-insensitive query v_name session variable

COPY DEFINE DEL DESCRIBE DISCONNECT EDIT EXECUTE EXIT GET HELP HOST INPUT LIST PASSWORD

PAUSE SHUTDOWN PRINT SPOOL PROMPT SQLPLUS QUIT START RECOVER STARTUP REMARK STORE REPFOOTER TIMING REPHEADER TTITLE RESERVED WORDS (SQL) UNDEFINE RESERVED WORDS (PL/SQL) VARIABLE RUN WHENEVER OSERROR SAVE WHENEVER SQLERROR SET SHOW

Lower (1 parameter) Initcap(1 parameter) 1st letter converted Upper else Lower for every word Initcap(Arun pal)  Arun Pal Lpad(parameter, length, ‘char’) overloading OOP concept Rpad(parameter, length, ‘char’) Ltrim(parameter, length, ‘char’) Ltrim(ename, ‘*$%&’) Rtrim(parameter, length, ‘char’) Rtrim(ename, ‘*$%&’) Substring(parameter, ±start_pos) start_pos to end Substring(parameter, ±start_pos, 2) start_pos to 2 more char-> total 2 Substring(parameter, -3) start 3rd last position Substring(parameter, -3,2) start 3rd last position to 2 more char-> total 2 Replace (parameter, old_str, new_str) Replace (parameter, old_str) all old_str is removed Translate(ename,’un’, ’xy’) character by character u=x n=y same length Translate(ename,’un’, ’x’) u=x n is removed Instr(parameter, srch_str) return type is number in first occur_pos Instr(parameter, srch_str, ±start_pos) begin start from start_pos Instr(parameter, srch_str, ±start_pos,occur) Instr(ename, ‘ab’ ,4, 2) found ab from 4th pos and 2nd occurrence Length(parameter) return type is number Ascii(parameter) ascii value of 1st char Chr(number) number 0-255 Soundex(parameter) remove the vowel then check European Accent Select * from emp where Sounder(‘Arun’) = Soundex(‘Aroon’) Parameter = String/Column_name Dual System Dummy table datatype char(1) Number Functions ROUND(number) float to integer ROUND(number, ±n) n’th digit after decimal point 1291,-2 1300 TRUNC(number) cuts 0ff decimal parts TRUNC(number, ±n) cuts 0ff decimal parts/REPLACE with 0s 1291,-2 1200 ceil(number) adds one if has any decimal value interest calc. floor(number) cuts 0ff decimal parts positive number no difference between trunc and floor trunk(2.3) 2 floor(2.3) 2 negative number difference between trunc and floor trunk(-2.3) -2 floor(-2.3) -3 sign(±number) return if +ve ans: +1 -ve ans: -1 0 ans: 0 sign(x-y) +1 x>y -1 x<y 0 x=y MOD(number/divider) remainder Sqrt(+number) Power(number, exponential) as ** Abs(±number) Absolute value Sin(x) Sin(x) cos(x) cosh(x) tan(x) tanh(x) x in radian ln(x) log(x,y) Date Functions: Sysdate RETURNS CURRENT DATABASE SERVER DATE AND TIME INTERNAL NUMERIC FORMAT 7 BYTES CENTURY YEAR MONTH DAY HOURS MINUTES SECONDS VALID DATE BETWEEN January 1,4712 B.C. TO December 31,9999 A.D. DEFAULT DATE FORMAT DD-MON-RR 01-JUL-06

DATE± NUMBER = DATE DATE - DATE = DAYS DATE±NUMBER/24 = DATE MONTHS_BETWEEN (DATE, DATE) calendar months *Decimal part balance days hours minutes seconds ADD_MONTHS (DATE, ± number) decimal part balance days hours minutes seconds Adding/Reducing 2 months as by calendar NEXT_DAY (DATE, DAY)here Day= Monday,….Sunday o/p in Oracle Date format LAST_DAY (DATE) o/p last DAY of month in Oracle Date format DD-MON-RR ROUND TRUNC DATE FORMAT MODEL TO_CHAR(DATE,’FORMAT MODEL’) ’FORMAT MODEL . GERMAN SEPARATOR AMERICAN SEPARATOR / BRITISH SEPARATOR : FRENCH SEPARATOR * ITALIAN SEPARATOR upper lower initcap J JSP JTH JSPTH TO_DATE(TO_CHAR(2000,’J’),’JSP’) DY DAY D DSP DTH DSPTH [DAY OF WEEK SUNDAY = 1] DD DDSP DDSPTH DDTH DDD DDDSP DDDTH DDDSPTH W WSP WTH WSPTH (1-5 WEAK OF MONTH) WW WWSP WWTH WWSPTH (1-52 WEAK OF YEAR) MM MMSP MMTH MMSPTH MON MONTH Y YY YYY YYYY YEAR TO_CHAR(2000,’year’) TIME FORMATS: AM/PM A.M./P.M. HH HH24 MI SS ENVIRONMENT FUNCTION: (Used to maintain logs of user actions) SELECT USER, UID FROM DUAL; SELECT USERENV (‘TERMINAL’), USERENV (‘SESSIONID’) FROM DUAL; In standard use USER, USERENV (‘TERMINAL’) in insert statement. CONNECT / DISCONNECT List function (independent of data type) Search for null pessimistic query = null if Null comparison true then returns null Treatment is [not] null used instead of [!]= null Any arithmetic operation with null returns null Treatment: (for all datatypes) a. NVL(EX1,EX2) EX1 NULL PUT/RETURN EX2 Greatest (ex1… ex255) LEAST(ex1… ex255) any data type Select Greatest (sal, 3000) from emp; return greater of 3000 and =3000

Select Least (sal, 3000) from emp;

return lesser of 3000 and =3000

DECODE (COL/EXP, SEARCH1, RESULT1, SEARCH2,RESULT2, [DEFAULT_RESULT]) If DEFAULT_RESULT not specified then null is returned. Select decode (sign (sal-5000), 1,’H’,-1,’L’, 0,’M’) FROM EMP;

Multi row functions Group/Aggregate function Sum(column) Avg(column) Min(column) max (column) count(sal) count(*) stddev (column) variance (column) select Aggregate_func (sal) from emp where deptno = 1; used to retrieve the rows from server disk to server ram

Limitations of SQL in Aggregate_func : Cant use in where clause Select * from emp where sal> avg(sal) not done Select * from emp where sal> (Select avg(sal) from emp ); solution solve in SQL*Plus Select Single_row_func (column), Aggregate_func (column) from table_name; not done Select column, Aggregate_func (column) from table_name; not done Select column, Aggregate_func (column) from table_name group by column; solution solve in SQL*Plus 1. Only selected column  rows are retrieved from derver hdd to server ram 2. Sorting column wise which specified in group by clause 3. Grouping be done column wise 4. Compute the operation using loop 5. having work as a filter 6. Sorting used in at last in select statement using order by Group by Rules *Whichever Column is in select statement must be in group by * Whichever Column is in group by Clause need not be present in select statement *where clause can come before group by *sequence of columns in group by affects speed of processing *Specify condition on group by output use having [strictly in group by] *sorted o/p use order by after group by Group function can be used in having clause without using select statement • Select • Where

• • •

Group by Having Order by

Nested group functions Max(sum(sal)) allowed for Oracle SQL not in ANSI SQL Matrix report Select deptno, count(*), sum(sal), max(sal), min(sal), avg(nvl(sal,0)) from emp group by deptno; SQL Joins Cartesian product Join condtn omitted/invalid All rows in 1st table joined to all rows in 2nd table Guidelines: Always use table_name.column_name for better output. Select dept.deptno,dname,ename from emp, dept where dept.deptno=emp. .deptno; Driven table emp more no. of rows Driving table dept lesser no. of rows [recommended] sequence of columns in from affects speed of processing in join condtn. Type of joins Equijoin simple join /inner join based on primary keys and foreign keys You can join n tables (all having single column primary keys) in a SQL statement by specifying a minimum of n-1 join conditions Use = for Non-equijoin Frequently used for 90% Non-Equijoin don’t use = between is simplest process for non-equijoin Use != for Non-equijoin Frequently not used Outer Join (+) placed on the side of the join that is deficient/missing in information in/or operator prohibited as Inner join do-while loop use Use (+) sign next to child table or where the foreign key is used • FULL OUTER JOIN TO VIEW all unmatched data from both tables. • Arbitary join condtn. On outer join And expression • Outer join can appear only one side of the expression • In OUTER JOIN Cannot use IN operator/cannot be linked with OR operator • You cannot link a condition that is involved in an outer join to another condition by using the OR operator. Self Join Open twice table in Ram and Join table to it. It is slow. Based on recursion try to avoid *If common column define qualifying ambiguous column names with table aliases upto 30 char Sql 1999 ANSI SQL Join EQUIVALANCE ORACLE SQL Cross Cartesian product Natural common column (same name and datatype) used ON clause Join on (col name) Equijoin Using clause Left/Right/Full outer join join using Left outer join Non-equijoin /In-equijoin Outer join

Sub Query A single row subquery can retrieve only one row but many columns. A single row subquery can retrieve data from more than one table. A multiple row subquery can retrieve multiple rows and multiple columns. A multiple row subquery can be compared by using the “>” operator (only case of all/any). The multiple-row subquery cannot be used with the comparison operator A multiple-row subquery cannot be used in an INSERT statement to insert multiple rows at a time. Subquery Retrieve data based on an unknown condition Multiple row • Subquery or inner query includes Where / Having/ From / Operator • Subquery in parenthesis ( ) • No limit in levels in 10g ( 9i upto 255 level) • RHS of comparison condition. • If Top-N analysis then order by needed otherwise not • Single row operator with Single row Subquery (return one row) • Multiple row operator with Multiple row Subquery (return multiple rows) • Executes sub queries first • Common Error: More than one row returned for a single row subquery Single row operator with Multiple row sub query Use IN/NOT IN instead of =, LIKE, BETWEEN, IS, <> [can’t use] • *Comparison of two null values yields a null then where condtn. Is not true • in • any <any less than the maximum >any more than the maximum =any as IN • all <all more than the maximum >all less than the maximum <>ALL as NOT IN • not operator can be use with in any all

Select * from emp Where sal =any (Select sal from emp where job = ‘M’); Select * from emp Where sal IN (Select sal from emp where job = ‘M’); Select * from emp Where sal>= (Select min(sal) from emp where job = ‘M’); Select * from emp Where sal > all

slower

faster

fastest

(Select sal from emp where job = ‘M’); Select * from emp Where sal > (Select max(sal) from emp where job = ‘M’);

slower

fastest

SET Operator Union combine o/p of both tables and suppress the duplicates in same structured select statement and same data types column name in o/p from 1st select statement Union all combine o/p of both tables and not suppress the duplicates Intersect common o/p of both tables and suppress the duplicates Minus first table contents which not present in second suppress the duplicates pseudo column Programmer created computed field expression function column System created Rownum Rowid

in respect to Table it using but rowid is the address of the row

Spool Spool filename Spool abc Spool off Ed abc.lst ALTER: DDL command Direct effect: Rename a table RENAME OLD_TABLE_NAME TO NEW_TABLE_NAME; Add a column alter ALTER TABLE EMP ADD COLUMN_NAME DATATYPE (n); Drop a column ALTER TABLE EMP DROP COLUMN COLUMN_NAME; Increase the width of a column ALTER TABLE EMP DROP MODIFY COLUMN_NAME DATATYPE (n); Indirect effect: Decrease the width of a column Set the column contents to null Decrease the width of a column Add another column x UPDATE EMP SET X = ENAME, ENAME = NULL; Decrease the width of a column UPDATE EMP SET ENAME=X;

Change a data type Set the column contents to null ALTER TABLE EMP MODIFY COLUMN_NAME DATATYPE (n); Copy a table CREATE TABLE N_TABLE_NAME AS SELECT * FROM O_TABLE_NAME; Structure of n_table_name are created based on select statement. then data cpoied to n_table_name from o_table_name Copy a structure of table Create table n_table_name as select * from o_table_name; where 2=1; -- abnormal condition Change sequence of columns Create table n_table_name as select empno, sal, ename from o_table_name; Drop o_table_name Rename n_table_name to o_table_name Rename column Create table n_table_name as select empno, sal SALARY, ename from o_table_name; Drop o_table_name Rename n_table_name to o_table_name Alter table table_name RENAME column O_COLUMN_NAME TO N_COLUMN_NAME; Alter table spj rename Column qty to qtty; Indexes: Speed up the search operation /faster access/ Improve performance of some queries (SELECT) Index contain table_column in ascending order and corresponding row id Null values are not stored in index Composite index two or more columns index key (column or set of column on based which index is created ) First column of index Primary index Second column of index Secondary index CREATE INDEX index_name ON table_name (column_name1,…, column_nameN [desc]); CREATE INDEX index_name ON table_name UPPER(column_name1); //case-insensitive search User_ind_columns user_indexes More than 1 index on same single column not allowed CREATE Unique index index_name ON table_name (column_name); DROP INDEX index_name; //to remove index definition from data dictionary ------------------------------------------------------------------------------------

Constraints • Oracle server uses constraints to prevent invalid data entry into tables. • Constraints must be satisfied for the operation to succeed. • Enforce rules at table and view level. (Row insertion, deletion, updating). • To prevent DELETION OF A TABLE if there are dependencies. • Provide rules for Oracle Tools (e.g. Oracle Developer). • Constraints stored in data dictionary (USER_CONSTRAINTS). • Provide a meaningful name follow standard object-naming rules. • If not specify name Oracle server generates a name as SYS_Cn [n is integer to make the name unique] • Create a constraint at the same time or after of table creation. • Define a Constraint in table or column level. • Create table schema.table_name (column_name data type(size) [default expr] [column_constraint], …,[table_constraint]); • column_constraint level: reference a single column defined within a specification for owning column, define any type of integrity constraint. column [constraint constraint_name] constraint_type e.g. create table t1(Emp_id number(6) constraint emp_id_uk unique, ename char(10) not null); here constraint for Emp_id is user named & constraint for ename system named table_constraint level: reference one or more columns defined separately from definitions of column, any type of integrity constraint except NOT NULL. [constraint constraint_name] constraint_type (column_name) e.g. create table t1(Emp_id number(6), ename char(10) not null, constraint emp_id_uk unique(Emp_id)); • NOT NULL can be specified only in column level not in table level • UNIQUE every value in a column must be unique • Single column (set of columns) uses this constraint is called unique key if two or more column comprises this groups of columns is called composite unique key. • UNIQUE can be specified in column or table level. Composite unique key specified table level • Unique Constraints allow the input of nulls because nulls are not considered equal to anything. So user also defines NOT NULL to prevent null acceptance • Oracle server enforces UNIQUE constraints by implicitly creating a unique index on the unique key column or columns. • Primary key constraint is a column or sets of columns, only one primary key is defined. • Enforce uniqueness for column or column combination but don’t accept null values. • Primary key can be specified in column or table level. Composite Primary key specified table level • Table contains only one primary key constraint but several unique constraints. • A UNIQUE index is automatically created for a Primary key column. • Foreign Key referential integrity designates a column or combination of columns & establishes a relationship between a primary key or a unique key in same or different table. • Foreign Key must match an existing value in the parent table or be NULL. • Foreign Key are based on data values and are purely logical, not physical, pointers. • Foreign key can be specified in column or table level. Composite Foreign key specified table level

• create table t1(Emp_id number(6) constraint emp_id_fk references dept (Emp_id)); • create table t1(Emp_id number(6), constraint emp_id_fk Foreign key (Emp_id) references dept (Emp_id)); • FOREIGN KEY: Defines the column in the child table at the table constraint level • REFERENCES: Identifies the table and column in the parent table • ON DELETE CASCADE: deletes the dependent rows in the child table when a row in parent table is deleted • ON DELETE SET NULL: converts dependent foreign key values to null when parent table is deleted • Default behavior of Foreign Key is called Restrict rule. • CHECK is a condition that each row must satisfy (both column or table level) • References to CURRVAL, NEXTVAL, LEVEL, ROWNUM pseudocolumns • Calls to SYSDATE, UID, USER AND USERENV functions • Queries that refer to other values in other rows • Single column can have multiple CHECK Constraints which refer to the column in its definition. • No limit to the no. of CHECK Constraints which user can define on a column. • salary number(8) check (salary>0) | city varchar2(10), constraint emp_city_ck check (city in (‘Kol’,’Delhi’,’Mumbai’)) • Add or Drop a constraint but can’t modify its structure • ALTER TABLE ADD constraint constraint_name constraint_type (COLUMN_NAME[s]); • ALTER TABLE EMP ADD CONSTRAINT EMP_MANAGER_FK FOREIGN KEY (MGRID) REFERENCES EMP(EMPID); • If user doesn’t specify constraint_name system itself generate a name. • Change existing column to not null constraint if the table is empty or column has value for every row. • Add a NOT NULL constraint only by using MODIFY clause of ALTER TABLE statement • ALTER TABLE T1 MODIFY NAME CONSTRAINT NAME_NN NOT NULL; • ALTER TABLE TABLE_NAME DROP CONSTRAINT constraint_name • CASCADE option used to drop dependent constraints (referential integrity to PK or UK). • CASCADE CONSTRAINTS used along DROP COLUMN clause/to drop multicolumn constraints. • ALTER TABLE TABLE_NAME DROP primary key|unique(column)| CONSTRAINT constraint_name [cascade]; • ALTER TABLE TABLE_NAME DROP (column_name) CASCADE CONSTRAINTS; • After dropping a constraint it no longer available by Oracle server data dictionary • DISABLE Clause to deactivate an integrity constraint/ apply cascade to disable dependent constraint • Alter table table_name disable constraint constraint_name cascade; • Disabling a unique or primary key constraint removes the unique index • Enable Clause to activate an integrity constraint used both in CREATE TABLE or ALTER TABLE statement • After enabling constraint, data must fit to it otherwise report error. • Enabling a unique or primary key constraint create the unique index • Enabling a primary key constraint disabled with CASCADE option does not enable foreign keys dependent on this primary key. • Data dictionary views to view constraints for user given or system-assigned name • Select CONSTRAINT_name, CONSTRAINT_type, search_condition from USER_CONSTRAINTS; o Here C CHECK, P PRIMARY KEY, RREFERENTIAL INTEGRITY, UUNIQUE KEY o NOT NULL also CHECK type CONSTRAINT. • Select CONSTRAINT_name, column_name from USER_CONS_COLUMNS;

select dept.*, a.tot from dept,(select emp.deptno, sum(emp.empno) tot from emp group by emp.deptno --having emp.deptno = 10)a where dept.deptno = a.deptno

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.