+ All Categories
Home > Documents > Most Useful SQL Queries

Most Useful SQL Queries

Date post: 07-Apr-2018
Category:
Upload: murali-rajan
View: 247 times
Download: 0 times
Share this document with a friend

of 26

Transcript
  • 8/6/2019 Most Useful SQL Queries

    1/26

    Use the command to get the output in txt file of a sql query...spool oradata.txtselect xxxxxxx from tab1;spool off

    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 queries?

    How does one eliminate duplicate rows from a table?

    How does one generate primary key values for a table?

    How does one get the time difference between two date columns?

    How does one add a day/hour/minute/second to a date value?

    How does one count different data values in a column?

    How does one count/sum RANGES of data values in a column?

    Can one retrieve only the Nth row from a table?

    Can one retrieve only rows X to Y from a table? How does one select EVERY Nth row from a table?

    How does one select the TOP N rows from a table?

    How does one code a tree-structured query?

    How does one code a matrix report in SQL?

    How does one implement IF-THEN-ELSE in a select statement?

    How can one dump/ examine the exact content of a database column?

    Can one drop a column from a table?

    Can one rename a column in a table?

    How can I change my Oracle password?

    How does one find the next value of a sequence?

    Workaround for snapshots on tables with LONG columns

    Where can one get more info about SQL?

    What are the difference between DDL, DML and DCL commands?

    DDL is Data Definition Language statements. Some examples:

    CREATE - to create objects in the database

    ALTER - alters the structure of the database

    DROP - delete objects from the database

    TRUNCATE - remove all records from a table, including all spaces allocated for

    the records are removed

    COMMENT - add comments to the data dictionary GRANT - gives user's access privileges to database

    REVOKE - withdraw access privileges given with the GRANT command

    DML is Data Manipulation Language statements. Some examples:

    SELECT - retrieve data from the a database

    INSERT - insert data into a table

    http://www.orafaq.com/faqsql.htm#WHAT%23WHAThttp://www.orafaq.com/faqsql.htm#CMDTYPES%23CMDTYPEShttp://www.orafaq.com/faqsql.htm#QUOTE%23QUOTEhttp://www.orafaq.com/faqsql.htm#ONLOGON%23ONLOGONhttp://www.orafaq.com/faqsql.htm#GENKEYS%23GENKEYShttp://www.orafaq.com/faqsql.htm#TIMEDIFF%23TIMEDIFFhttp://www.orafaq.com/faqsql.htm#DATEADD%23DATEADDhttp://www.orafaq.com/faqsql.htm#COUNT%23COUNThttp://www.orafaq.com/faqsql.htm#COUNTRANGE%23COUNTRANGEhttp://www.orafaq.com/faqsql.htm#NTHROW%23NTHROWhttp://www.orafaq.com/faqsql.htm#ROWXtoY%23ROWXtoYhttp://www.orafaq.com/faqsql.htm#EVERYNTHROW%23EVERYNTHROWhttp://www.orafaq.com/faqsql.htm#TOP%23TOPhttp://www.orafaq.com/faqsql.htm#TREE%23TREEhttp://www.orafaq.com/faqsql.htm#MATRIX%23MATRIXhttp://www.orafaq.com/faqsql.htm#IF%23IFhttp://www.orafaq.com/faqsql.htm#DEBUG%23DEBUGhttp://www.orafaq.com/faqsql.htm#DROPCOL%23DROPCOLhttp://www.orafaq.com/faqsql.htm#RENAMECOL%23RENAMECOLhttp://www.orafaq.com/faqsql.htm#PASSWD%23PASSWDhttp://www.orafaq.com/faqsql.htm#SEQVALS%23SEQVALShttp://www.orafaq.com/faqsql.htm#SNAPSHOTS%23SNAPSHOTShttp://www.orafaq.com/faqsql.htm#WHERE%23WHEREhttp://www.orafaq.com/faqsql.htm#WHAT%23WHAThttp://www.orafaq.com/faqsql.htm#CMDTYPES%23CMDTYPEShttp://www.orafaq.com/faqsql.htm#QUOTE%23QUOTEhttp://www.orafaq.com/faqsql.htm#ONLOGON%23ONLOGONhttp://www.orafaq.com/faqsql.htm#GENKEYS%23GENKEYShttp://www.orafaq.com/faqsql.htm#TIMEDIFF%23TIMEDIFFhttp://www.orafaq.com/faqsql.htm#DATEADD%23DATEADDhttp://www.orafaq.com/faqsql.htm#COUNT%23COUNThttp://www.orafaq.com/faqsql.htm#COUNTRANGE%23COUNTRANGEhttp://www.orafaq.com/faqsql.htm#NTHROW%23NTHROWhttp://www.orafaq.com/faqsql.htm#ROWXtoY%23ROWXtoYhttp://www.orafaq.com/faqsql.htm#EVERYNTHROW%23EVERYNTHROWhttp://www.orafaq.com/faqsql.htm#TOP%23TOPhttp://www.orafaq.com/faqsql.htm#TREE%23TREEhttp://www.orafaq.com/faqsql.htm#MATRIX%23MATRIXhttp://www.orafaq.com/faqsql.htm#IF%23IFhttp://www.orafaq.com/faqsql.htm#DEBUG%23DEBUGhttp://www.orafaq.com/faqsql.htm#DROPCOL%23DROPCOLhttp://www.orafaq.com/faqsql.htm#RENAMECOL%23RENAMECOLhttp://www.orafaq.com/faqsql.htm#PASSWD%23PASSWDhttp://www.orafaq.com/faqsql.htm#SEQVALS%23SEQVALShttp://www.orafaq.com/faqsql.htm#SNAPSHOTS%23SNAPSHOTShttp://www.orafaq.com/faqsql.htm#WHERE%23WHERE
  • 8/6/2019 Most Useful SQL Queries

    2/26

    UPDATE - updates existing data within a table

    DELETE - deletes all records from a table, the space for the records remain

    CALL - call a PL/SQL or Java subprogram

    EXPLAIN PLAN - explain access path to data

    LOCK TABLE - control concurrency

    DCL is Data Control Language statements. Some examples:

    COMMIT - save work done

    SAVEPOINT - identify a point in a transaction to which you can later roll back

    ROLLBACK - restore database to original since the last COMMIT

    SET TRANSACTION - Change transaction options like what rollback segmentto use

    Back to top of file

    How does one escape special characters when building SQL queries?

    The LIKE keyword allows for string searches. The '_' wild card character is used to

    match exactly one character, '%' is used to match zero or more occurrences of anycharacters. These characters can be escaped in SQL. Example:

    SELECT name FROM emp WHERE id LIKE '%\_%' ESCAPE '\';

    Use two quotes for every one displayed. Example:

    SELECT 'Franks''s Oracle site' FROM DUAL;

    SELECT 'A ''quoted'' word.' FROM DUAL;

    SELECT 'A ''''double quoted'''' word.' FROM DUAL;

    Back to top of file

    How does one eliminate duplicates rows from a table?

    Choose one of the following queries to identify or remove duplicate rows from a table

    leaving only unique records in the table:

    Method 1:

    SQL> DELETE FROM table_name A WHERE ROWID > (

    2 SELECT min(rowid) FROM table_name B

    3 WHERE A.key_values = B.key_values);

    Method 2:

    http://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    3/26

    SQL> create table table_name2 as select distinct * from table_name1;

    SQL> drop table_name1;

    SQL> rename table_name2 to table_name1;

    SQL> -- Remember to recreate all indexes, constraints, triggers, etc on table...

    Method 3: (thanks to Dennis Gurnick)

    SQL> delete from my_table t1

    SQL> where exists (select 'x' from my_table t2

    SQL> where t2.key_value1 = t1.key_value1

    SQL> and t2.key_value2 = t1.key_value2

    SQL> and t2.rowid > t1.rowid);

    Note: One can eliminate N^2 unnecessary operations by creating an index on thejoined fields in the inner loop (no need to loop through the entire table on each pass

    by a record). This will speed-up the deletion process.

    Note 2: If you are comparing NOT-NULL columns, use the NVL function. Remember

    that NULL is not equal to NULL. This should not be a problem as all key columnsshould be NOT NULL by definition.

    Back to top of file

    How does one generate primary key values for a table?

    Create your table with a NOT NULL column (say SEQNO). This column can now be

    populated with unique values:

    SQL> UPDATE table_name SET seqno = ROWNUM;

    or use a sequences generator:

    SQL> CREATE SEQUENCE sequence_name START WITH 1 INCREMENT BY 1;

    SQL> UPDATE table_name SET seqno = sequence_name.NEXTVAL;

    Finally, create a unique index on this column.

    Back to top of file

    How does one get the time difference between two date columns?

    Look at this example query:

    mailto:[email protected]://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilemailto:[email protected]://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    4/26

    select floor(((date1-date2)*24*60*60)/3600)

    || ' HOURS ' ||

    floor((((date1-date2)*24*60*60) -

    floor(((date1-date2)*24*60*60)/3600)*3600)/60)

    || ' MINUTES ' ||

    round((((date1-date2)*24*60*60) -

    floor(((date1-date2)*24*60*60)/3600)*3600 -

    (floor((((date1-date2)*24*60*60) -

    floor(((date1-date2)*24*60*60)/3600)*3600)/60)*60)))

    || ' SECS ' time_difference

    from ...

    If you don't want to go through the floor and ceiling math, try this method

    (contributed by Erik Wile):

    select to_char(to_date('00:00:00','HH24:MI:SS') +

    (date1 - date2), 'HH24:MI:SS') time_difference

    from ...

    Note that this query only uses the time portion of the date and ignores the dateitself. It will thus never return a value bigger than 23:59:59.

    Back to top of file

    How does one add a day/hour/minute/second to a date value?

    The SYSDATE pseudo-column shows the current system date and time. Adding 1 to

    SYSDATE will advance the date by 1 day. Use fractions to add hours, minutes orseconds to the date. Look at these examples:

    SQL> select sysdate, sysdate+1/24, sysdate +1/1440, sysdate + 1/86400

    from dual;

    SYSDATE SYSDATE+1/24 SYSDATE+1/1440

    SYSDATE+1/86400

    -------------------- -------------------- -------------------- --------------------

    mailto:[email protected]://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilemailto:[email protected]://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    5/26

    03-Jul-2002 08:32:12 03-Jul-2002 09:32:12 03-Jul-2002 08:33:12 03-Jul-

    2002 08:32:13

    The following format is frequently used with Oracle Replication:

    select sysdate NOW, sysdate+30/(24*60*60) NOW_PLUS_30_SECS fromdual;

    NOW NOW_PLUS_30_SECS

    -------------------- --------------------

    03-JUL-2002 16:47:23 03-JUL-2002 16:47:53

    Here are a couple of examples:

    Description Date Expression

    Now SYSDATE

    Tomorow/ next day SYSDATE + 1

    Seven days from

    nowSYSDATE + 7

    One hour from now SYSDATE + 1/24

    Three hours fromnow

    SYSDATE + 3/24

    An half hour fromnow

    SYSDATE + 1/48

    10 minutes from now SYSDATE + 10/1440

    30 seconds from now SYSDATE + 30/86400

    Tomorrow at 12midnight

    TRUNC(SYSDATE + 1)

    Tomorrow at 8 AM TRUNC(SYSDATE + 1) + 8/24

    Next Monday at12:00 noon

    NEXT_DAY(TRUNC(SYSDATE), 'MONDAY') + 12/24

    First day of next

    month at 12midnight

    TRUNC(LAST_DAY(SYSDATE ) + 1)

    First day of thecurrent month

    TRUNC(LAST_DAY(ADD_MONTHS(SYSDATE,-1))) + 1

    The next Monday,Wednesday or Friday

    at 9 a.m

    TRUNC(LEAST(NEXT_DAY(sysdate,''MONDAY'' ),NEXT_DAY(sysd

    ate,''WEDNESDAY''), NEXT_DAY(sysdate,''FRIDAY'' ))) + (9/24)

    Back to top of file

    How does one count different data values in a column?

    http://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    6/26

    Use this simple query to count the number of data values in a column:

    select my_table_column, count(*)

    from my_table

    group by my_table_column;

    A more sophisticated example...

    select dept, sum( decode(sex,'M',1,0)) MALE,

    sum( decode(sex,'F',1,0)) FEMALE,

    count(decode(sex,'M',1,'F',1)) TOTAL

    from my_emp_table

    group by dept;

    Back to top of file

    How does one count/sum RANGES of data values in a column?

    A value x will be between values y and z if GREATEST(x, y) = LEAST(x, z). Look at

    this example:

    select f2,

    sum(decode(greatest(f1,59), least(f1,100), 1, 0)) "Range 60-100",

    sum(decode(greatest(f1,30), least(f1, 59), 1, 0)) "Range 30-59",

    sum(decode(greatest(f1, 0), least(f1, 29), 1, 0)) "Range 00-29"

    from my_table

    group by f2;

    For equal size ranges it might be easier to calculate it withDECODE(TRUNC(value/range), 0, rate_0, 1, rate_1, ...). Eg.

    select ename "Name", sal "Salary",

    decode( trunc(f2/1000, 0), 0, 0.0,

    1, 0.1,

    2, 0.2,

    3, 0.31) "Tax rate"

    from my_table;

    Back to top of file

    http://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    7/26

    Can one retrieve only the Nth row from a table?

    Rupak Mohan provided this solution to select the Nth row from a table:

    SELECT * FROM t1 a

    WHERE n = (SELECT COUNT(rowid)

    FROM t1 b

    WHERE a.rowid >= b.rowid);

    Shaik Khaleel provided this solution:

    SELECT * FROM (

    SELECT ENAME,ROWNUM RN FROM EMP WHERE ROWNUM < 101 )

    WHERE RN = 100;

    Note: In this first query we select one more than the required row number, then weselect the required one. Its far better than using a MINUS operation.

    Ravi Pachalla provided these solutions:

    SELECT f1 FROM t1

    WHERE rowid = (

    SELECT rowid FROM t1

    WHERE rownum

  • 8/6/2019 Most Useful SQL Queries

    8/26

    Please note, there is no explicit row order in a relational database. However, thisquery is quite fun and may even help in the odd situation.

    Back to top of file

    Can one retrieve only rows X to Y from a table?

    Shaik Khaleel provided this solution to the problem:

    SELECT * FROM (

    SELECT ENAME,ROWNUM RN FROM EMP WHERE ROWNUM < 101

    ) WHERE RN between 91 and 100 ;

    Note: the 101 is just one greater than the maximum row of the required rows

    (means x= 90, y=100, so the inner values is y+1).

    Ravi Pachalla provided this solution:

    SELECT rownum, f1 FROM t1

    GROUP BY rownum, f1 HAVING rownum BETWEEN 2 AND 4;

    Another solution is to use the MINUS operation. For example, to display rows 5 to 7,

    construct a query like this:

    SELECT *

    FROM tableX

    WHERE rowid in (

    SELECT rowid FROM tableX

    WHERE rownum

  • 8/6/2019 Most Useful SQL Queries

    9/26

    Method 1: Using a subquery

    SELECT *

    FROM emp

    WHERE (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,4)

    FROM emp);

    Method 2: Use dynamic views (available from Oracle7.2):

    SELECT *

    FROM ( SELECT rownum rn, empno, ename

    FROM emp

    ) temp

    WHERE MOD(temp.ROWNUM,4) = 0;

    Method 3: Using GROUP BY and HAVING - provided by Ravi Pachalla

    SELECT rownum, f1

    FROM t1

    GROUP BY rownum, f1 HAVING MOD(rownum,n) = 0 OR rownum = 2-n

    Please note, there is no explicit row order in a relational database. However, these

    queries are quite fun and may even help in the odd situation.

    Back to top of file

    How does one select the TOP N rows from a table?

    Form Oracle8i one can have an inner-query with an ORDER BY clause. Look at thisexample:

    SELECT *

    FROM (SELECT * FROM my_table ORDER BY col_name_1 DESC)

    WHERE ROWNUM < 10;

    Use this workaround with prior releases:

    SELECT *

    FROM my_table a

    WHERE 10 >= (SELECT COUNT(DISTINCT maxcol)

    mailto:[email protected]://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilemailto:[email protected]://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    10/26

    FROM my_table b

    WHERE b.maxcol >= a.maxcol)

    ORDER BY maxcol DESC;

    Back to top of file

    How does one code a tree-structured query?

    Tree-structured queries are definitely non-relational (enough to kill Codd and make

    him roll in his grave). Also, this feature is not often found in other database

    offerings.

    The SCOTT/TIGER database schema contains a table EMP with a self-referencingrelation (EMPNO and MGR columns). This table is perfect for tesing and

    demonstrating tree-structured queries as the MGR column contains the employeenumber of the "current" employee's boss.

    The LEVEL pseudo-column is an indication of how deep in the tree one is. Oracle canhandle queries with a depth of up to 255 levels. Look at this example:

    select LEVEL, EMPNO, ENAME, MGR

    from EMP

    connect by prior EMPNO = MGR

    start with MGR is NULL;

    One can produce an indented report by using the level number to substring or lpad()a series of spaces, and concatenate that to the string. Look at this example:

    select lpad(' ', LEVEL * 2) || ENAME ........

    One uses the "start with" clause to specify the start of the tree. More than onerecord can match the starting condition. One disadvantage of having a "connect by

    prior" clause is that you cannot perform a join to other tables. The "connect by prior"

    clause is rarely implemented in the other database offerings. Trying to do thisprogrammatically is difficult as one has to do the top level query first, then, for each

    of the records open a cursor to look for child nodes.

    One way of working around this is to use PL/SQL, open the driving cursor with the"connect by prior" statement, and the select matching records from other tables on arow-by-row basis, inserting the results into a temporary table for later retrieval.

    Back to top of file

    How does one code a matrix report in SQL?

    http://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    11/26

    Look at this example query with sample output:

    SELECT *

    FROM (SELECT job,

    sum(decode(deptno,10,sal)) DEPT10,

    sum(decode(deptno,20,sal)) DEPT20,

    sum(decode(deptno,30,sal)) DEPT30,

    sum(decode(deptno,40,sal)) DEPT40

    FROM scott.emp

    GROUP BY job)

    ORDER BY 1;

    JOB DEPT10 DEPT20 DEPT30 DEPT40

    --------- ---------- ---------- ---------- ----------

    ANALYST 6000

    CLERK 1300 1900 950

    MANAGER 2450 2975 2850

    PRESIDENT 5000

    SALESMAN 5600

    Back to top of file

    How does one implement IF-THEN-ELSE in a select statement?

    The Oracle decode function acts like a procedural statement inside an SQLstatement to return different values or columns based on the values of othercolumns in the select statement.

    Some examples:

    select decode(sex, 'M', 'Male', 'F', 'Female', 'Unknown')

    from employees;

    select a, b, decode( abs(a-b), a-b, 'a > b',

    0, 'a = b',

    http://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    12/26

    'a < b') from tableX;

    select decode( GREATEST(A,B), A, 'A is greater OR EQUAL than B', 'B is

    greater than A')...

    select decode( GREATEST(A,B),

    A, decode(A, B, 'A NOT GREATER THAN B', 'A GREATER THAN B'),

    'A NOT GREATER THAN B')...

    Note: The decode function is not ANSI SQL and is rarely implemented in otherRDBMS offerings. It is one of the good things about Oracle, but use it sparingly ifportability is required.

    From Oracle 8i one can also use CASE statements in SQL. Look at this example:

    SELECT ename, CASE WHEN sal>1000 THEN 'Over paid' ELSE 'Under paid'

    END

    FROM emp;

    Back to top of file

    How can one dump/ examine the exact content of a database column?

    SELECT DUMP(col1)

    FROM tab1

    WHERE cond1 = val1;

    DUMP(COL1)

    -------------------------------------

    Typ=96 Len=4: 65,66,67,32

    For this example the type is 96, indicating CHAR, and the last byte in the column is

    32, which is the ASCII code for a space. This tells us that this column is blank-padded.

    Back to top of file

    Can one drop a column from a table?

    http://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    13/26

    From Oracle8i one can DROP a column from a table. Look at this sample script,demonstrating theALTER TABLE table_name DROP COLUMN column_name;command.

    Other workarounds:

    1. SQL> update t1 set column_to_drop = NULL;

    SQL> rename t1 to t1_base;

    SQL> create view t1 as select from t1_base;

    2. SQL> create table t2 as select from t1;

    SQL> drop table t1;

    SQL> rename t2 to t1;

    Back to top of file

    Can one rename a column in a table?

    From Oracle9i one can RENAME a column from a table. Look at this example:

    ALTER TABLE tablename RENAME COLUMN oldcolumn TO newcolumn;

    Other workarounds:

    1. -- Use a view with correct column names...

    rename t1 to t1_base;

    create view t1 as select * from t1_base;

    2. -- Recreate the table with correct column names...

    create table t2 as select * from t1;

    drop table t1;

    rename t2 to t1;

    3. -- Add a column with a new name and drop an old column...

    alter table t1 add ( newcolame datatype );

    update t1 set newcolname=oldcolname;

    http://www.orafaq.com/scripts/sql/dropcol.txthttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/scripts/sql/dropcol.txthttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    14/26

    alter table t1 drop column oldcolname;

    Back to top of file

    How can I change my Oracle password?

    Issue the following SQL command: ALTER USER IDENTIFIED BY

    /

    From Oracle8 you can just type "password" from SQL*Plus, or if you need to changeanother user's password, type "password user_name".

    Back to top of file

    How does one find the next value of a sequence?

    Perform an "ALTER SEQUENCE ... NOCACHE" to unload the unused cached sequencenumbers from the Oracle library cache. This way, no cached numbers will be lost. If

    you then select from the USER_SEQUENCES dictionary view, you will see the correcthigh water mark value that would be returned for the next NEXTVALL call.

    Afterwards, perform an "ALTER SEQUENCE ... CACHE" to restore caching.

    You can use the above technique to prevent sequence number loss before a

    SHUTDOWN ABORT, or any other operation that would cause gaps in sequence

    values.

    Back to top of file

    Workaround for snapshots on tables with LONG columns

    You can use the SQL*Plus COPY command instead of snapshots if you need to copyLONG and LONG RAW variables from one location to another. Eg:

    COPY TO SCOTT/TIGER@REMOTE -

    CREATE IMAGE_TABLE USING -

    SELECT IMAGE_NO, IMAGE -

    FROM IMAGES;

    Note: If you run Oracle8, convert your LONGs to LOBs, as it can be replicated.

    Contents of this Page

    Can I Update From Another Table ?

    Can I Remove Duplicate Rows ?

    What is ROWID good for ?

    http://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#UpdFromOther%23UpdFromOtherhttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#RmDup%23RmDuphttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_r.html#ROWIDhttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.orafaq.com/faqsql.htm#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#UpdFromOther%23UpdFromOtherhttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#RmDup%23RmDuphttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_r.html#ROWID
  • 8/6/2019 Most Useful SQL Queries

    15/26

    What is ROWNUM good for ?

    Views

    Questions on views have moved to another page.

    Can I implement Tree Structured Queries ?

    How can I get information on the row based on group information ? How can I get a name for a temporary table that will not clash ?

    How can I discover what tables, columns, etc are there ?

    How can I rename a column ?

    Is there a formatter for SQL or PL/SQL ?

    How come records for the date I want are missing ?

    How can I interpret a two digit year after 2000 ?

    What is a cluster ?

    How do I control which rollback segment I use ?

    How do order a union ?

    Who are SCOTT, SYSTEM and SYS ?

    How do I avoid blowing rollback segments ?

    How can I restore passwords ? Not Formatted Yet

    Can I Update From Another Table ?

    Yes. For example, if we had a table DEPT_SUMMARY, we could update the number of

    employees field as follows:

    update DEPT_SUMMARY s

    set NUM_EMPS = (

    select count(1)

    from EMP E

    where E.DEPTNO = S.DEPTNO

    );

    Back to Top of File

    Can I remove duplicate rows ?

    Yes, using the ROWID field. The ROWID is guaranteed unique. There are manyvariations on this theme, but the logic is to delete all but one record for each key

    value.

    delete from EMP E

    where not E.ROWID = (

    http://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_r.html#ROWNUMhttp://www.db.cs.ucdavis.edu/public/oracle/faq/views.htmlhttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#QryTree%23QryTreehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#RowBasedOnGroup%23RowBasedOnGrouphttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#GenTmpTbls%23GenTmpTblshttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#WhatIsThere%23WhatIsTherehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#ColRename%23ColRenamehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#SQLFmt%23SQLFmthttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#daterecmiss%23daterecmisshttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#centuryswap%23centuryswaphttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_c.html#CLUSTERhttp://www.db.cs.ucdavis.edu/public/oracle/faq/WhichRBShttp://www.db.cs.ucdavis.edu/public/oracle/faq/OrderUnionhttp://www.db.cs.ucdavis.edu/public/oracle/faq/SCOTTETChttp://www.db.cs.ucdavis.edu/public/oracle/faq/NoBlowRBShttp://www.db.cs.ucdavis.edu/public/oracle/faq/RestorePasswordshttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#NotFmt%23NotFmthttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_r.html#ROWIDhttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_r.html#ROWNUMhttp://www.db.cs.ucdavis.edu/public/oracle/faq/views.htmlhttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#QryTree%23QryTreehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#RowBasedOnGroup%23RowBasedOnGrouphttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#GenTmpTbls%23GenTmpTblshttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#WhatIsThere%23WhatIsTherehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#ColRename%23ColRenamehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#SQLFmt%23SQLFmthttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#daterecmiss%23daterecmisshttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#centuryswap%23centuryswaphttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_c.html#CLUSTERhttp://www.db.cs.ucdavis.edu/public/oracle/faq/WhichRBShttp://www.db.cs.ucdavis.edu/public/oracle/faq/OrderUnionhttp://www.db.cs.ucdavis.edu/public/oracle/faq/SCOTTETChttp://www.db.cs.ucdavis.edu/public/oracle/faq/NoBlowRBShttp://www.db.cs.ucdavis.edu/public/oracle/faq/RestorePasswordshttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#NotFmt%23NotFmthttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_r.html#ROWID
  • 8/6/2019 Most Useful SQL Queries

    16/26

    select min(F.ROWID)

    from EMP F

    where F.EMP_ID = E.EMP_ID

    );

    Back to Top of File

    Can I implement Tree Structured Queries ?

    Yes! This is commonly asked by those migrating from non-RDBMS apps. This isdefinitely non-relational (enough to kill Codd and then make him roll in his grave)

    and is a feature I have not seen in the competition.

    The definitive example is in the example SCOTT/TIGER database, when looking at

    the EMP table (EMPNO and MGR columns). The MGR column contains the employeenumber of the "current" employee's boss.

    You have available an extra pseudo-column, LEVEL, that says how deep in the treeyou are. Oracle can handle queries with a depth up to 255.

    select LEVEL, EMPNO, ENAME, MGRfrom EMP

    connect by prior EMPNO = MGRstart with MGR is NULL;

    You can get an "indented" report by using the level number to substring or lpad aseries of spaces and concatenate that to the string.

    select lpad(' ', LEVEL * 2) || ENAME ........

    You use the start with clause to specify the start of the tree(s). More than one record

    can match the starting condition.

    One disadvantage of a "connect by prior" is that you cannot perform a join to other

    tables. Still, I have not managed to see anything else like the "connect by prior" inthe other vendor offerings and I like trees. Even trying to doing this

    programmatically in embedded SQL is difficult as you have to do the top level query,for each of them open a cursor to look for lower level rows, for each of these.......

    soon you blow the cursor limit for your installation.

    The way around this is to use PL/SQL, open the driving cursor with the "connect by

    prior" statement, and the select matching records from other tables on a row-by-row

    basis, inserting the results into a temporary table for later retrieval.

    http://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_s.html#SCOTThttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_s.html#SCOTT
  • 8/6/2019 Most Useful SQL Queries

    17/26

    Note that you can't trick Oracle by using CONNECT BY PRIOR on a view that does thejoin.

    Back to Top of File

    How can I get information on the row based on group information ?

    Imagine we have the EMP table and want details on the employee who has the

    highest salary. You need to use a subquery.

    select e.ENAME, e.EMPNO, e.SAL

    from EMP e

    where e.SAL in (

    select max (e2.SAL)

    from EMP e2

    );

    You could get similar info on employees with the highest salary in their departments

    as follows

    select e.ENAME, e.DEPTNO, e.SAL

    from EMP e

    where e.SAL = (

    select max (e2.SAL)

    from EMP e2

    where e2.DEPTNO = e.DEPTNO

    );

    Back to Top of File

    How can I get a name for a temporary table that will not clash ?

    Use a sequence, and use the number to help you build the temporary table name.Note that SQL-92 is developing specific constructs for using temporary tables.

    Back to Top of File

    http://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    18/26

    How can I discover what tables, columns, etc are there ?

    Oracle maintains a live set of views that you can query to tell you what you have

    available. In V6, the first two to look at are DICT and DICT_COLUMNS which act as adirectory of the other dictionary views. It is a good idea to be familiar with these.

    Not all of these views are accessible by all users. If you are a DBA you should alsocreate private DBA synonyms by running $ORACLE_HOME/rdbms/admin/dba_syn.sql

    in your account.

    Back to Top of File

    How can I rename a column ?

    There is no way a column can be renamed using normal SQL. It can be done

    carefully by the DBA playing around with internal SYS dictionary tables and bouncingthe database, but this is not supported. (I have successfully done it in V4 thru V7).

    Do backup the database first unless you feel brave. I've written a quick and dirtyscript rncol.sql to do this. If you can't figure out how to use it from the source you

    definitely should not run it.

    You can use a similar dirty trick for changing ownership of tables if storage space islimited.

    Back to Top of File

    Is there a formatter for SQL or PL/SQL ?

    There are a number of "beautifiers" for various program languages. The cb andindent programs for the C language spring to mind (although they have slightlydifferent conventions). As far as I know there is no PD formatter for SQL available.

    Given that there are PD general SQL parsers and that the SQL standards are draftedin something close to BNF, maybe someone could base a reformatter based on the

    grammar.

    Note that you CANNOT use cb and indent with Pro*C as both these programs will

    screw up the embedded SQL code.

    I have recently heard that Kumaran Systems (see Vendor list) have a Forms PL/SQL

    and SQL formatter, but I do not now if they have unbundled it.

    Back to Top of File

    http://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_d.html#DICThttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFileftp://ftp.bf.rmit.edu.au/pub/Oracle/sources/dba/rncol.sqlhttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/vendors.htmlhttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_d.html#DICThttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFileftp://ftp.bf.rmit.edu.au/pub/Oracle/sources/dba/rncol.sqlhttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/vendors.htmlhttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    19/26

    How come records for the date I want are missing ?

    You are trying to retrieve data based on something like:

    SELECT fld1, fld2 FROM tbl WHERE date_field = '18-jun-60'

    You *know* there are records for that day - but none of them are coming back to

    you.

    What has happened is that your records are not set to midnight (which is the default

    value if time of day not specified).

    You can either use to_char and to_date functions, which can be a bad move

    regarding SQL performance, or you can sayWHERE date_field >= '18-jun-60' AND date_field < '19-jun-60'

    An alternative could be something like

    WHERE date_field between '18-jun-1960'

    AND to_date('23:59:59 18-jun-60', 'HH24:......YY')

    ;

    Back to Top of File

    How can I interpret a two digit year after 2000 ?

    When converting to dates from characters when you only have two characters for the

    year, the picture format "RR" will be interpreted as the year based on a guess thatthat date is between 1950 and 2049.

    Back to Top of File

    What are these V$ tables?

    There are a number of tables/views beginning with V$ that hold gory details for

    performance monitoring. These are not guaranteed to be stable from minor releaseto minor release and are for DBAs only.

    There are usually no real underlying tables (unlike SYS.OBJ$) and are dummied upby the RDBMS kernel software in much the same way that UNIX System V.4

    dummies up the files in the /proc or /dev/proc directories.

    If you have any code depending on these (and the widely used tools supplied by

    Oracle but unsupported are in this category) then you need to verify that everythingworks each time you upgrade your database. And when a major revision changes, all

    bets are off.

    http://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    20/26

    Back to Top of File

    How do I get a top ten ?

    This question often gets the response WHERE ROWNUM (

    select count(1)

    from table_name b

    where b.ordered_column

    < a.ordered_column )

    order by a.ordered_columnl;

    I do not believe that straight SQL is the way to go for such problems when you have

    PL/SQL available.

    My approach is to use PL/SQL instead (in SQL*Plus):

    variable tenthsal number

    declare

    n number;

    cursor c1 is

    select SAL from EMP order BY SAL desc;

    begin

    open c1;

    for n in 1..10 loop

    fetch c1 into :tenthsal;

    http://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    21/26

    end loop;

    close c1;

    end:

    /

    select * from EMP

    where SAL

  • 8/6/2019 Most Useful SQL Queries

    22/26

    select DEPTNO, DNAME from DEPT

    union

    select EMPNO, ENAME from EMP

    order by 2;

    Back to Top of File

    Who are SCOTT, SYSTEM and SYS ?

    These three users are common in many databases. See the glossary entries underSCOTT, SCOTT and SYS. Another common user/password is PLSQL/SUPERSECRET

    used for PL/SQL demo stuff.

    Back to Top of File

    How can I avoid blowing rollback segments ?

    The simple answer is make sure you have them big enough and keep yourtransactions small, but that is being a smartarse.

    More recent versions of Oracle have an option for the session that you can set thatcommits every so many DML statements. This is OK except for where you are doing

    your work in a single statement rather than using PL/SQL and a loop construct.

    Imagine you have a HUGE table and need to update it, possibly updating the key.

    You cannot update it in one go because your rollback segments are too small. Youcannot open a cursor and commit every n records, because usually the cursor will

    close. You cannot have a number of updates of a few records each because the keysmay change - causing you to visit records more than once.

    The solution I have used was to have one process select ROWID from theappropriate rows and pump these (via standard I/O) to another process that looped

    around reading ROWIDs from standard input, updating the appropriate record andcommitting every 10 records or so. This was very easy to program and also was

    quite fast in execution. The number of locks and size of rollback segments requiredwas minimal.

    If you are writing in Pro*C and use MODE=ORACLE, there are ways around it too,but not if you are using MODE=ANSI.

    Back to Top of File

    http://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_s.html#SCOTThttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_s.html#SYSTEMhttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_s.html#SYShttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_s.html#SCOTThttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_s.html#SYSTEMhttp://www.db.cs.ucdavis.edu/public/oracle/faq/gloss_s.html#SYShttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFilehttp://www.db.cs.ucdavis.edu/public/oracle/faq/sql.html#TopOfFile%23TopOfFile
  • 8/6/2019 Most Useful SQL Queries

    23/26

    How can I restore passwords ?

    OK, so this is really a DBA question, but it is worth putting in here because it

    involves SQL regardless of interface.

    First, look at the PASSWORD column in DBA_USERS. It looks like gobbledygookbecause it is an encrypted password. However you can use this if you have saved it

    somewhere else. Say you want to impersonate a user in a batch run overnight. Firststash the gobbledygook password away somewhere, grant connect to the user

    identified by some password you know and then run your batches using the newknown password.

    To restore the password to what it was use the following syntax (which I think isundocumented).

    grant connect to SCOTT identified by passwords GOBBLEDYGOOK;

    Note especially the S on the end of PASSWORDS.

    Question: What versions are loaded on my machine ?

    SQL> select substr(product,1,15) product,substr(version,1,15)

    version,substr(status,1,15) statusfrom product_component_version

    PRODUCT VERSION STATUS

    --------------- --------------- ---------------NLSRTL 3.4.1.0.0 Production

    Oracle8i Enterp 8.1.7.3.0 ProductionPL/SQL 8.1.7.3.0 Production

    TNS for 32-bit 8.1.7.3.0 Production

    also,

    SQL> select * from v$version where banner like 'Oracle%';

    BANNER----------------------------------------------------------------

    Oracle8i Enterprise Edition Release 8.1.7.3.0 - Production

    Question: What Applications/Versions/Patch Levels are loaded on my machine ?

    this query gives more details than the one below

    select substr(a.APPLICATION_NAME,1,60) "Application Name", substr(i.PRODUCT_VERSION,1,4) "Version"

  • 8/6/2019 Most Useful SQL Queries

    24/26

    , i.PATCH_LEVEL "Patch Level", i.APPLICATION_ID "Application ID"

    , i.LAST_UPDATE_DATE "Last Update"from APPS.FND_PRODUCT_INSTALLATIONS i

    , APPS.FND_APPLICATION_ALL_VIEW awhere i.APPLICATION_ID = a.APPLICATION_ID

    -- not all applications update the next field correctly-- and i.PATCH_LEVEL like '11i%'

    -- these are the applications that concern me most-- and i.APPLICATION_ID in ('0','140','260','101','200','275','201','222','185')

    order by a.APPLICATION_NAME

    Question: What patches are loaded on my machine ?

    select patch_name,

    patch_type,applied_patch_id,

    rapid_installed_flag,maint_pack_level

    from ad_applied_patcheswhere patch_name like '%'

    order by 1

    How do I obtain CCID / Chart of Account data for General Ledger

    select

    substr(gl.code_combination_id,1,5) ccid,

    substr(gl.segment1,1,5) Auth,substr(gl.segment2,1,8) Account,

    substr(gl.segment3,1,5) RC,

    substr(gl.segment4,1,5) Func,substr(gl.segment5,1,5) Job

    FROM gl.gl_code_combinations glorder by code_combination_id

    Question: How many transactions exist by GL DATE (period) ?

    select gl_date,count(gl_date)

    from ra_cust_trx_line_gl_dist_Allwhere account_class = 'REV'

    group by gl_date

    Question: What is my current GL SET OF BOOKS

    select SET_OF_BOOKS_ID,NAME,SHORT_NAME,

    CHART_OF_ACCOUNTS_ID,CURRENCY_CODE,

    PERIOD_SET_NAME,ACCOUNTED_PERIOD_TYPE,

  • 8/6/2019 Most Useful SQL Queries

    25/26

    LATEST_OPENED_PERIOD_NAME,substr(DESCRIPTION,1,30) description from gl_sets_of_books

    Question: What DB version is on my machine ?

    SQL> VARIABLE VERSION VARCHAR2(50)SQL> VARIABLE COMPATIBILITY VARCHAR2(50)

    SQL> EXEC DBMS_UTILITY.DB_VERSION(:VERSION,:COMPATIBILITY)

    PL/SQL procedure successfully completed.

    SQL> PRINT VERSION

    VERSION----------------------------------------

    8.0.4.0.0

    SQL> PRINT COMPATIBILITY

    COMPATIBILITY----------------------------------------

    8.0.0

    Question: What machine or instance am I using ??

    SQL> Select name from v$database;

    NAME

    ---------ARGP

    also you can use this:

    SQL> select sys_context('USERENV','DB_NAME') AS instance from dual;

    INSTANCE---------------------------------------------------------------------

    ARGP

    This variation will give you the machine name you are running on:

    SQL> Select sys_context('USERENV','TERMINAL') from dual;

    SYS_CONTEXT('USERENV','TERMINAL')

    --------------------------------------------------------------AR0669

    Question: How can I retrieve a random number ?

    SQL> select dbms_random.random from dual;

    RANDOM

  • 8/6/2019 Most Useful SQL Queries

    26/26

    ----------495129087

    Question: What patches are loaded on our machine ?

    SQL> select * from AD_APPLIED_PATCHES

    Question: Am I setup for Multi-Org ?

    select multi_org_flag from fnd_product_groups;

    Useful DATE output SQL

    This format is yymmdd = year month day | hh24mi = 24 hour clock and minutes

    select to_char(sysdate,'yymmddhh24mi')from dual

    TO_CHAR(SY----------

    0409141005

    select to_char(sysdate,'hh24:mi:ss')

    from dual

    TO_CHAR(--------

    10:11:14


Recommended