100% found this document useful (1 vote)
2K views22 pages

Oracle Programming - SQL Cheatsheet

This document provides a summary of Oracle SQL and PL/SQL functions in the form of a cheat sheet. It covers basic queries, DDL statements, string functions, and PL/SQL concepts. The resource is intended to serve as a quick reference for both new and experienced Oracle developers and database administrators. Sections include descriptions of common commands like SELECT, INSERT, UPDATE and DELETE as well as programming concepts such as sequences, stored procedures, and string manipulation functions.

Uploaded by

RahulRoy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
2K views22 pages

Oracle Programming - SQL Cheatsheet

This document provides a summary of Oracle SQL and PL/SQL functions in the form of a cheat sheet. It covers basic queries, DDL statements, string functions, and PL/SQL concepts. The resource is intended to serve as a quick reference for both new and experienced Oracle developers and database administrators. Sections include descriptions of common commands like SELECT, INSERT, UPDATE and DELETE as well as programming concepts such as sequences, stored procedures, and string manipulation functions.

Uploaded by

RahulRoy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

OracleProgramming/SQLCheatsheet

This"cheatsheet"coversmostofthebasicfunctionalitythatanOracleDBAneedstorunbasicqueries
andperformbasictasks.ItalsocontainsinformationthataPL/SQLprogrammerfrequentlyusestowrite
storedprocedures.TheresourceisusefulasaprimerforindividualswhoarenewtoOracle,orasa
referenceforthosewhoareexperiencedatusingOracle.
AgreatdealofinformationaboutOracleexiststhroughoutthenet.Wedevelopedthisresourcetomakeit
easierforprogrammersandDBAstofindmostofthebasicsinoneplace.Topicsbeyondthescopeofa
"cheatsheet"generallyprovidealinktofurtherresearch.
OtherOracleReferences
OracleXMLReferencetheXMLreferenceisstillinitsinfancy,butiscomingalongnicely.
Contents
1SELECT
2SELECTINTO
3INSERT
4DELETE
5UPDATE
5.1Settingconstraintsonatable
5.2Uniqueindexonatable
6SEQUENCES
6.1CREATESEQUENCE
6.2ALTERSEQUENCE
7Generatequeryfromastring
8Stringoperations
8.1Length
8.2Instr
8.3Replace
8.4Substr
8.5Trim
9DDLSQL
9.1Tables
9.1.1Createtable
9.1.2Addcolumn
9.1.3Modifycolumn
9.1.4Dropcolumn
9.1.5Constraints
9.1.5.1Constrainttypesandcodes
9.1.5.2Displayingconstraints
9.1.5.3Selectingreferentialconstraints
9.1.5.4Creatinguniqueconstraints
9.1.5.5Deletingconstraints
9.2INDEXES
9.2.1Createanindex
9.2.2Createafunctionbasedindex
9.2.3RenameanIndex
9.2.4Collectstatisticsonanindex
9.2.5Dropanindex
10DBARelated
10.1UserManagement
10.1.1Creatingauser
10.1.2Grantingprivileges
10.1.3Changepassword
10.2Importingandexporting
10.2.1ImportadumpfileusingIMP
11PL/SQL
11.1Operators
11.1.1Arithmeticoperators
11.1.1.1Examples
11.1.2Comparisonoperators
11.1.2.1Examples
11.1.3Stringoperators
11.1.4Dateoperators
11.2Types
11.2.1BasicPL/SQLTypes
11.2.2%TYPEanchoredtypevariabledeclaration
11.2.3Collections
11.3Storedlogic
11.3.1Functions
11.3.2Procedures
11.3.3anonymousblock
11.3.4Passingparameterstostoredlogic
11.3.4.1Positionalnotation
11.3.4.2Namednotation
11.3.4.3Mixednotation
11.3.5Tablefunctions
11.4Flowcontrol
11.4.1ConditionalOperators
11.4.2Example
11.4.3If/then/else
11.5Arrays
11.5.1Associativearrays
11.5.2Example
12APEX
12.1Stringsubstitution
13Externallinks
14MoreWikibooks
SELECT
TheSELECTstatementisusedtoretrieverowsselectedfromoneormoretables,objecttables,views,
objectviews,ormaterializedviews.
SELECT *
FROM beverages
WHERE field1 = 'Kona'
AND field2 = 'coffee'
AND field3 = 122;
SELECTINTO
Selectintotakesthevaluesname,addressandphonenumberoutofthetableemployee,andplacesthem
intothevariablesv_employee_name,v_employee_address,andv_employee_phone_number.
Thisonlyworksifthequerymatchesasingleitem.Ifthequeryreturnsnorowsitraisesthe
NO_DATA_FOUNDbuiltinexception.Ifyourqueryreturnsmorethanonerow,Oracleraisesthe
exceptionTOO_MANY_ROWS.
SELECT name,address,phone_number
INTO v_employee_name,v_employee_address,v_employee_phone_number
FROM employee
WHERE employee_id = 6;
INSERT
TheINSERTstatementaddsoneormorenewrowsofdatatoadatabasetable.
insertusingtheVALUESkeyword
INSERT INTO table_name VALUES (' Value1', 'Value2', ... );
INSERT INTO table_name( Column1, Column2, ... ) VALUES ( 'Value1', 'Value2', ... );
insertusingaSELECTstatement
INSERT INTO table_name( SELECT Value1, Value2, ... from table_name );
INSERT INTO table_name( Column1, Column2, ... ) ( SELECT Value1, Value2, ... from table_name );
DELETE
TheDELETEstatementisusedtodeleterowsinatable.
deletesrowsthatmatchthecriteria
DELETE FROM table_name WHERE some_column=some_value
DELETE FROM customer WHERE sold = 0;
UPDATE
TheUPDATEstatementisusedtoudpaterowsinatable.
updatestheentirecolumnofthattable
UPDATE customer SET state='CA';
updatesthespecificrecordofthetableeg:
UPDATE customer SET name='Joe' WHERE customer_id=10;
updatesthecolumninvoiceaspaidwhenpaidcolumnhasmorethanzero.
UPDATE movies SET invoice='paid' WHERE paid > 0;
Settingconstraintsonatable
ThesyntaxforcreatingacheckconstraintusingaCREATETABLEstatementis:
CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE]
);
Forexample:
CREATE TABLE suppliers
(
supplier_id numeric(4),
supplier_name varchar2(50),
CONSTRAINT check_supplier_id
CHECK (supplier_id BETWEEN 100 and 9999)
);
Uniqueindexonatable
ThesyntaxforcreatingauniqueconstraintusingaCREATETABLEstatementis:
CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT constraint_name UNIQUE (column1, column2, column_n)
);
Forexample:
CREATE TABLE customer
(
id integer not null,
name varchar2(20),
CONSTRAINT customer_id_constraint UNIQUE (id)
);
ExampleCREATETABLEOOP(IDNUMBER(20),NAMEVARCHAR2(20))
TABLECREATED
SQL>ALTERTABLEOPPADDCONSTRAINTOPP_ID_UKUNIQUE(ID)
'TABLEALTERED'
SEQUENCES
Sequencesaredatabaseobjectsthatmultipleuserscanusetogenerateuniqueintegers.Thesequence
generatorgeneratessequentialnumbers,whichcanhelpautomaticallygenerateuniqueprimarykeys,and
coordinatekeysacrossmultiplerowsortables.
CREATESEQUENCE
Thesyntaxforasequenceis:
CREATE SEQUENCE sequence_name
MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;
Forexample:
CREATE SEQUENCE supplier_seq
MINVALUE 1
MAXVALUE 999999999999999999999999999
START WITH 1
INCREMENT BY 1
CACHE 20;
ALTERSEQUENCE
Incrementasequencebyacertainamount:
ALTER SEQUENCE <sequence_name> INCREMENT BY <integer>;
ALTER SEQUENCE seq_inc_by_ten INCREMENT BY 10;
Changethemaximumvalueofasequence:
ALTER SEQUENCE <sequence_name> MAXVALUE <integer>;
ALTER SEQUENCE seq_maxval MAXVALUE 10;
Setthesequencetocycleornotcycle:
ALTER SEQUENCE <sequence_name> <CYCLE | NOCYCLE>;
ALTER SEQUENCE seq_cycle NOCYCLE;
Configurethesequencetocacheavalue:
ALTER SEQUENCE <sequence_name> CACHE <integer> | NOCACHE;
ALTER SEQUENCE seq_cache NOCACHE;
Setwhetherornottoreturnthevaluesinorder
ALTER SEQUENCE <sequence_name> <ORDER | NOORDER>;
ALTER SEQUENCE seq_order NOORDER;
LTERSEQUENCEseq_order
Generatequeryfromastring
Itissometimesnecessarytocreateaqueryfromastring.Thatis,iftheprogrammerwantstocreateaquery
atruntime(generateanOraclequeryonthefly),basedonaparticularsetofcircumstances,etc.
Careshouldbetakennottoinsertusersupplieddatadirectlyintoadynamicquerystring,withoutfirst
vettingthedataverystrictlyforSQLescapecharactersotherwiseyourunasignificantriskofenabling
datainjectionhacksonyourcode.
Hereisaverysimpleexampleofhowadynamicqueryisdone.Thereare,ofcourse,manydifferentways
todothisthisisjustanexampleofthefunctionality.
PROCEDURE oracle_runtime_query_pcd IS
TYPE ref_cursor IS REF CURSOR;
l_cursor ref_cursor;
v_query varchar2(5000);
v_name varchar2(64);
BEGIN
v_query := 'SELECT name FROM employee WHERE employee_id=5';
OPEN l_cursor FOR v_query;
LOOP
FETCH l_cursor INTO v_name;
EXIT WHEN l_cursor%NOTFOUND;
END LOOP;
CLOSE l_cursor;
END;
Stringoperations
Length
Lengthreturnsanintegerrepresentingthelengthofagivenstring.Itcanbereferredtoas:lengthb,
lengthc,length2,andlength4.
length( string1 );
SELECT length('hello world') FROM dual;
this returns 11, since the argument is made up of 11 characters including the space
SELECT lengthb('hello world') FROM dual;
SELECT lengthc('hello world') FROM dual;
SELECT length2('hello world') FROM dual;
SELECT length4('hello world') FROM dual;
these also return 11, since the functions called are equivalent
Instr
Instrreturnsanintegerthatspecifiesthelocationofasubstringwithinastring.Theprogrammercan
specifywhichappearanceofthestringtheywanttodetect,aswellasastartingposition.Anunsuccessful
searchreturns0.
instr( string1, string2, [ start_position ], [ nth_appearance ] )
instr( 'oracle pl/sql cheatsheet', '/');
this returns 10, since the first occurrence of "/" is the tenth character
instr( 'oracle pl/sql cheatsheet', 'e', 1, 2);
this returns 17, since the second occurrence of "e" is the seventeenth character
instr( 'oracle pl/sql cheatsheet', '/', 12, 1);
this returns 0, since the first occurrence of "/" is before the starting point, which is the 12th character
Replace
Replacelooksthroughastring,replacingonestringwithanother.Ifnootherstringisspecified,itremoves
thestringspecifiedinthereplacementstringparameter.
replace( string1, string_to_replace, [ replacement_string ] );
replace('i am here','am','am not');
this returns "i am not here"
Substr
Substrreturnsaportionofthegivenstring.The"start_position"is1based,not0based.If"start_position"
isnegative,substrcountsfromtheendofthestring.If"length"isnotgiven,substrdefaultstothe
remaininglengthofthestring.
substr(string,start_position[,length])
SELECT substr( 'oracle pl/sql cheatsheet', 8, 6) FROM dual;
returns"pl/sql"sincethe"p"in"pl/sql"isinthe8thpositioninthestring(countingfrom1atthe
"o"in"oracle")

SELECT substr( 'oracle pl/sql cheatsheet', 15) FROM dual;
returns"cheatsheet"since"c"isinthe15thpositioninthestringand"t"isthelastcharacterinthe
string.
SELECT substr('oracle pl/sql cheatsheet', -10, 5) FROM dual;
returns"cheat"since"c"isthe10thcharacterinthestring,countingfromtheendofthestringwith
"t"asposition1.
Trim
Thesefunctionscanbeusedtofilterunwantedcharactersfromstrings.Bydefaulttheyremovespaces,but
acharactersetcanbespecifiedforremovalaswell.
trim ( [ leading | trailing | both ] [ trim-char ] from string-to-be-trimmed );
trim (' removing spaces at both sides ');
this returns "removing spaces at both sides"
ltrim ( string-to-be-trimmed [, trimming-char-set ] );
ltrim (' removing spaces at the left side ');
this returns "removing spaces at the left side "
rtrim ( string-to-be-trimmed [, trimming-char-set ] );
rtrim (' removing spaces at the right side ');
this returns " removing spaces at the right side"
DDLSQL
Tables
Createtable
Thesyntaxtocreateatableis:
CREATE TABLE [table name]
( [column name] [datatype], ... );
Forexample:
CREATE TABLE employee
(id int, name varchar(20));
Addcolumn
Thesyntaxtoaddacolumnis:
ALTER TABLE [table name]
ADD ( [column name] [datatype], ... );
Forexample:
ALTER TABLE employee
ADD (id int)
Modifycolumn
Thesyntaxtomodifyacolumnis:
ALTER TABLE [table name]
MODIFY ( [column name] [new datatype] );
ALTERtablesyntaxandexamples:
Forexample:
ALTER TABLE employee
MODIFY( sickHours s float );
Dropcolumn
Thesyntaxtodropacolumnis:
ALTER TABLE [table name]
DROP COLUMN [column name];
Forexample:
ALTER TABLE employee
DROP COLUMN vacationPay;
Constraints
Constrainttypesandcodes
TypeCode TypeDescription ActsOnLevel
C Checkonatable Column
O ReadOnlyonaview Object
P PrimaryKey Object
R ReferentialAKAForeignKey Column
U UniqueKey Column
V CheckOptiononaview Object
Displayingconstraints
Thefollowingstatementshowsallconstraintsinthesystem:
SELECT
table_name,
constraint_name,
constraint_type
FROM user_constraints;
select*table_name
Selectingreferentialconstraints
Thefollowingstatementshowsallreferentialconstraints(foreignkeys)withbothsourceand
destinationtable/columncouples:
SELECT
c_list.CONSTRAINT_NAME as NAME,
c_src.TABLE_NAME as SRC_TABLE,
c_src.COLUMN_NAME as SRC_COLUMN,
c_dest.TABLE_NAME as DEST_TABLE,
c_dest.COLUMN_NAME as DEST_COLUMN
FROM ALL_CONSTRAINTS c_list,
ALL_CONS_COLUMNS c_src,
ALL_CONS_COLUMNS c_dest
WHERE c_list.CONSTRAINT_NAME = c_src.CONSTRAINT_NAME
AND c_list.R_CONSTRAINT_NAME = c_dest.CONSTRAINT_NAME
AND c_list.CONSTRAINT_TYPE = 'R'
GROUP BY c_list.CONSTRAINT_NAME,
c_src.TABLE_NAME,
c_src.COLUMN_NAME,
c_dest.TABLE_NAME,
c_dest.COLUMN_NAME;
Creatinguniqueconstraints
Thesyntaxforauniqueconstraintis:
ALTER TABLE [table name]
ADD CONSTRAINT [constraint name] UNIQUE( [column name] ) USING INDEX [index name];
Forexample:
ALTER TABLE employee
ADD CONSTRAINT uniqueEmployeeId UNIQUE(employeeId) USING INDEX ourcompanyIndx_tbs;
Deletingconstraints
Thesyntaxfordropping(removing)aconstraintis:
ALTER TABLE [table name]
DROP CONSTRAINT [constraint name];
Forexample:
ALTER TABLE employee
DROP CONSTRAINT uniqueEmployeeId;
Seealso:OracleConstraints(http://www.psoug.org/reference/constraints.html)
INDEXES
Anindexisamethodthatretrievesrecordswithgreaterefficiency.Anindexcreatesanentryforeach
valuethatappearsintheindexedcolumns.Bydefault,OraclecreatesBtreeindexes.
Createanindex
Thesyntaxforcreatinganindexis:
CREATE [UNIQUE] INDEX index_name
ON table_name (column1, column2, . column_n)
[ COMPUTE STATISTICS ];
UNIQUEindicatesthatthecombinationofvaluesintheindexedcolumnsmustbeunique.
COMPUTESTATISTICStellsOracletocollectstatisticsduringthecreationoftheindex.Thestatistics
arethenusedbytheoptimizertochooseanoptimalexecutionplanwhenthestatementsareexecuted.
Forexample:
CREATE INDEX customer_idx
ON customer (customer_name);
Inthisexample,anindexhasbeencreatedonthecustomertablecalledcustomer_idx.Itconsistsofonlyof
thecustomer_namefield.
Thefollowingcreatesanindexwithmorethanonefield:
CREATE INDEX customer_idx
ON supplier (customer_name, country);
Thefollowingcollectsstatisticsuponcreationoftheindex:
CREATE INDEX customer_idx
ON supplier (customer_name, country)
COMPUTE STATISTICS;
Createafunctionbasedindex
InOracle,youarenotrestrictedtocreatingindexesononlycolumns.Youcancreatefunctionbased
indexes.
Thesyntaxthatcreatesafunctionbasedindexis:
CREATE [UNIQUE] INDEX index_name
ON table_name (function1, function2, . function_n)
[ COMPUTE STATISTICS ];
Forexample:
CREATE INDEX customer_idx
ON customer (UPPER(customer_name));
Anindex,basedontheuppercaseevaluationofthecustomer_namefield,hasbeencreated.
ToassurethattheOracleoptimizerusesthisindexwhenexecutingyourSQLstatements,besurethat
UPPER(customer_name)doesnotevaluatetoaNULLvalue.Toensurethis,add
UPPER(customer_name)ISNOTNULLtoyourWHEREclauseasfollows:
SELECT customer_id, customer_name, UPPER(customer_name)
FROM customer
WHERE UPPER(customer_name) IS NOT NULL
ORDER BY UPPER(customer_name);
RenameanIndex
Thesyntaxforrenaminganindexis:
ALTER INDEX index_name
RENAME TO new_index_name;
Forexample:
ALTER INDEX customer_id
RENAME TO new_customer_id;
Inthisexample,customer_idisrenamedtonew_customer_id.
Collectstatisticsonanindex
Ifyouneedtocollectstatisticsontheindexafteritisfirstcreatedoryouwanttoupdatethestatistics,you
canalwaysusetheALTERINDEXcommandtocollectstatistics.Youcollectstatisticssothatoraclecan
usetheindexesinaneffectivemanner.Thisrecalcultesthetablesize,numberofrows,blocks,segments
andupdatethedictionarytablessothatoraclecanusethedataeffectivelywhilechoosingtheexecution
plan.
Thesyntaxforcollectingstatisticsonanindexis:
ALTER INDEX index_name
REBUILD COMPUTE STATISTICS;
Forexample:
ALTER INDEX customer_idx
REBUILD COMPUTE STATISTICS;
Inthisexample,statisticsarecollectedfortheindexcalledcustomer_idx.
Dropanindex
Thesyntaxfordroppinganindexis:
DROP INDEX index_name;
Forexample:
DROP INDEX customer_idx;
Inthisexample,thecustomer_idxisdropped.
DBARelated
UserManagement
Creatingauser
ggOracleProgramming/SQLCheatsheetThesyntaxforcreatingauseris:
CREATE USER username IDENTIFIED BY password;
Forexample:
CREATE USER brian IDENTIFIED BY brianpass;
Grantingprivileges
Thesyntaxforgrantingprivilegesis:
GRANT privilege TO Gulfnet_krishna(user);
Forexample:
GRANT dba TO brian;
Changepassword
Thesyntaxforchanginguserpasswordis:
ALTER USER username IDENTIFIED BY password;
Forexample:
ALTER USER brian IDENTIFIED BY brianpassword;
Importingandexporting
Therearetwomethodsofbackingupandrestoringdatabasetablesanddata.The'exp'and'imp'toolsare
simplertoolsgearedtowardssmallerdatabases.Ifdatabasestructuresbecomemorecomplexorarevery
large(>50GBforexample)thenusingtheRMANtoolismoreappropriate.
ImportadumpfileusingIMP
ThiscommandisusedtoimportOracletablesandtabledatafroma*.dmpfilecreatedbythe'exp'tool.
Rememberthatthisacommandthatisexecutedfromthecommandlinethrough$ORACLE_HOME/bin
andnotwithinSQL*Plus.
Thesyntaxforimportingadumpfileis:
imp KEYWORD=value
Therearenumberofparametersyoucanuseforkeywords.
Toviewallthekeywords:
imp HELP=yes
Anexample:
imp brian/brianpassword FILE=mydump.dmp FULL=yes
PL/SQL
Operators
(incomplete)
Arithmeticoperators
Addition:+
Subtraction:
Multiplication:*
Division:/
Power(PL/SQLonly):**
Examples
givesallemployeesa5%raise
UPDATE employee SET salary = salary * 1.05
WHERE customer_id = 5;
determinestheaftertaxwageforallemployees
SELECT wage - tax FROM employee;
Comparisonoperators
GreaterThan:>
GreaterThanorEqualTo:>=
LessThan:<
LessThanorEqualto:<=
Equivalence:=
Inequality:!=^=<>=(dependsonplatform)
Examples
SELECT name, salary, email FROM employees WHERE salary > 40000;
SELECT name FROM customers WHERE customer_id < 6;
Stringoperators
Concatenate:||
Dateoperators
Addition:+
Subtraction:
Types
BasicPL/SQLTypes
Scalartype(definedinpackageSTANDARD):NUMBER,CHAR,VARCHAR2,BOOLEAN,
BINARY_INTEGER,LONG\LONGRAW,DATE,TIMESTAMP(anditsfamilyincludingintervals)
Compositetypes(userdefinedtypes):TABLE,RECORD,NESTEDTABLEandVARRAY
LOBdatatypes:usedtostoreanunstructuredlargeamountofdata
%TYPEanchoredtypevariabledeclaration
Thesyntaxforanchoredtypedeclarationsis
<var_name> <obj>%type [not null][:= <init-val>];
Forexample
name Books.title%type; /* name is defined as the same type as column 'title' of table Books */
commission number(5,2) := 12.5;
x commission%type; /* x is defined as the same type as variable 'commission' */
Note:
1. Anchoredvariablesallowfortheautomaticsynchronizationofthetypeofanchoredvariablewith
thetypeof<obj>whenthereisachangetothe<obj>type.
2. Anchoredtypesareevaluatedatcompiletime,sorecompiletheprogramtoreflectthechangeof
<obj>typeintheanchoredvariable.
Collections
Acollectionisanorderedgroupofelements,allofthesametype.Itisageneralconceptthatencompasses
lists,arrays,andotherfamiliardatatypes.Eachelementhasauniquesubscriptthatdeterminesitsposition
inthecollection.
--Define a PL/SQL record type representing a book:
TYPE book_rec IS RECORD
(title book.title%TYPE,
author book.author_last_name%TYPE,
year_published book.published_date%TYPE);
--define a PL/SQL table containing entries of type book_rec:
Type book_rec_tab IS TABLE OF book_rec%TYPE
INDEX BY BINARY_INTEGER;
my_book_rec book_rec%TYPE;
my_book_rec_tab book_rec_tab%TYPE;
...
my_book_rec := my_book_rec_tab(5);
find_authors_books(my_book_rec.author);
...
Therearemanygoodreasonstousecollections.
Dramaticallyfasterexecutionspeed,thankstotransparentperformanceboostsincludinganew
optimizingcompiler,betterintegratednativecompilation,andnewdatatypesthathelpoutwith
numbercrunchingapplications.
TheFORALLstatement,madeevenmoreflexibleanduseful.Forexample,FORALLnow
supportsnonconsecutiveindexes.
RegularexpressionsareavailableinPL/SQLintheformofthreenewfunctions
(REGEXP_INSTR,REGEXP_REPLACE,andREGEXP_SUBSTR)andtheREGEXP_LIKE
operatorforcomparisons.(Formoreinformation,see"FirstExpressions"byJonathanGennickin
thisissue.)
Collections,improvedtoincludesuchthingsascollectioncomparisonforequalityandsupportfor
setoperationsonnestedtables.
seealso:
TakingUpCollections(http://www.oracle.com/technology/oramag/oracle/03sep/o53plsql.html)
OracleProgrammingwithPL/SQLCollections(http://www.developer.com/db/article.php/3379271)
Storedlogic
Functions
Afunctionmustreturnavaluetothecaller.
Thesyntaxforafunctionis
CREATE [OR REPLACE] FUNCTION function_name [ (parameter [,parameter]) ]
RETURN [return_datatype]
IS
[declaration_section]
BEGIN
executable_section
return [return_value]
[EXCEPTION
exception_section]
END [procedure_name];
Forexample:
CREATE OR REPLACE FUNCTION to_date_check_null(dateString IN VARCHAR2, dateFormat IN VARCHAR2)
RETURN DATE IS
BEGIN
IF dateString IS NULL THEN
return NULL;
ELSE
return to_date(dateString, dateFormat);
END IF;
END;
Procedures
Aprocedurediffersfromafunctioninthatitmustnotreturnavaluetothecaller.
Thesyntaxforaprocedureis:
CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
Whenyoucreateaprocedureorfunction,youmaydefineparameters.Therearethreetypesofparameters
thatcanbedeclared:
1. INTheparametercanbereferencedbytheprocedureorfunction.Thevalueoftheparametercan
notbeoverwrittenbytheprocedureorfunction.
2. OUTTheparametercannotbereferencedbytheprocedureorfunction,butthevalueofthe
parametercanbeoverwrittenbytheprocedureorfunction.
3. INOUTTheparametercanbereferencedbytheprocedureorfunctionandthevalueofthe
parametercanbeoverwrittenbytheprocedureorfunction.
AlsoyoucandeclareaDEFAULTvalue
CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter [IN|OUT|IN OUT] [DEFAULT value] [,parameter]) ]
Thefollowingisasimpleexampleofaprocedure:
/* purpose: shows the students in the course specified by courseId */

CREATE OR REPLACE Procedure GetNumberOfStudents
( courseId IN number, numberOfStudents OUT number )
IS
/* although there are better ways to compute the number of students,
this is a good opportunity to show a cursor in action */
cursor student_cur is
select studentId, studentName
from course
where course.courseId = courseId;
student_rec student_cur%ROWTYPE;
BEGIN
OPEN student_cur;
LOOP
FETCH student_cur INTO student_rec;
EXIT WHEN student_cur%NOTFOUND;
numberOfStudents := numberOfStudents + 1;
END LOOP;
CLOSE student_cur;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
END GetNumberOfStudents;
anonymousblock
DECLARE
x NUMBER(4) := 0;
BEGIN
x := 1000;
BEGIN
x := x + 100;
EXCEPTION
WHEN OTHERS THEN
x := x + 2;
END;
x := x + 10;
dbms_output.put_line(x);
EXCEPTION
WHEN OTHERS THEN
x := x + 3;
END;
Passingparameterstostoredlogic
Therearethreebasicsyntaxesforpassingparameterstoastoredprocedure:positionalnotation,named
notationandmixednotation.
Thefollowingexamplescallthisprocedureforeachofthebasicsyntaxesforparameterpassing:
CREATE OR REPLACE PROCEDURE create_customer( p_name IN varchar2,
p_id IN number,
p_address IN varchar2,
p_phone IN varchar2 ) IS
BEGIN
INSERT INTO customer ( name, id, address, phone )
VALUES ( p_name, p_id, p_address, p_phone );
END create_customer;
Positionalnotation
Specifythesameparametersinthesameorderastheyaredeclaredintheprocedure.Thisnotationis
compact,butifyouspecifytheparameters(especiallyliterals)inthewrongorder,thebugcanbehardto
detect.Youmustchangeyourcodeiftheprocedure'sparameterlistchanges.
create_customer('James Whitfield', 33, '301 Anystreet', '251-222-3154');
Namednotation
Specifythenameofeachparameteralongwithitsvalue.Anarrow(=>)servesastheassociationoperator.
Theorderoftheparametersisnotsignificant.Thisnotationismoreverbose,butmakesyourcodeeasierto
readandmaintain.Youcansometimesavoidchangingcodeiftheprocedure'sparameterlistchanges,for
exampleiftheparametersarereorderedoranewoptionalparameterisadded.Namednotationisagood
practicetouseforanycodethatcallssomeoneelse'sAPI,ordefinesanAPIforsomeoneelsetouse.
create_customer(p_address => '301 Anystreet', p_id => 33, p_name => 'James Whitfield', p_phone => '251-222-3154');
Mixednotation
Specifythefirstparameterswithpositionalnotation,thenswitchtonamednotationforthelastparameters.
Youcanusethisnotationtocallproceduresthathavesomerequiredparameters,followedbysome
optionalparameters.
create_customer(v_name, v_id, p_address=> '301 Anystreet', p_phone => '251-222-3154');
Tablefunctions
CREATE TYPE object_row_type as OBJECT (
object_type VARCHAR(18),
object_name VARCHAR(30)
);
CREATE TYPE object_table_type as TABLE OF object_row_type;
CREATE OR REPLACE FUNCTION get_all_objects
RETURN object_table_type PIPELINED AS
BEGIN
FOR cur IN (SELECT * FROM all_objects)
LOOP
PIPE ROW(object_row_type(cur.object_type, cur.object_name));
END LOOP;
RETURN;
END;
SELECT * FROM TABLE(get_all_objects);
Flowcontrol
ConditionalOperators
and:AND
or:OR
not:NOT
Example
IFsalary>40000ANDsalary<=70000THEN
If/then/else
IF [condition] THEN
[statements]
ELSIF [condition] THEN
[statements}
ELSIF [condition] THEN
[statements}
ELSIF [condition] THEN
[statements}
ELSIF [condition] THEN
[statements}
ELSIF [condition] THEN
[statements}
ELSIF [condition] THEN
[statements}
ELSIF [condition] THEN
[statements}
ELSE
[statements}
END IF;
Arrays
Associativearrays
Stronglytypedarrays,usefulasinmemorytables
Example
Verysimpleexample,theindexisthekeytoaccessingthearraysothereisnoneedtoloopthrough
thewholetableunlessyouintendtousedatafromeverylineofthearray.
Theindexcanalsobeanumericvalue.
DECLARE
-- Associative array indexed by string:

-- Associative array type
TYPE population IS TABLE OF NUMBER
INDEX BY VARCHAR2(64);
-- Associative array variable
city_population population;
i VARCHAR2(64);
BEGIN
-- Add new elements to associative array:
city_population('Smallville') := 2000;
city_population('Midland') := 750000;
city_population('Megalopolis') := 1000000;

-- Change value associated with key 'Smallville':
city_population('Smallville') := 2001;

-- Print associative array by looping through it:
i := city_population.FIRST;

WHILE i IS NOT NULL LOOP
DBMS_OUTPUT.PUT_LINE
('Population of ' || i || ' is ' || TO_CHAR(city_population(i)));
i := city_population.NEXT(i);
END LOOP;

-- Print selected value from a associative array:
DBMS_OUTPUT.PUT_LINE('Selected value');
DBMS_OUTPUT.PUT_LINE('Population of
END;
/

-- Printed results:
Population of Megalopolis is 1000000
Population of Midland is 750000
Population of Smallville is 2001
Morecomplexexample,usingarecord
DECLARE
-- Record type
TYPE apollo_rec IS RECORD
(
commander VARCHAR2(100),
launch DATE
);
-- Associative array type
TYPE apollo_type_arr IS TABLE OF apollo_rec INDEX BY VARCHAR2(100);
-- Associative array variable
apollo_arr apollo_type_arr;
BEGIN
apollo_arr('Apollo 11').commander := 'Neil Armstrong';
apollo_arr('Apollo 11').launch := TO_DATE('July 16, 1969','Month dd, yyyy');
apollo_arr('Apollo 12').commander := 'Pete Conrad';
apollo_arr('Apollo 12').launch := TO_DATE('November 14, 1969','Month dd, yyyy');
apollo_arr('Apollo 13').commander := 'James Lovell';
apollo_arr('Apollo 13').launch := TO_DATE('April 11, 1970','Month dd, yyyy');
apollo_arr('Apollo 14').commander := 'Alan Shepard';
apollo_arr('Apollo 14').launch := TO_DATE('January 31, 1971','Month dd, yyyy');

DBMS_OUTPUT.PUT_LINE(apollo_arr('Apollo 11').commander);
DBMS_OUTPUT.PUT_LINE(apollo_arr('Apollo 11').launch);
end;
/

-- Printed results:
Neil Armstrong
16-JUL-69
APEX
Stringsubstitution
* In SQL: :VARIABLE
* In PL/SQL: V('VARIABLE') or NV('VARIABLE')
* In text: &VARIABLE.
Externallinks
PSOUGreference(http://www.psoug.org/reference/)
MoreWikibooks
IntroductiontoSQL
Retrievedfrom"http://en.wikibooks.org/w/index.php?
title=Oracle_Programming/SQL_Cheatsheet&oldid=2680244"
Thispagewaslastmodifiedon10July2014,at16:49.
TextisavailableundertheCreativeCommonsAttributionShareAlikeLicense.additionalterms
mayapply.Byusingthissite,youagreetotheTermsofUseandPrivacyPolicy.

Common questions

Powered by AI

Sequences in Oracle databases play a crucial role in generating unique integer values automatically, which can be used as primary keys. They allow multiple users to generate unique numbers without conflicts, facilitating distributed and concurrent transactions without errors. Sequences enhance data integrity and application performance by reducing lock contention and required application logic for key management, making them ideal for scalable applications requiring efficient key generation .

The DELETE statement in SQL is used to remove rows from a table that match specified criteria. Its basic syntax is `DELETE FROM table_name WHERE condition;`. It should be used with caution since executing a DELETE statement without a WHERE clause will remove all rows in the table, leading to potential data loss. A critical scenario would be deleting all customer data when only specific records were intended to be targeted, highlighting the need for precise conditions .

The INSERT statement using VALUES is suitable for adding one or more rows with specific values directly stated, beneficial when inserting known discrete data points. Alternatively, using INSERT with a SELECT statement is advantageous for transferring data from one table to another or populating a table with results from a query. The SELECT method should be preferred when data is dynamically derived from existing tables, whereas VALUES is simpler and preferred for static, predefined data entries .

Not specifying a UNIQUE constraint during table creation can have significant implications, including the possibility of duplicate records in the tables. This can lead to inconsistencies, particularly if columns require unique values for data integrity, such as email addresses or customer IDs. Additionally, it can complicate business logic and data retrieval operations that depend on unique entries, ultimately affecting the database's reliability and performance .

Anchored type variable declarations in PL/SQL offer the advantage of automatic synchronization of variable types with database object types, ensuring consistency and reducing maintenance. When the type of the database object changes, anchored types update automatically with recompilation, preventing runtime errors and decreasing manual changes in code. This feature leads to more robust and adaptable PL/SQL programs .

An associative array in PL/SQL is a collection of key-value pairs where the keys can be strings or numbers. Unlike traditional arrays, they are unbounded and can be sparse. Associative arrays are useful for dynamic data storage not restricted by fixed-size constraints. An example usage includes storing city populations where cities are the keys: `city_population('Smallville') := 2001;`. This dynamic management of data allows efficient data retrieval and manipulation based on keys without iterating through the entire array .

The TRIM function removes unwanted characters from both sides of a string, which is useful for cleaning up data entries with irregular spacing. LTRIM specifically removes characters from the left side, suitable for aligning text by removing leading spaces. Conversely, RTRIM eliminates characters from the right, useful for removing trailing spaces before data is stored or processed further. Each function serves specific formatting needs based on where the unwanted character resides within the string .

Creating an index in a database improves query performance by allowing for faster retrieval of records. An index creates an entry for each value in the indexed columns, which helps the database management system to locate data without scanning the entire table. By default, Oracle creates B-tree indexes, which organize data in a balanced tree structure, facilitating rapid data access and efficient query execution .

Oracle's functions like REGEXP_INSTR and REGEXP_REPLACE enhance string handling in PL/SQL by allowing complex pattern matching and substitution operations. REGEXP_INSTR searches for a pattern within a string and returns the position of the match, while REGEXP_REPLACE replaces occurrences of a pattern with a specified replacement. These functions provide flexible and powerful string manipulation capabilities, enabling developers to perform sophisticated text processing tasks that are efficient and concise .

Mixed notation for parameter passing in PL/SQL allows the combination of positional and named notation, enhancing readability and maintainability by clearly associating parameter names with their values. This is particularly useful in procedures with optional parameters, as it allows developers to explicitly specify critical parameters positionally while using named notation for others, reducing the likelihood of errors and enhancing the clarity of the code. It facilitates understanding and modification, especially in large codebases or when using external APIs .

You might also like