Most Useful Queries
Most Useful Queries
Most Useful Queries
spool oradata.txt
select 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?
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:
Choose one of the following queries to identify or remove duplicate rows from a table
leaving only unique records in the table:
Method 1:
Method 2:
SQL> create table table_name2 as select distinct * from table_name1;
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.
Create your table with a NOT NULL column (say SEQNO). This column can now be
populated with unique values:
How does one get the time difference between two date columns?
Look at this example query:
select floor(((date1-date2)*24*60*60)/3600)
floor((((date1-date2)*24*60*60) -
floor(((date1-date2)*24*60*60)/3600)*3600)/60)
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)))
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') +
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.
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:
NOW NOW_PLUS_30_SECS
-------------------- --------------------
from my_table
group by my_table_column;
count(decode(sex,'M',1,'F',1)) TOTAL
from my_emp_table
group by dept;
select f2,
from my_table
group by f2;
1, 0.1,
2, 0.2,
from my_table;
Rupak Mohan provided this solution to select the Nth row from a table:
SELECT * FROM t1 a
FROM t1 b
SELECT * FROM (
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.
SELECT f1 FROM t1
WHERE rowid = (
MINUS
Alternatively...
SELECT * FROM (
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).
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 (
MINUS
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
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
FROM emp);
SELECT *
FROM emp
) temp
WHERE MOD(temp.ROWNUM,4) = 0;
SELECT rownum, f1
FROM t1
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
Form Oracle8i one can have an inner-query with an ORDER BY clause. Look at this
example:
SELECT *
SELECT *
FROM my_table a
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 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:
from EMP
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:
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.
SELECT *
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;
ANALYST 6000
PRESIDENT 5000
SALESMAN 5600
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:
from employees;
0, 'a = b',
'a < b') from tableX;
A, decode(A, B, 'A NOT GREATER THAN B', 'A GREATER THAN B'),
Note: The decode function is not ANSI SQL and is rarely implemented in other
RDBMS offerings. It is one of the good things about Oracle, but use it sparingly if
portability 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;
How can one dump/ examine the exact content of a database column?
SELECT DUMP(col1)
FROM tab1
DUMP(COL1)
-------------------------------------
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
Other workarounds:
From Oracle9i one can RENAME a column from a table. Look at this example:
Other workarounds:
rename t1 to t1_base;
create view t1 <column list with new name> as select * from t1_base;
create table t2 <column list with new name> as select * from t1;
rename t2 to t1;
From Oracle8 you can just type "password" from SQL*Plus, or if you need to change
another user's password, type "password user_name".
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.
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 -
FROM IMAGES;
Note: If you run Oracle8, convert your LONGs to LOBs, as it can be replicated.
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
);
Yes, using the ROWID field. The ROWID is guaranteed unique. There are many
variations on this theme, but the logic is to delete all but one record for each key
value.
from EMP F
);
Yes! This is commonly asked by those migrating from non-RDBMS apps. This is
definitely 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.
You have available an extra pseudo-column, LEVEL, that says how deep in the tree
you are. Oracle can handle queries with a depth up to 255.
You can get an "indented" report by using the level number to substring or lpad a
series of spaces and concatenate that to the string.
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" in
the 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.......
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.
Note that you can't trick Oracle by using CONNECT BY PRIOR on a view that does the
join.
Imagine we have the EMP table and want details on the employee who has the
highest salary. You need to use a subquery.
from EMP e
where e.SAL in (
from EMP e2
);
You could get similar info on employees with the highest salary in their departments
as follows
from EMP e
where e.SAL = (
from EMP e2
);
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.
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 a
directory 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 also
create private DBA synonyms by running $ORACLE_HOME/rdbms/admin/dba_syn.sql
in your account.
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 bouncing
the 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 dirty
script 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 is
limited.
There are a number of "beautifiers" for various program languages. The cb and
indent programs for the C language spring to mind (although they have slightly
different 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 drafted
in 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.
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 say
WHERE date_field >= '18-jun-60' AND date_field < '19-jun-60'
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 that
that date is between 1950 and 2049.
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 release
to minor release and are for DBAs only.
There are usually no real underlying tables (unlike SYS.OBJ$) and are dummied up
by 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 everything
works each time you upgrade your database. And when a major revision changes, all
bets are off.
Back to Top of File
This question often gets the response WHERE ROWNUM <= 10 but this will not work
(except accidentally) because the ROWNUM pseudocolumn is generated before the
ORDER or WHERE clauses come into effect.
One elegant SQL-only approach (although it will be a bitch on a large table) was
suggested by [email protected]
from table_name a
where 10 > (
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.
declare
n number;
cursor c1 is
begin
open c1;
close c1;
end:
Late news: index descending hint to SQL works if you use a dummy restriction to
force use of the index. Needs V7, etc.
In SQL, you may need to control the rollback segment used as the default rollback
segment may be too small for the required transaction, or you may want to ensure
that your transaction runs in a special rollback segment, unaffected by others. The
statement is as follows:
On a related note, if all you are doing are SELECTS, it is worth telling the database of
this using the following:
(Governments around the world have been trying to figure this one out).
Say we are getting a list of names and codes and want it ordered by the name, using
both EMP and DEPT tables:
select DEPTNO, DNAME from DEPT
union
order by 2;
These three users are common in many databases. See the glossary entries under
SCOTT, SCOTT and SYS. Another common user/password is PLSQL/SUPERSECRET
used for PL/SQL demo stuff.
The simple answer is make sure you have them big enough and keep your
transactions small, but that is being a smartarse.
More recent versions of Oracle have an option for the session that you can set that
commits 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. You
cannot 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 keys
may change - causing you to visit records more than once.
The solution I have used was to have one process select ROWID from the
appropriate rows and pump these (via standard I/O) to another process that looped
around reading ROWIDs from standard input, updating the appropriate record and
committing 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 required
was 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.
OK, so this is really a DBA question, but it is worth putting in here because it
involves SQL regardless of interface.
To restore the password to what it was use the following syntax (which I think is
undocumented).
also,
BANNER
----------------------------------------------------------------
Oracle8i Enterprise Edition Release 8.1.7.3.0 - Production
select patch_name,
patch_type,
applied_patch_id,
rapid_installed_flag,
maint_pack_level
from ad_applied_patches
where patch_name like '%'
order by 1
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 gl
order by code_combination_id
select gl_date,count(gl_date)
from ra_cust_trx_line_gl_dist_All
where account_class = 'REV'
group by gl_date
select SET_OF_BOOKS_ID,
NAME,SHORT_NAME,
CHART_OF_ACCOUNTS_ID,
CURRENCY_CODE,
PERIOD_SET_NAME,
ACCOUNTED_PERIOD_TYPE,
LATEST_OPENED_PERIOD_NAME,
substr(DESCRIPTION,1,30) description from gl_sets_of_books
VERSION
----------------------------------------
8.0.4.0.0
COMPATIBILITY
----------------------------------------
8.0.0
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:
SYS_CONTEXT('USERENV','TERMINAL')
--------------------------------------------------------------
AR0669
RANDOM
----------
495129087
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