Professional Documents
Culture Documents
Page 1
1.0 Introduction
Page 2
1.0 Introduction
SELECT
INTO
FROM
WHERE
AND/OR
GROUP BY
HAVING
CONNECT BY
FOR UPDATE OF
ORDER BY
SELECT sal,
Job,
ename,
dept
FROM emp
WHERE sal > any
(SELECT sal
FROM emp
WHERE deptno = 30)
ORDER BY sal;
SELECT ename,
dept
FROM emp
SELECT ename
FROM emp
WHERE empno = '1232'
Or
SELECT ename
FROM emp
WHERE empno = :1
Page 5
SELECT ename
FROM emp e,
dept d
WHERE e.empno = d.empno(+)
SELECT count(*)
FROM oe o,
oe_link l,
oe_link_name n
WHERE o.oe = l.oe
AND l.name = n.name
Page 6
Page 7
See appendix A for a listing of the predicate
scoring system.
Indexes :
unique on oe(id)
unique on oe_link(oe)
unique on oe_link_name(name)
non unique on oe(oe)
SELECT count(*)
FROM oe_link l,
oe_link_name n,
oe o
WHERE o.oe = l.oe
AND l.name = n.name
SELECT count(*)
FROM oe o,
oe_link l,
oe_link_name n
WHERE o.oe = l.oe
AND l.name = n.name
SELECT id,
oe
FROM oe
WHERE to_char(id) = 1232
Page 7
Time 97 secs.
whereas
SELECT id,
oe
FROM oe
WHERE id = 1232
Time .4 secs.
SELECT id,
oe
FROM oe
WHERE id+1 = 1233
SELECT *
FROM oe
WHERE trunc(timestamp) = '26-MAR-91'
SELECT *
FROM oe
WHERE timestamp between '26-mar-91'
AND '27-mar-91'
SELECT *
FROM oe
WHERE timestamp >= to_date('26-mar-91:00:00',
'dd-mon-yy:hh24:mi')
AND timestamp < to_date('27-mar-91:00:00',
'dd-mon-yy:hh24:mi')
The first one when run takes 240 seconds to
produce a result.
Page 8
Page 9
a)
SELECT *
FROM job
WHERE db_id||job_no = 'AZ0100201'
b)
SELECT *
FROM job
WHERE db_id = 'AZ'
AND job_no = '0100201'
SELECT deptno
FROM dept
indexes
SELECT deptno
FROM dept
WHERE deptno = to_char(1324)
SELECT deptno
FROM dept
WHERE deptno = '1324'
Char char||''
number number+0
date add_months(date,0)
SELECT deptno
FROM dept
WHERE nvl(deptno,0) = '1234'
SELECT p.name
FROM people p,
job j
WHERE p.name = j.name(+)
AND j.name is null
fred the 27
1 record selected.
SELECT name
FROM people
WHERE name not in
(SELECT name
FROM job)
fred the 27
1 record selected.
SELECT name
FROM people p
where not name in
(SELECT name
FROM job j
WHERE p.name = j.name)
fred the 27
1 record selected.
1 record selected.
SELECT 'x'
FROM dual
WHERE exists
( SELECT 'x'
FROM job
where name = 'fred the 45')
1 record selected.
SELECT 'x'
FROM dual
WHERE exists
(SELECT 'x'
FROM job
WHERE name = 'fred the 34')
SELECT 'x'
FROM dual
WHERE exists
(SELECT 'x'
FROM job
WHERE name = 'fred the 9999')
Page 13
missing entities.
SELECT p.name
FROM people p,
job j
WHERE p.name = j.name(+)
AND j.name is null
SELECT name
FROM people
WHERE not name in
(SELECT name
FROM job)
SELECT name
FROM people p
WHERE not name in
(SELECT name
FROM job j
WHERE p.name = j.name)
Step 1
Step 2
Step 3
Update Target_Table
Set Target_Field = (Select Source_Information
From Source_Table
Where Source_Table.Key =
Target_Table.Key)
Where exists (Select 'x'
From Source_Table
Where Source_Table.Key =
Target_Table.Key)
Declare
Cursor Source is
Select *
From Source_Table;
Begin
For Row in Source Loop
Update Target_Table
Set Target_Field = Row.Source_Information
Where Key = Row.Key;
End Loop;
Exception
When OTHERS Then
Null;
End;
on column COMM
SELECT *
FROM emp
WHERE comm is NULL
SELECT *
FROM emp
WHERE comm is not NULL
SELECT *
FROM emp
WHERE comm > -0.01
SELECT job,
avg(sal)
FROM emp
GROUP BY job
HAVING job = 'president'
OR job = 'manager'
SELECT job,
avg(sal)
FROM emp
WHERE job = 'president'
OR job = 'manager'
GROUP BY job
SELECT ename
FROM emp
WHERE deptno=20
AND job='manager'
SELECT *
FROM emp
WHERE job='manager'
AND deptno > 10
indexes:
SELECT ename
FROM emp
WHERE sal > 1
AND empno > 1
indexes :
SELECT ename
FROM emp
WHERE sal = 3000
AND empno = 7902
indexes :
SELECT *
FROM emp
WHERE empno =7844
AND job = 'salesman'
AND deptno = 30
AND sal = 1500
AND comm = 0
AND ename = 'turner'
indexes :
SELECT *
FROM emp
WHERE job = 'president'
AND deptno = 10
SELECT *
FROM emp
WHERE deptno = 10
AND job = 'president'
SELECT *
FROM emp
WHERE deptno = 10
SELECT *
FROM emp
WHERE job = 'analyst'
SELECT *
FROM emp
WHERE job != 'clerk'
AND deptno = 10
6.9 Or optimisation
SELECT ename,
sal,
job
FROM emp
WHERE sal = 3000
OR job = 'clerk'
index :
indexes :
Becomes :
SELECT ename,
sal,
job
FROM emp
WHERE job = 'clerk'
UNION
SELECT ename,
sal,
job
FROM emp
WHERE sal = 3000
AND job != 'clerk'
SELECT ename,
sal,
job
FROM emp
WHERE job = 'clerk'
OR sal = 3000
indexes :
Becomes :
SELECT ename,
sal,
job
FROM emp
WHERE sal = 3000
UNION
SELECT ename,
sal,
job
FROM emp
WHERE job = 'clerk'
AND sal != 3000
indexes :
SORT(UNIQUE)
MERGE JOIN
TABLE ACCESS (FULL) OF 'MEN'
SORT(JOIN)
TABLE ACCESS (FULL) OF 'JOB'
indexes :
unique on job(jobno)
non unique on job(pin)
SORT(UNIQUE)
NESTED LOOPS
TABLE ACCESS (FULL) OF 'MEN'
INDEX(RANGE SCAN) OF 'JOB_1' (NON_UNIQUE)
SELECT *
FROM dept
WHERE deptno not in
(SELECT deptno
FROM emp)
SELECT d.*
FROM dept d,emp e
WHERE d.deptno = e.deptno(+)
AND e.rowid is NULL
1 ROWID = constant
2 Unique indexed column = constant
3 entire unique concatenated index =
constant
4 entire cluster key = corresponding
cluster key in another table in
the same cluster
5 entire cluster key = constant
6 entire non-unique concatenated
index = constant
7 non-unique single column index
merge
8 most leading concatenated index =
constant
9 indexed column BETWEEN low value
AND high value, or indexed
column LIKE 'C%' (bounded range)
10 sort/merge (joins only)
11 MAX or MIN of single indexed
column
12 ORDER BY entire index
13 full table scans
14 unindexed column = constant, or
column IS NULL, or column LIKE
'%C%' (full table scan)
APPENDIX B
unique index on id
nonunique index on oe
with 2 records
With 1 record
job(job_id,name)
APPENDIX C
Update Target_Table
Set Target_Field = (Select Source_Information
From Source_Table
Where Source_Table.Key =
Target_Table.Key)
Where exists (Select 'x'
From Source_Table
Where Source_Table.Key =
Target_Table.Key)
Declare
Cursor Source is
Select *
From Source_Table;
Begin
For Row in Source Loop
Update Target_Table
Set Target_Field = Row.Source_Information
Where Key = Row.Key;
End Loop;
Exception
When OTHERS Then
Null;
End;
Performance Gain
1 INTRODUCTION
EMP.EMPNO(+) = PERS.EMPNO
AND PERS.DEPTNO(+) = DEPT.DEPTNO
AND DEPT.JOB(+) = EMP.JOB - circular outer
join relationship
APPENDIX E
The Ten commandments for fast Queries
THOU SHALL NOT ASK THE KERNEL FOR MORE THAN THOU
WANTEST.
APPENDIX F
EXPLAIN Facility
MOTIVATION
There is a need for users to be able to determine the steps the system
takes in performing various operations on a database. The EXPLAIN facility
provides users with a convenient mechanism for getting this information.
The facility stores this information in a standard database table that can
be manipulated with standard SQL statements.
SYNTAX
The following syntax is based on the syntax used by DB2 for their
EXPLAIN facility:
where
TABLE FORMATS
The core table used to represent the plan information consists of the
following fields:
TIMESTAMP - The date and time when the statement was analysed.
REMARKS - Any comment the user wishes to associate with this step of
the analysis.
OPERATION - the name of the operation being performed. The following table
provides a listing of the operations described by the facility.
Operation Description
---------------------------------------------------------------
And-Equal A retrieval utilising intersection of
rowids from index searches
Connect by A retrieval that is based on a tree walk
Concatenation A retrieval from a group of tables. It is
essentially a UNION ALL operation of the
sources. Used for OR operations.
Counting A node that is used to count the number of
rows returned from a table. Used for queries
that use the ROWNUM meta-column.
Filter A restriction of the rows returned from a table
First Row A retrieval of only the first row
For Update A retrieval that is used for updating
Index A retrieval from an index
Intersection A retrieval of rows common to two tables
Merge Join A join utilising merge scans
Minus A retrieval of rows in Source 1 table but not in
Source 2 table
Nested Loops A join utilising nested loops. Each
value in the
first subnode is looked up in the second subnode.
This is often used when one table in a join is
indexed and the other is not.
Project A retrieval of a subset of columns from a table
Remote A retrieval from a database other than the current
database
Sequence An operation involving a sequence table
Sort A retrieval of rows ordered on some column or group
of columns
Table A retrieval from a base table
Union A retrieval of unique rows from two tables
View A retrieval from a virtual table
-------------------------------------------------------------------
Note that the operation shown when counting the number of rows
returned by a query (i.e. select count(*)) is SORT. This is due to
the way that COUNT is implemented internally. The table will not
really be sorted.
OBJECT_NODE - the name of the node that owns the database object.
OBJECT_OWNER - the name of the schema the owns the database object.
POSITION - the position this database object occupies for the previous
operation.
OTHER - other information that is specific to the row source that a user
may find useful. For example, the select statement to a remote node, etc.
An SQL script to create this table resides in file xplainpl.sql in the same
directory containing the file catalog.sql. This table must reside in the
current schema unless you use the optional INTO clause of the EXPLAIN
command.
EXAMPLES
EXPLAIN PLAN
SET STATEMENT_ID = 'query1'
INTO QUERY_PLANS
FOR SELECT * FROM T1,T2,T3 WHERE T1.F1 = T2.F1 AND T2.F2 = T3.F2;
8 RECORDS selected
EXPLAIN PLAN
SET STATEMENT_ID = 'query2'
INTO QUERY_PLANS
FOR SELECT * FROM T1 WHERE F1 > 1;
2 RECORDS selected
EXPLAIN PLAN
SET STATEMENT_ID = 'query3'
INTO QUERY_PLANS
FOR SELECT F1 FROM T1 WHERE F1 > 1;
1 RECORDS selected
EXPLAIN PLAN
SET STATEMENT_ID = 'query4'
INTO QUERY_PLANS
FOR SELECT AVG(F1),F2 FROM T1 GROUP BY F2;
2 RECORDS selected
EXPLAIN PLAN
SET STATEMENT_ID = 'query5'
INTO QUERY_PLANS
FOR SELECT DISTINCT F1 FROM T1;
2 RECORDS selected
EXPLAIN PLAN
SET STATEMENT_ID = 'query6'
INTO QUERY_PLANS
FOR SELECT * FROM T1 WHERE F1 < ( SELECT F2 FROM T2 WHERE F1=3);
3 RECORDS selected
The final example displays a complex query whose output is sent to the
default plan table. ( It is assumed that this table has been created before
issuing the statement.)
EXPLAIN PLAN
SET STATEMENT_ID = 'query7'
FOR SELECT * FROM T1,T2 WHERE T1.F1 = T2.F1 UNION
SELECT * FROM T2,T3 WHERE T2.F1 = T3.F1;
13 RECORDS selected
UNION
SORT
DISTINCT
NEST LOOP
TABLE SCAN
BY ROWID T1
INDEX SCAN
RANGE IT1
TABLE SCAN
FULL T2
SORT
DISTINCT
MERGE JOIN
SORT
JOIN
TABLE SCAN
FULL T2
SORT
JOIN
TABLE SCAN
FULL T3
13 RECORDS selected
Oracle SQL FAQ
$Date: 15-Jul-2003 $
$Revision: 1.90 $
$Author: Frank Naudé $
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?
Back to Oracle FAQ Index
What is SQL and where does it come from?
Structured Query Language (SQL) is a language that provides an interface to relational database systems.
SQL was developed by IBM in the 1970s for use in System R, and is a de facto standard, as well as an ISO
and ANSI standard. SQL is often pronounced SEQUEL.
In common usage SQL also encompasses DML (Data Manipulation Language), for
INSERTs, UPDATEs, DELETEs and DDL (Data Definition Language), used for creating
and modifying tables and other database structures.
The development of SQL is governed by standards. A major revision to the SQL
standard was completed in 1992, called SQL2. SQL3 support object extensions and
are (partially?) implemented in Oracle8 and 9.
Back to top of file
What are the difference between DDL, DML and DCL
commands?
DDL is Data Definition Language statements. Some examples:
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 any characters. 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:
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 the joined 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 columns
should 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:
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 date itself.
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 or seconds to the date. Look at these
examples:
SQL> select sysdate, sysdate+1/24, sysdate +1/1440, sysdate + 1/86400 from
dual;
NOW NOW_PLUS_30_SECS
-------------------- --------------------
03-JUL-2002 16:47:23 03-JUL-2002 16:47:53
Back to top of file
How does one count different data values in a column?
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 with DECODE(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
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 we select 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 <= 10
MINUS
SELECT rowid FROM t1
WHERE rownum < 10);
SELECT rownum,empno FROM scott.emp a
GROUP BY rownum,empno HAVING rownum = 4;
Alternatively...
SELECT * FROM emp WHERE rownum=1 AND rowid NOT IN
(SELECT rowid FROM emp WHERE rownum < 10);
Please note, there is no explicit row order in a relational database. However, this query 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 <= 7
MINUS
SELECT rowid FROM tableX
WHERE rownum < 5);
Please note, there is no explicit row order in a relational database. However, this query is quite fun and may
even help in the odd situation.
Back to top of file
How does one select EVERY Nth row from a table?
One can easily select all even, odd, or Nth rows from a table using SQL queries like this:
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 this example:
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)
FROM my_table b
WHERE b.maxcol >= a.maxcol)
ORDER BY maxcol DESC;
Back to top of file
How does one code a treestructured 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-referencing
relation (EMPNO and MGR columns). This table is perfect for tesing and
demonstrating tree-structured queries as the MGR column contains the employee
number of the "current" employee's boss.
The LEVEL pseudo-column is an indication of how deep in the tree one is. Oracle can
handle 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 one record 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 this
programmatically 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 a
row-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?
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;
How does one implement IFTHENELSE in a select
statement?
The Oracle decode function acts like a procedural statement inside an SQL statement to return different
values or columns based on the values of other columns in the select statement.
Some examples:
select decode(sex, 'M', 'Male', 'F', 'Female', 'Unknown')
from employees;
select decode( GREATEST(A,B), A, 'A is greater OR EQUAL than B', 'B is greater
than A')...
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?
From Oracle8i one can DROP a column from a table. Look at this sample script, demonstrating the ALTER
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 <specific columns> from t1_base;
Can one rename a column in a table?
No, this is listed as Enhancement Request 163519. Some workarounds:
1. -- Use a view with correct column names...
rename t1 to t1_base;
create view t1 <column list with new name> as select * from t1_base;
How can I change my Oracle password?
Issue the following SQL command: ALTER USER <username> IDENTIFIED BY
<new_password>
/
From Oracle8 you can just type "password" from SQL*Plus, or if you need to change
another 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 sequence numbers 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 correct high 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 copy LONG 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.
Back to top of file
Where can one get more info about SQL?
• The SQL FAQ
• Introduction to Structured Query Language
• SQL Tutorial
• Tina London's SQL Guide