Here’s a list of 40+ Useful Oracle queries that every Oracle developer must bookmark. These queries range from date manipulation, getting server info, get execution status, calculate database size etc.
Date / Time related queries
Get the first day of the month
Quickly returns the first day of current month. Instead of current month you want to find first day of month where a date falls, replace SYSDATE with any date column/value.Code language: SQL (Structured Query Language) (sql)
SELECT TRUNC (SYSDATE, 'MONTH') "First day of current month"FROM DUAL;
Get the last day of the month
This query is similar to above but returns last day of current month. One thing worth noting is that it automatically takes care of leap year. So if you have 29 days in Feb, it will return 29/2. Also similar to above query replace SYSDATE with any other date column/value to find last day of that particular month.Code language: SQL (Structured Query Language) (sql)
SELECT TRUNC (LAST_DAY (SYSDATE)) "Last day of current month"FROM DUAL;
Get the first day of the Year
First day of year is always 1-Jan. This query can be use in stored procedure where you quickly want first day of year for some calculation.Code language: SQL (Structured Query Language) (sql)
SELECT TRUNC (SYSDATE, 'YEAR') "Year First Day" FROM DUAL;
Get the last day of the year
Similar to above query. Instead of first day this query returns last day of current year.Code language: SQL (Structured Query Language) (sql)
SELECT ADD_MONTHS (TRUNC (SYSDATE, 'YEAR'), 12) - 1 "Year Last Day" FROM DUAL
Get number of days in current month
Now this is useful. This query returns number of days in current month. You can change SYSDATE with any date/value to know number of days in that month.Code language: SQL (Structured Query Language) (sql)
SELECT CAST (TO_CHAR (LAST_DAY (SYSDATE), 'dd') AS INT) number_of_daysFROM DUAL;
Get number of days left in current month
Below query calculates number of days left in current month.Code language: SQL (Structured Query Language) (sql)
SELECT SYSDATE,LAST_DAY (SYSDATE) "Last",LAST_DAY (SYSDATE) - SYSDATE "Days left"FROM DUAL;
Get number of days between two dates
Use this query to get difference between two dates in number of days.Code language: SQL (Structured Query Language) (sql)
SELECT ROUND ( (MONTHS_BETWEEN ('01-Feb-2014', '01-Mar-2012') * 30), 0)num_of_daysFROM DUAL;</p> <p>OR</p> <p>SELECT TRUNC(sysdate) - TRUNC(e.hire_date) FROM employees;
Use second query if you need to find number of days since some specific date. In this example number of days since any employee is hired.
Display each months start and end date upto last month of the year
This clever query displays start date and end date of each month in current year. You might want to use this for certain types of calculations.Code language: SQL (Structured Query Language) (sql)
SELECT ADD_MONTHS (TRUNC (SYSDATE, 'MONTH'), i) start_date,TRUNC (LAST_DAY (ADD_MONTHS (SYSDATE, i))) end_dateFROM XMLTABLE ('for $i in 0 to xs:int(D) return $i'PASSING XMLELEMENT (d,FLOOR (MONTHS_BETWEEN (ADD_MONTHS (TRUNC (SYSDATE, 'YEAR') - 1, 12),SYSDATE)))COLUMNS i INTEGER PATH '.');
Get number of seconds passed since today (since 00:00 hr)Code language: SQL (Structured Query Language) (sql)
SELECT (SYSDATE - TRUNC (SYSDATE)) * 24 * 60 * 60 num_of_sec_since_morningFROM DUAL;
Get number of seconds left today (till 23:59:59 hr)Code language: SQL (Structured Query Language) (sql)
SELECT (TRUNC (SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_leftFROM DUAL;
Data dictionary queries
Check if a table exists in the current database schema
A simple query that can be used to check if a table exists before you create it. This way you can make your create table script rerunnable. Just replace table_name with actual table you want to check. This query will check if table exists for current user (from where the query is executed).Code language: SQL (Structured Query Language) (sql)
SELECT table_nameFROM user_tablesWHERE table_name = 'TABLE_NAME';
Check if a column exists in a table
Simple query to check if a particular column exists in table. Useful when you tries to add new column in table using ALTER TABLE statement, you might wanna check if column already exists before adding one.Code language: SQL (Structured Query Language) (sql)
SELECT column_name AS FOUNDFROM user_tab_colsWHERE table_name = 'TABLE_NAME' AND column_name = 'COLUMN_NAME';
Showing the table structure
This query gives you the DDL statement for any table. Notice we have pass ‘TABLE’ as first parameter. This query can be generalized to get DDL statement of any database object. For example to get DDL for a view just replace first argument with ‘VIEW’ and second with your view name and so.Code language: SQL (Structured Query Language) (sql)
SELECT DBMS_METADATA.get_ddl ('TABLE', 'TABLE_NAME', 'USER_NAME') FROM DUAL;
Getting current schema
Yet another query to get current schema name.Code language: SQL (Structured Query Language) (sql)
SELECT SYS_CONTEXT ('userenv', 'current_schema') FROM DUAL;
Changing current schema
Yet another query to change the current schema. Useful when your script is expected to run under certain user but is actually executed by other user. It is always safe to set the current user to what your script expects.Code language: SQL (Structured Query Language) (sql)
ALTER SESSION SET CURRENT_SCHEMA = new_schema;
Database administration queries
Database version information
Returns the Oracle database version.Code language: SQL (Structured Query Language) (sql)
SELECT * FROM v$version;
Database default information
Some system default information.Code language: SQL (Structured Query Language) (sql)
SELECT username,profile,default_tablespace,temporary_tablespaceFROM dba_users;
Database Character Set information
Display the character set information of database.Code language: SQL (Structured Query Language) (sql)
SELECT * FROM nls_database_parameters;
Get Oracle versionCode language: SQL (Structured Query Language) (sql)
SELECT VALUEFROM v$system_parameterWHERE name = 'compatible';
Store data case sensitive but to index it case insensitive
Now this ones tricky. Sometime you might querying database on some value independent of case. In your query you might do UPPER(..) = UPPER(..) on both sides to make it case insensitive. Now in such cases, you might want to make your index case insensitive so that they don’t occupy more space. Feel free to experiment with this one.Code language: SQL (Structured Query Language) (sql)
CREATE TABLE tab (col1 VARCHAR2 (10));</p> <p>CREATE INDEX idx1ON tab (UPPER (col1));</p> <p>ANALYZE TABLE a COMPUTE STATISTICS;
Resizing Tablespace without adding datafile
Yet another DDL query to resize table space.Code language: SQL (Structured Query Language) (sql)
ALTER DATABASE DATAFILE '/work/oradata/STARTST/STAR02D.dbf' resize 2000M;
Checking autoextend on/off for Tablespaces
Query to check if autoextend is on or off for a given tablespace.Code language: SQL (Structured Query Language) (sql)
SELECT SUBSTR (file_name, 1, 50), AUTOEXTENSIBLE FROM dba_data_files;</p> <p>(OR)</p> <p>SELECT tablespace_name, AUTOEXTENSIBLE FROM dba_data_files;
Adding datafile to a tablespace
Query to add datafile in a tablespace.Code language: SQL (Structured Query Language) (sql)
ALTER TABLESPACE data01 ADD DATAFILE '/work/oradata/STARTST/data01.dbf'SIZE 1000M AUTOEXTEND OFF;
Increasing datafile size
Yet another query to increase the datafile size of a given datafile.Code language: SQL (Structured Query Language) (sql)
ALTER DATABASE DATAFILE '/u01/app/Test_data_01.dbf' RESIZE 2G;
Find the Actual size of a Database
Gives the actual database size in GB.Code language: SQL (Structured Query Language) (sql)
SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_data_files;
Find the size occupied by Data in a Database or Database usage details
Gives the size occupied by data in this database.Code language: SQL (Structured Query Language) (sql)
SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_segments;
Find the size of the SCHEMA/USER
Give the size of user in MBs.Code language: SQL (Structured Query Language) (sql)
SELECT SUM (bytes / 1024 / 1024) "size"FROM dba_segmentsWHERE owner = '&owner';
Last SQL fired by the User on Database
This query will display last SQL query fired by each user in this database. Notice how this query display last SQL per each session.Code language: SQL (Structured Query Language) (sql)
SELECT S.USERNAME || '(' || s.sid || ')-' || s.osuser UNAME,s.program || '-' || s.terminal || '(' || s.machine || ')' PROG,s.sid || '/' || s.serial# sid,s.status "Status",p.spid,sql_text sqltextFROM v$sqltext_with_newlines t, V$SESSION s, v$process pWHERE t.address = s.sql_addressAND p.addr = s.paddr(+)AND t.hash_value = s.sql_hash_valueORDER BY s.sid, t.piece;
Performance related queries
CPU usage of the USER
Displays CPU usage for each User. Useful to understand database load by user.Code language: SQL (Structured Query Language) (sql)
SELECT ss.username, se.SID, VALUE / 100 cpu_usage_secondsFROM v$session ss, v$sesstat se, v$statname snWHERE se.STATISTIC# = sn.STATISTIC#AND NAME LIKE '%CPU used by this session%'AND se.SID = ss.SIDAND ss.status = 'ACTIVE'AND ss.username IS NOT NULLORDER BY VALUE DESC;
Long Query progress in database
Show the progress of long running queries.Code language: SQL (Structured Query Language) (sql)
SELECT a.sid,a.serial#,b.username,opname OPERATION,target OBJECT,TRUNC (elapsed_seconds, 5) "ET (s)",TO_CHAR (start_time, 'HH24:MI:SS') start_time,ROUND ( (sofar / totalwork) * 100, 2) "COMPLETE (%)"FROM v$session_longops a, v$session bWHERE a.sid = b.sidAND b.username NOT IN ('SYS', 'SYSTEM')AND totalwork > 0ORDER BY elapsed_seconds;
Get current session id, process id, client process id?
This is for those who wants to do some voodoo magic using process ids and session ids.Code language: SQL (Structured Query Language) (sql)
SELECT b.sid,b.serial#,a.spid processid,b.process clientpidFROM v$process a, v$session bWHERE a.addr = b.paddr AND b.audsid = USERENV ('sessionid');
- V$SESSION.SID AND V$SESSION.SERIAL# is database process id
- V$PROCESS.SPID is shadow process id on this database server
- V$SESSION.PROCESS is client PROCESS ID, ON windows it IS : separated THE FIRST # IS THE PROCESS ID ON THE client AND 2nd one IS THE THREAD id.
Last SQL Fired from particular Schema or Table:Code language: SQL (Structured Query Language) (sql)
SELECT CREATED, TIMESTAMP, last_ddl_timeFROM all_objectsWHERE OWNER = 'MYSCHEMA'AND OBJECT_TYPE = 'TABLE'AND OBJECT_NAME = 'EMPLOYEE_TABLE';
Find Top 10 SQL by reads per executionCode language: SQL (Structured Query Language) (sql)
SELECT *FROM ( SELECT ROWNUM,SUBSTR (a.sql_text, 1, 200) sql_text,TRUNC (a.disk_reads / DECODE (a.executions, 0, 1, a.executions))reads_per_execution,a.buffer_gets,a.disk_reads,a.executions,a.sorts,a.addressFROM v$sqlarea aORDER BY 3 DESC)WHERE ROWNUM < 10;
Oracle SQL query over the view that shows actual Oracle connections.Code language: SQL (Structured Query Language) (sql)
SELECT osuser,username,machine,programFROM v$sessionORDER BY osuser;
Oracle SQL query that show the opened connections group by the program that opens the connection.Code language: SQL (Structured Query Language) (sql)
SELECT program application, COUNT (program) Numero_SesionesFROM v$sessionGROUP BY programORDER BY Numero_Sesiones DESC;
Oracle SQL query that shows Oracle users connected and the sessions number for userCode language: SQL (Structured Query Language) (sql)
SELECT username Usuario_Oracle, COUNT (username) Numero_SesionesFROM v$sessionGROUP BY usernameORDER BY Numero_Sesiones DESC;
Get number of objects per ownerCode language: SQL (Structured Query Language) (sql)
SELECT owner, COUNT (owner) number_of_objectsFROM dba_objectsGROUP BY ownerORDER BY number_of_objects DESC;
Utility / Math related queries
Convert number to words
More info: Converting number into words in OracleCode language: SQL (Structured Query Language) (sql)
SELECT TO_CHAR (TO_DATE (1526, 'j'), 'jsp') FROM DUAL;
one thousand five hundred twenty-six
Find string in package source code
Below query will search for string ‘FOO_SOMETHING’ in all package source. This query comes handy when you want to find a particular procedure or function call from all the source code.Code language: SQL (Structured Query Language) (sql)
--search a string foo_something in package source codeSELECT *FROM dba_sourceWHERE UPPER (text) LIKE '%FOO_SOMETHING%'AND owner = 'USER_NAME';
Convert Comma Separated Values into Table
The query can come quite handy when you have comma separated data string that you need to convert into table so that you can use other SQL queries like IN or NOT IN. Here we are converting ‘AA,BB,CC,DD,EE,FF’ string to table containing AA, BB, CC etc. as each row. Once you have this table you can join it with other table to quickly do some useful stuffs.Code language: SQL (Structured Query Language) (sql)
WITH csvAS (SELECT 'AA,BB,CC,DD,EE,FF'AS csvdataFROM DUAL)SELECT REGEXP_SUBSTR (csv.csvdata, '[^,]+', 1, LEVEL) pivot_charFROM DUAL, csvCONNECT BY REGEXP_SUBSTR (csv.csvdata,'[^,]+', 1, LEVEL) IS NOT NULL;
Find the last record from a table
This ones straight forward. Use this when your table does not have primary key or you cannot be sure if record having max primary key is the latest one.Code language: SQL (Structured Query Language) (sql)
SELECT *FROM employeesWHERE ROWID IN (SELECT MAX (ROWID) FROM employees);</p> <p>(OR)</p> <p>SELECT * FROM employeesMINUSSELECT *FROM employeesWHERE ROWNUM < (SELECT COUNT (*) FROM employees);
Row Data Multiplication in Oracle
This query use some tricky math functions to multiply values from each row. Read below article for more details.
More info: Row Data Multiplication In OracleCode language: SQL (Structured Query Language) (sql)
WITH tblAS (SELECT -2 num FROM DUALUNIONSELECT -3 num FROM DUALUNIONSELECT -4 num FROM DUAL),sign_valAS (SELECT CASE MOD (COUNT (*), 2) WHEN 0 THEN 1 ELSE -1 END valFROM tblWHERE num < 0)SELECT EXP (SUM (LN (ABS (num)))) * valFROM tbl, sign_valGROUP BY val;
Generating Random Data In Oracle
You might want to generate some random data to quickly insert in table for testing. Below query help you do that. Read this article for more details.
More info: Random Data in OracleCode language: SQL (Structured Query Language) (sql)
SELECT LEVEL empl_id,MOD (ROWNUM, 50000) dept_id,TRUNC (DBMS_RANDOM.VALUE (1000, 500000), 2) salary,DECODE (ROUND (DBMS_RANDOM.VALUE (1, 2)), 1, 'M', 2, 'F') gender,TO_DATE (ROUND (DBMS_RANDOM.VALUE (1, 28))|| '-'|| ROUND (DBMS_RANDOM.VALUE (1, 12))|| '-'|| ROUND (DBMS_RANDOM.VALUE (1900, 2010)),'DD-MM-YYYY')dob,DBMS_RANDOM.STRING ('x', DBMS_RANDOM.VALUE (20, 50)) addressFROM DUALCONNECT BY LEVEL < 10000;
Random number generator in Oracle
Plain old random number generator in Oracle. This ones generate a random number between 0 and 100. Change the multiplier to number that you want to set limit for.Code language: SQL (Structured Query Language) (sql)
--generate random number between 0 and 100SELECT ROUND (DBMS_RANDOM.VALUE () * 100) + 1 AS random_num FROM DUAL;
Check if table contains any data
This one can be written in multiple ways. You can create count(*) on a table to know number of rows. But this query is more efficient given the fact that we are only interested in knowing if table has any data.Code language: SQL (Structured Query Language) (sql)
SELECT 1FROM TABLE_NAMEWHERE ROWNUM = 1;
If you have some cool query that can make life of other Oracle developers easy, do share in comment section.
Hi Viral Patel,Thanks a LOT for providing these useful Oracle Queries for us.Please keep up the Good Work.All the Best.
very useful queries, thanks for sharing :)
Excellent compilation of queries Viral!.
You rock bhai :)
using above database queries i will solve db related problems in my many project.
Good Job Viral, really useful article. Looking forward to more such stuff. :)
Really Some useful queries …
Can you please give 50 different views of Data Dictionary in form of SQL Queries?
You can use USER_VIEWS to see the available views with the SCHEMA.
Describe the view and see the columns..
Use the column name to get the details
I have a requirement.
I have 5 attribute columns corresponding 5 days of the week from Monday to Friday.
The attribute values can be Yes or No.
If Wednesday and Friday are set to Yes, I need a query to retrieve all the wednesdays and Fridays from a given date to sysdate.
Similarly, If Monday, Wednesday and Thursday are set to Yes, I need all the Mondays, Wednesdays and Thursday from a given date(passed as parameter) to sysdate.
Could anyone please help me in writing this query?
for David’s question on April 17th..I’m sure this could probably be cleaned up some more and I see that the Friday portion of this returns a friday before 01/01/2012 but this is a start…
note, the “<=” should be <=
or "less than or equal to"
it didn't format correctly in my cut/paste
Hello and thanks Viral, I think you can include a query which return number of columns result of a dynamic query, these usefull when you send a script inside a function and you don’t know exactly how many columns you obtain.
Once again thaks for your effort.
Thank you dear for sharing knowledge
in response to David’s query….cleaned up the dates that come out prior to the date entered as well as if you enter a date in the future. Both SQL and PL/SQL solutions are below. note, greater than, equal, less than formatting might be affected by the tags
ans for q 8
WITH csv AS(
select (to_char(trunc(sysdate,’MONTH’),’MM’)-level) as Mnt from dual where (to_char(trunc(sysdate,’MONTH’),’MM’)-level) >-1 connect by level < 20 )
select add_months(trunc(sysdate,'MONTH'),-csv.Mnt), add_months(trunc(sysdate,'MONTH'),-csv.Mnt)-1 from dual ,csv
pl answer to my query, I have a table emp (empno,login)—- in my table an employee can login many times in a day. Assume each employee 4 times logged into the table with employeeno 11,22,33,44 since one week. Now I want a query to list all employees 11,22,33,44 once per day.(total I need to get 7 records for each employee)….
please suggest the ansewr
please try this !
select empno,login from emp where to_Date(login) >= to_date(sysdate – 7) order by login desc;
very usefull !
I really appreciate that !
I want to select 1st,10th and 20th of the month by giving 1,10,20 as the parameters. is there the a possible way?
Thanks for sharing the above queries. very useful.
I need one query which will give me the last month salary drawn of each employee. All employee last month salary is not same. I tried the same
the below query works for unique record but not for the last
select * From demo_orders a
where order_id not IN (
select order_id from demo_orders b
where b.customer_id = a.customer_id and rownum=1
logically I want the
select * From demo_orders a
where order_id IN (
select b.order_id from demo_orders b
where a.customer_id = b.customer_id and rownum=1 order by a.customer_id );
very usefull …… looking forward to see much stufff……………………………
Hi can u pls share me any queries to find the table name if i know the table header. As i’m beginner unable to find it
How to find a value in a pipe delimiter value.
For ex: Assume that we have a column A and B. In A column i have value ‘A1’ and in B column i have a value like ‘A1|B1|C1|D1’. Now i have to search A1 in B column. Please note that: A and B columns are in different table.
Please help me to optimize following code as it is taking a lot of time to execute
:select distinct Cust_no_717 from (select a1.cust_no_717, a1.cust_cc_no_717, a1.cust_long_name_717 from customer a1 where a1.cust_client_717 LIKE ‘%’ UNION select a2.cust_no_717, a2.cust_cc_no_717, a2.cust_long_name_717 From Customer a2, alias_connector where ( connection_alias_778 like ‘%’ and (connection_status_778 =’BA’) and connection_cust_no_778 = a2.cust_no_717))
kindly help me to find last one hour and previous day database increased or decreased size
i have tables
CREATE TABLE Classes (
CONSTRAINT pkClasses PRIMARY KEY (className),
CHECK (typeClass IN (‘bb’, ‘bc’))
CREATE TABLE Ships
CONSTRAINT pkShips PRIMARY KEY (shipName),
CONSTRAINT fkClasses FOREIGN KEY (shipClass) REFERENCES Classes (className)
i want Find for each class, the year when the latest ship of that class was launched. Order the results by the name of the class.
I have one doubt in oracle.I sent on query.I need last one hour data on that query.
action_view.string_value AS action,
to_char(to_date(‘1970-01-01’, ‘YYYY-MM-DD’) + (action_view.audittime/ 86400000),’MM-DD-YYYY HH24:MI:SS’) as audittime
SUBSTR(action_path.string_value,instr(action_path.string_value,’cm:’,-1)+3) AS FileName,
action_path.string_value AS path
FROM ALFDBSPRFSCMA.cisco_audit_entry_action_view action_view,
WHERE action_view.id =action_path.id
AND action_view.id =type_view.id
AND action_path.string_value LIKE (‘/app:company_home/st:sites/cm:nextgen-edcs/cm:documentLibrary/%’)
AND action_view.userid != ‘admin’
AND type_view.string_value =’cs:ciscodoc’
AND action_view.string_value != ‘READ’
We are showing audit time format like mentioned in green color. The yellow color condition should be last one hour from sys time.
action_view.audittime > ((sysdate – to_date(’01-JAN-1970′,’DD-MON-YYYY’))-5) * (86400000)+to_number(to_char(systimestamp,’FF3′)) but this is not working properly.
Very nice work. Thanks a lot…
Well can you please have a look on 7th query. I think we need to add to_date function to months_between function.
please give me a clarification on this;
if we give startup command when instance is in idle condition, what happens to database. please provide me answer urgent
meaning of queries
I am looking to show the remaining Monday’s in a year and I have the following SQL which shows all the Mondays in a year. How can I change it to only show the remaining Mondays? TIA
SELECT TRUNC (SYSDATE, ‘YEAR’) + LEVEL – 1 the_date from dual
WHERE TO_CHAR (TRUNC (SYSDATE, ‘YEAR’) + LEVEL – 1, ‘Dy’) IN (‘Mon’)
CONNECT BY LEVEL <= LAST_DAY (SYSDATE) – TRUNC (SYSDATE, 'YEAR') + 1;
I just vist your side i realy like this queries ..losts of thanks for shaering this like queries .
How convert latter one into 1 in oracle without using any Comparision condations
i.e case ,decode.
Hi, thanks for share the information with us.. keep update your blogs.
Very useful…Thank u so much.
Please give me a query to find
1. how long the database or application has used in a particular day.
2. Most visited pages in the application.
Hello guys please tell me the query to get the output like the below:
Valuable information thanks for sharing
Create a query that displays the employees’ names, job and hire date also display a column with the name “new hire date” in which increase 6 months in the hire date of salesman , 2 months in the hire date of clerk, 1 months in the hire date of president
anyone help me to write a query to find data fro 1st to last of the month. like
from dual table
SELECT TRUNC(SYSDATE, ‘MM’) + LEVEL – 1 AS day
CONNECT BY TRUNC(TRUNC(SYSDATE, ‘MM’) + LEVEL – 1, ‘MM’) = TRUNC(SYSDATE, ‘MM’)
Thanks a million buddy. its very helpfull.
Awesome Stuff Viral Patel. Simply Superb.Thanks a lottttttt
Let you have a bright future ahead
Hi, Thanks for sharing the information. Reading this article gave me many things to think about.
Query #30 is missing a match on username. Please add
AND A.username = b.username so that you don’t get colliding SIDs of different users.
Very useful one
i have the db capacity script but it has to execute on the last date of every month
is there is any automatic script,
thanks in advance
can someone help me how to do query for insert,delete,select, and update table?
Want to write a procedure count the words in a given string
need help to keep birthdates in excel
Can anyone tell me how to display count of day wise total employees where day should start from Monday