0% found this document useful (0 votes)
127 views7 pages

Oracle SQL Common Questions and Answers

The document discusses various SQL queries related to selecting, manipulating, and summarizing data in database tables. Some key topics covered include: - How to escape special characters in SQL queries - Methods for eliminating duplicate rows from a table - How to generate primary keys and add sequences for tables - Calculations for getting time differences between date columns and adding time values - Counting and summing different data values or ranges of values in columns - Retrieving specific rows by number from a table, such as the nth row - Selecting a range of rows between x and y - Selecting every nth row from a table using subqueries or views

Uploaded by

ashu2312
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views7 pages

Oracle SQL Common Questions and Answers

The document discusses various SQL queries related to selecting, manipulating, and summarizing data in database tables. Some key topics covered include: - How to escape special characters in SQL queries - Methods for eliminating duplicate rows from a table - How to generate primary keys and add sequences for tables - Calculations for getting time differences between date columns and adding time values - Counting and summing different data values or ranges of values in columns - Retrieving specific rows by number from a table, such as the nth row - Selecting a range of rows between x and y - Selecting every nth row from a table using subqueries or views

Uploaded by

ashu2312
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Oracle SQL FAQ Topics What is SQL and where does it come from?

? What are the difference between DDL, DML and DCL commands? How does one escape characters when building SQL ueries? How does one eliminate duplicate rows from a table? How does one generate primar! "e! #alues for a table? How does one get the time difference between two date columns? How does one add a da!$hour$minute$second to a date #alue? How does one count different data #alues in a column? How does one count$sum %&'()S of data #alues in a column? Can one retrie#e onl! the 'th row from a table? Can one retrie#e onl! rows * to + from a table? How does one select ),)%+ 'th row from a table? How does one select the -./ ' rows from a table? How does one code a tree0structured uer!? How does one code a matri1 report in SQL? How does one implement 230-H)'0)LS) in a select statement? How can one dump$ e1amine the e1act content of a database column? Can one drop a column from a table? Can one rename a column in a table? How can 2 change m! .racle password? How does one find the ne1t #alue of a se uence? Wor"around for snapshots on tables with L.'( columns Where can one get more info about SQL? 4ac" to .racle 3&Q 2nde1 What is SQL and where does it come from? Structured Quer! Language 5SQL6 is a language that pro#ides an interface to relational database s!stems7 SQL was de#eloped b! 24M in the 89:;s for use in S!stem %, and is a de facto standard, as well as an 2S. and &'S2 standard7 SQL is often pronounced S)Q<)L7 2n common usage SQL also encompasses DML 5Data Manipulation Language6, for 2'S)%-s, </D&-)s, D)L)-)s and DDL 5Data Definition Language6, used for creating and modif!ing tables and other database structures7 -he de#elopment of SQL is go#erned b! standards7 & ma=or re#ision to the SQL standard was completed in 899>, called SQL>7 SQL? support ob=ect e1tensions and are 5partiall!?6 implemented in .racle@ and 97 4ac" to top of file What are the difference between DDL, DML and DCL commands? DDL is Data Definition Language statements. Some examples: C%)&-) 0 to create ob=ects in the database &L-)% 0 alters the structure of the database D%./ 0 delete ob=ects from the database -%<'C&-) 0 remo#e all records from a table, including all spaces allocated for the records are remo#ed [Link])'- 0 add comments to the data dictionar! (%&'- 0 gi#es userAs access pri#ileges to database %),.B) 0 withdraw access pri#ileges gi#en with the (%&'- command

DML is Data Manipulation Language statements. Some examples: S)L)C- 0 retrie#e data from the a database 2'S)%- 0 insert data into a table </D&-) 0 updates e1isting data within a table

D)L)-) 0 deletes all records from a table, the space for the records remain C&LL 0 call a /L$SQL or Ca#a subprogram )*/L&2' /L&' 0 e1plain access path to data [Link] -&4L) 0 control concurrenc!

DCL is Data Control Language statements. Some examples: C.MM2- 0 sa#e wor" done S&,)/.2'- 0 identif! a point in a transaction to which !ou can later roll bac" %.LL4&CB 0 restore database to original since the last C.MM2S)- -%&'S&C-2.' 0 Change transaction options li"e what rollbac" segment to use

4ac" to top of file How does one escape special characters when building SQL queries? -he L2B) "e!word allows for string searches7 -he ADA wild card character is used to match e1actl! one character, AEA is used to match Fero or more occurrences of an! characters7 -hese characters can be escaped in SQL7 )1ampleG SELECT name FROM emp WHERE id LIKE '%\_%' ESCAPE '\'; <se two uotes for e#er! one displa!ed7 )1ampleG SELECT 'Franks''s Ora !e si"e' FROM #$AL; SELECT 'A ''%&'"ed'' ('rd)' FROM #$AL; SELECT 'A ''''d'&*!e %&'"ed'''' ('rd)' FROM #$AL; 4ac" to top of file How does one eliminate duplicates rows from a table? Choose one of the following ueries to identif! or remo#e duplicate rows from a table lea#ing uni ue records in the tableG Method 1: S+L, #ELETE FROM "a*!e_name A WHERE ROWI# , . SELECT min-r'(id/ FROM "a*!e_name 0 1 WHERE A)ke2_3a!&es 4 0)ke2_3a!&es/; Method 2: S+L, rea"e "a*!e "a*!e_name. as se!e " dis"in " 5 6r'm "a*!e_name7; S+L, dr'p "a*!e_name7; S+L, rename "a*!e_name. "' "a*!e_name7; Method 3: (thanks to Kenneth !anlu"anee# S+L, #e!e"e 6r'm m2_"a*!e (8ere r'(id n'" inS+L, se!e " ma9-r'(id/ 6r'm m2_"a*!e S+L, :r'&p *2 m2_ '!&mn_name /; Method $: (thanks to Dennis %urni&k# S+L, de!e"e 6r'm m2_"a*!e "7 S+L, (8ere e9is"s -se!e " '9' 6r'm m2_"a*!e ". S+L, (8ere ".)ke2_3a!&e7 4 "7)ke2_3a!&e7 S+L, and ".)ke2_3a!&e. 4 "7)ke2_3a!&e. S+L, and ".)r'(id , "7)r'(id/; 'oteG 2f !ou create an inde1 on the =oined fields in the inner loop, !ou, for all intents purposes, eliminate 'H> operations 5no need to loop through the entire table on each pass b! a record67 -his will speed0up th 'ote >G 2f !ou are comparing '.-0'<LL columns, use the ',L function7 %emember that '<LL is not e ual to '<LL7 -his should not be a problem as all "e! columns should be '.- '<LL b! definition7 4ac" to top of file How does one generate primary key values for a table? Create !our table with a '.- '<LL column 5sa! S)Q'.67 -his column can now be populated with uni ue #aluesG S+L, $P#ATE "a*!e_name SET se%n' 4 ROW;$M; or use a se uences generatorG S+L, CREATE SE+$E;CE se%&en e_name START WITH 7 I;CREME;T 0< 7;

S+L, $P#ATE "a*!e_name SET se%n' 4 se%&en e_name);E=T>AL; 3inall!, create a uni ue inde1 on this column7 4ac" to top of file How does one get the time difference between two date columns Loo" at this e1ample uer!G se!e " 6!''r---da"e7?da"e./5.@5AB5AB/C1ABB/ DD ' HO$RS ' DD 6!''r----da"e7?da"e./5.@5AB5AB/ ? 6!''r---da"e7?da"e./5.@5AB5AB/C1ABB/51ABB/CAB/ DD ' MI;$TES ' DD r'&nd----da"e7?da"e./5.@5AB5AB/ ? 6!''r---da"e7?da"e./5.@5AB5AB/C1ABB/51ABB ? -6!''r----da"e7?da"e./5.@5AB5AB/ ? 6!''r---da"e7?da"e./5.@5AB5AB/C1ABB/51ABB/CAB/5AB/// DD ' SECS ' "ime_di66eren e 6r'm ))) 2f !ou donAt want to go through the floor and ceiling math, tr! this method 5contributed b! )ri" Wile6G se!e " "'_ 8ar-"'_da"e-'BBEBBEBB'F'HH.@EMIESS'/ G -da"e7 ? da"e./F 'HH.@EMIESS'/ "ime_di66eren e 6r'm ))) 'ote that the second uer! onl! uses the time0of0da! portion of the date fields and thus will ne#er return a #alue bigger than >?GI9GI97 4ac" to top of file How does one add a day/hour/minute/second to a date value? -he S+SD&-) pseudo0column shows the current s!stem date and time7 &dding 8 to S+SD&-) will ad#ance the date b! 8 da!7 <se fractions to add hours, minutes or seconds to the date7 Loo" at these e1amplesG S+L, se!e " s2sda"eF s2sda"eG7C.@F s2sda"e G7C7@@BF s2sda"e G 7CHA@BB 6r'm d&a!; S<S#ATE S<S#ATEG7C.@ S<S#ATEG7C7@@B S<S#ATEG7CHA@BB ???????????????????? ???????????????????? ???????????????????? ???????????????????? B1?I&!?.BB. BHE1.E7. B1?I&!?.BB. BJE1.E7. B1?I&!?.BB. BHE11E7. B1?I&!?.BB. BHE1.E71 -he following format is fre uentl! used with .racle %eplicationG se!e " s2sda"e ;OWF s2sda"eG1BC-.@5AB5AB/ ;OW_PL$S_1B_SECS 6r'm d&a!; ;OW ;OW_PL$S_1B_SECS ???????????????????? ???????????????????? B1?I$L?.BB. 7AE@KE.1 B1?I$L?.BB. 7AE@KEL1 4ac" to top of file How does one count different data values in a column? <se this simple uer! to count the number of data #alues in a columnG se!e " m2_"a*!e_ '!&mnF '&n"-5/ 6r'm m2_"a*!e :r'&p *2 m2_"a*!e_ '!&mn; & more sophisticated e1ample777 se!e " dep"F s&m- de 'de-se9F'M'F7FB// MALEF s&m- de 'de-se9F'F'F7FB// FEMALEF '&n"-de 'de-se9F'M'F7F'F'F7// TOTAL 6r'm m2_emp_"a*!e :r'&p *2 dep"; 4ac" to top of file How does one count/sum RANGES of data values in a column? & #alue 1 will be between #alues ! and F if (%)&-)S-51, !6 J L)&S-51, F67 Loo" at this e1ampleG se!e " 6.F s&m-de 'de-:rea"es"-67FLJ/F !eas"-67F7BB/F 7F B// MRan:e AB?7BBMF s&m-de 'de-:rea"es"-67F1B/F !eas"-67F LJ/F 7F B// MRan:e 1B?LJMF s&m-de 'de-:rea"es"-67F B/F !eas"-67F .J/F 7F B// MRan:e BB?.JM

6r'm m2_"a*!e :r'&p *2 6.; 3or e ual siFe ranges it might be easier to calculate it with D)C.D)5-%<'C5#alue$range6, ;, rateD;, 8, rateD8, 77767 )g7 se!e " ename M;ameMF sa! MSa!ar2MF de 'de- "r&n -6.C7BBBF B/F BF B)BF 7F B)7F .F B).F 1F B)17/ MTa9 ra"eM 6r'm m2_"a*!e; 4ac" to top of file Can one retrieve only the Nth row from a table? Shai" Bhaleel pro#ided this solution to select the 'th row from a tableG SELECT 5 FROM SELECT E;AMEFROW;$M R; FROM EMP WHERE ROW;$M N 7B7 / WHERE R; 4 7BB; 'oteG 'oteG 2n this first it select onl! one more than the re uired row, then it selects the re uired one7 2ts far better than using M2'<S operation7 %a#i /achalla pro#ided this solutionG SELECT 67 FROM "7 WHERE r'(id 4 SELECT r'(id FROM "7 WHERE r'(n&m N4 7B MI;$S SELECT r'(id FROM "7 WHERE r'(n&m N 7B/; &lternati#el!777 SELECT 5 FROM emp WHERE r'(n&m47 A;# r'(id ;OT I; -SELECT r'(id FROM emp WHERE r'(n&m N 7B/; /lease note, there is no e1plicit row order in a relational database7 Howe#er, this uer! is uite fun and ma! e#en help in the odd situation7 4ac" to top of file Can one retrieve only rows X to Y from a table? Shai" Bhaleel pro#ided this solution to the problemG SELECT 5 FROM SELECT E;AMEFROW;$M R; FROM EMP WHERE ROW;$M N 7B7 / WHERE R; *e"(een J7 and 7BB ; 'oteG the 8;8 is =ust one greater than the ma1imum row of the re uired rows 5means 1J 9;, !J8;;, so the inner #alues is !K867 &nother solution is to use the M2'<S operation7 3or e1ample, to displa! rows I to :, construct a uer! li"e thisG SELECT 5 FROM "a*!e= WHERE r'(id in SELECT r'(id FROM "a*!e= WHERE r'(n&m N4 K MI;$S SELECT r'(id FROM "a*!e= WHERE r'(n&m N L/; /lease note, there is no e1plicit row order in a relational database7 Howe#er, this uer! is uite fun and ma! e#en help in the odd situation7 4ac" to top of file How does one select EVERY Nth row from a table? .ne can easil! select all e#en, odd, or 'th rows from a table using SQL ueries li"e thisG Method 1: <sing a sub uer! SELECT 5 FROM emp WHERE -ROWI#FB/ I; -SELECT ROWI#F MO#-ROW;$MF@/ FROM emp/; Method 2: <se d!namic #iews 5a#ailable from .racle:7>6G

SELECT 5 FROM - SELECT r'(n&m rnF empn'F ename FROM emp / "emp WHERE MO#-"emp)ROW;$MF@/ 4 B; /lease note, there is no e1plicit row order in a relational database7 Howe#er, these ueries are uite fun and ma! e#en help in the odd situation7 4ac" to top of file How does one select the TOP N rows from a table? 3orm .racle@i one can ha#e an inner0 uer! with an .%D)% 4+ clause7 Loo" at this e1ampleG SELECT 5 FROM -SELECT 5 FROM m2_"a*!e OR#ER 0< '!_name_7 #ESC/ WHERE ROW;$M N 7B; <se this wor"around with prior releasesG SELECT 5 FROM m2_"a*!e a WHERE 7B ,4 -SELECT CO$;T-#ISTI;CT ma9 '!/ FROM m2_"a*!e * WHERE *)ma9 '! ,4 a)ma9 '!/ OR#ER 0< ma9 '! #ESC; 4ac" to top of file How does one code a tree-structured query? -ree0structured ueries are definitel! non0relational 5enough to "ill Codd and ma"e him roll in his gra#e67 &lso, this feature is not often found in other database offerings7 -he SC.--$-2()% database schema contains a table )M/ with a self0referencing relation 5)M/'. and M(% columns67 -his table is perfect for tesing and demonstrating tree0structured ueries as the M(% column contains the emplo!ee number of the LcurrentL emplo!eeAs boss7 -he L),)L pseudo0column is an indication of how deep in the tree one is7 .racle can handle ueries with a depth of up to >II le#els7 Loo" at this e1ampleG se!e " LE>ELF EMP;OF E;AMEF MOR 6r'm EMP 'nne " *2 pri'r EMP;O 4 MOR s"ar" (i"8 MOR is ;$LL; .ne can produce an indented report b! using the le#el number to substring or lpad56 a series of spaces, and concatenate that to the string7 Loo" at this e1ampleG se!e " !pad-' 'F LE>EL 5 ./ DD E;AME )))))))) .ne uses the Lstart withL clause to specif! the start of the tree7 More than one record can match the starting condition7 .ne disad#antage of ha#ing a Lconnect b! priorL clause is that !ou cannot perform a =oin to other tables7 -he Lconnect b! priorL clause is rarel! implemented in the other database offerings7 -r!ing to do this programmaticall! is difficult as one has to do the top le#el uer! first, then, for each of the records open a cursor to loo" for child nodes7 .ne wa! of wor"ing around this is to use /L$SQL, open the dri#ing cursor with the Lconnect b! priorL statement, and the select matching records from other tables on a row0b!0row basis, inserting the results into a temporar! table for later retrie#al7 4ac" to top of file How does one code a matrix report in SQL? Loo" at this e1ample uer! with sample outputG SELECT 5 FROM -SELECT P'*F s&m-de 'de-dep"n'F7BFsa!// s&m-de 'de-dep"n'[Link]!// s&m-de 'de-dep"n'F1BFsa!// s&m-de 'de-dep"n'F@BFsa!// FROM s '"")emp ORO$P 0< P'*/ OR#ER 0< 7;

#EPT7BF #[Link] #EPT1BF #EPT@B

IO0 #EPT7B #EPT.B #EPT1B #EPT@B ????????? ?????????? ?????????? ?????????? ?????????? A;AL<ST ABBB

CLERK MA;AOER PRESI#E;T SALESMA; 4ac" to top of file

71BB .@LB LBBB

7JBB .JKL

JLB .HLB LABB

How does one implement IF-THEN-ELSE in a select statement? -he .racle de&ode function acts li"e a procedural statement inside an SQL statement to return different #alues or columns based on the #alues of other columns in the select statement7 Some examples: se!e " de 'de-se9F 'M'F 'Ma!e'F 'F'F 'Fema!e'F '$nkn'(n'/ 6r'm emp!'2ees; se!e " aF *F de 'de- a*s-a?*/F a?*F 'a , *'F BF 'a 4 *'F 'a N *'/ 6r'm "a*!e=; se!e " de 'de- OREATEST-AF0/F AF 'A is :rea"er OR E+$AL "8an 0'F '0 is :rea"er "8an A'/))) se!e " de 'de- OREATEST-AF0/F AF de 'de-AF 0F 'A ;OT OREATER THA; 0'F 'A OREATER THA; 0'/F 'A ;OT OREATER THA; 0'/))) 'ote: -he decode function is not &'S2 SQL and is rarel! implemented in other %D4MS offerings7 2t is one of the good things about .racle, but use it sparingl! if portabilit! is re uired7 3rom .racle @i one can also use C&S) statements in SQL7 Loo" at this e1ampleG SELECT enameF CASE WHE; sa!,7BBB THE; 'O3er paid' ELSE '$nder paid' E;# FROM emp; 4ac" to top of file How can one dump/ examine the exact content of a database column? SELECT #$MP- '!7/ FROM "a*7 WHERE 'nd7 4 3a!7; #$MP-COL7/ ????????????????????????????????????? T2p4JA Len4@E ALFAAFAKF1. 3or this e1ample the t!pe is 9M, indicating CH&%, and the last b!te in the column is ?>, which is the &SC22 code for a space7 -his tells us that this column is blan"0padded7 4ac" to top of file Can one drop a column from a table? 3rom .racle@i one can D%./ a column from a table7 Loo" at this sample script, demonstrating the ALTER TABLE table_name DROP COLUMN column_name; command7 .ther wor"aroundsG 7) S+L, &pda"e "7 se" '!&mn_"'_dr'p 4 ;$LL; S+L, rename "7 "' "7_*ase; S+L, rea"e 3ie( "7 as se!e " Nspe i6i '!&mns, 6r'm "7_*ase; .) S+L, rea"e "a*!e ". as se!e " Nspe i6i S+L, dr'p "a*!e "7; S+L, rename ". "' "7; 4ac" to top of file Can one rename a column in a table? 'o, this is listed as )nhancement %e uest 8M?I897 Some wor"aroundsG 7) ?? $se a 3ie( (i"8 'rre " '!&mn names))) rename "7 "' "7_*ase; rea"e 3ie( "7 N '!&mn !is" (i"8 ne( name, as se!e " 5 6r'm "7_*ase; .) ?? Re rea"e "8e "a*!e (i"8 'rre " '!&mn names))) rea"e "a*!e ". N '!&mn !is" (i"8 ne( name, as se!e " 5 6r'm "7; '!&mns, 6r'm "7;

dr'p "a*!e "7; rename ". "' "7; 1) ?? Add a '!&mn (i"8 a ne( name and dr'p an '!d a!"er "a*!e "7 add - ne( '!ame da"a"2pe /; &pda"e "7 se" ne( '!name4'!d '!name; a!"er "a*!e "7 dr'p '!&mn '!d '!name; 4ac" to top of file How can I change my Oracle password? 2ssue the following SQL commandG ALTER $SER N&sername, I#E;TIFIE# 0< Nne(_pass('rd, C 3rom .racle@ !ou can =ust t!pe LpasswordL from SQLN/lus, or if !ou need to change another userAs password, t!pe Lpassword userDnameL7 4ac" to top of file How does one find the next value of a sequence? /erform an L&L-)% S)Q<)'C) 777 '.C&CH)L to unload the unused cached se uence numbers from the .racle librar! cache7 -his wa!, no cached numbers will be lost7 2f !ou then select from the <S)%DS)Q<)'C)S dictionar! #iew, !ou will see the correct high water mar" #alue that would be returned for the ne1t ')*-,&LL call7 &fterwards, perform an L&L-)% S)Q<)'C) 777 C&CH)L to restore caching7 +ou can use the abo#e techni ue to pre#ent se uence number loss before a SHUTDOWN ABORT, or an! other operation that would cause gaps in se uence #alues7 4ac" to top of file Workaround for snapshots on tables with LONG columns +ou can use the SQLN/lus C./+ command instead of snapshots if !ou need to cop! L.'( and L.'( %&W #ariables from one location to another7 )gG COP< TO SCOTTCTIOERQREMOTE ? CREATE IMAOE_TA0LE $SI;O ? SELECT IMAOE_;OF IMAOE ? FROM IMAOES; 'oteG 2f !ou run .racle@, con#ert !our L.'(s to L.4s, as it can be replicated7 4ac" to top of file Where can one get more info about SQL? -he SQL 3&Q 2ntroduction to Structured Quer! Language SQL -utorial -ina LondonAs SQL (uide '!&mn)))

You might also like