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.
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.
SELECT TRUNC (SYSDATE, 'MONTH') "First day of current month"FROM DUAL;
Code language: SQL (Structured Query Language) (sql)
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.
SELECT TRUNC (LAST_DAY (SYSDATE)) "Last day of current month"FROM DUAL;
Code language: SQL (Structured Query Language) (sql)
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.
SELECT TRUNC (SYSDATE, 'YEAR') "Year First Day" FROM DUAL;
Code language: SQL (Structured Query Language) (sql)
Similar to above query. Instead of first day this query returns last day of current year.
SELECT ADD_MONTHS (TRUNC (SYSDATE, 'YEAR'), 12) - 1 "Year Last Day" FROM DUAL
Code language: SQL (Structured Query Language) (sql)
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.
SELECT CAST (TO_CHAR (LAST_DAY (SYSDATE), 'dd') AS INT) number_of_daysFROM DUAL;
Code language: SQL (Structured Query Language) (sql)
Below query calculates number of days left in current month.
SELECT SYSDATE,LAST_DAY (SYSDATE) "Last",LAST_DAY (SYSDATE) - SYSDATE "Days left"FROM DUAL;
Code language: SQL (Structured Query Language) (sql)
Use this query to get difference between two dates in number of days.
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;
Code language: SQL (Structured Query Language) (sql)
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.
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 '.');
Code language: SQL (Structured Query Language) (sql)
SELECT (SYSDATE - TRUNC (SYSDATE)) * 24 * 60 * 60 num_of_sec_since_morningFROM DUAL;
Code language: SQL (Structured Query Language) (sql)
SELECT (TRUNC (SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_leftFROM DUAL;
Code language: SQL (Structured Query Language) (sql)
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).
SELECT table_nameFROM user_tablesWHERE table_name = 'TABLE_NAME';
Code language: SQL (Structured Query Language) (sql)
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.
SELECT column_name AS FOUNDFROM user_tab_colsWHERE table_name = 'TABLE_NAME' AND column_name = 'COLUMN_NAME';
Code language: SQL (Structured Query Language) (sql)
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.
SELECT DBMS_METADATA.get_ddl ('TABLE', 'TABLE_NAME', 'USER_NAME') FROM DUAL;
Code language: SQL (Structured Query Language) (sql)
Yet another query to get current schema name.
SELECT SYS_CONTEXT ('userenv', 'current_schema') FROM DUAL;
Code language: SQL (Structured Query Language) (sql)
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.
ALTER SESSION SET CURRENT_SCHEMA = new_schema;
Code language: SQL (Structured Query Language) (sql)
Returns the Oracle database version.
SELECT * FROM v$version;
Code language: SQL (Structured Query Language) (sql)
Some system default information.
SELECT username,profile,default_tablespace,temporary_tablespaceFROM dba_users;
Code language: SQL (Structured Query Language) (sql)
Display the character set information of database.
SELECT * FROM nls_database_parameters;
Code language: SQL (Structured Query Language) (sql)
SELECT VALUEFROM v$system_parameterWHERE name = 'compatible';
Code language: SQL (Structured Query Language) (sql)
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.
CREATE TABLE tab (col1 VARCHAR2 (10));</p>
<p>CREATE INDEX idx1ON tab (UPPER (col1));</p>
<p>ANALYZE TABLE a COMPUTE STATISTICS;
Code language: SQL (Structured Query Language) (sql)
Yet another DDL query to resize table space.
ALTER DATABASE DATAFILE '/work/oradata/STARTST/STAR02D.dbf' resize 2000M;
Code language: SQL (Structured Query Language) (sql)
Query to check if autoextend is on or off for a given tablespace.
SELECT SUBSTR (file_name, 1, 50), AUTOEXTENSIBLE FROM dba_data_files;</p>
<p>(OR)</p>
<p>SELECT tablespace_name, AUTOEXTENSIBLE FROM dba_data_files;
Code language: SQL (Structured Query Language) (sql)
Query to add datafile in a tablespace.
ALTER TABLESPACE data01 ADD DATAFILE '/work/oradata/STARTST/data01.dbf'SIZE 1000M AUTOEXTEND OFF;
Code language: SQL (Structured Query Language) (sql)
Yet another query to increase the datafile size of a given datafile.
ALTER DATABASE DATAFILE '/u01/app/Test_data_01.dbf' RESIZE 2G;
Code language: SQL (Structured Query Language) (sql)
Gives the actual database size in GB.
SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_data_files;
Code language: SQL (Structured Query Language) (sql)
Gives the size occupied by data in this database.
SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_segments;
Code language: SQL (Structured Query Language) (sql)
Give the size of user in MBs.
SELECT SUM (bytes / 1024 / 1024) "size"FROM dba_segmentsWHERE owner = '&owner';
Code language: SQL (Structured Query Language) (sql)
This query will display last SQL query fired by each user in this database. Notice how this query display last SQL per each session.
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;
Code language: SQL (Structured Query Language) (sql)
Displays CPU usage for each User. Useful to understand database load by user.
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;
Code language: SQL (Structured Query Language) (sql)
Show the progress of long running queries.
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;
Code language: SQL (Structured Query Language) (sql)
This is for those who wants to do some voodoo magic using process ids and session ids.
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');
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';
Code 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;
Code language: SQL (Structured Query Language) (sql)
SELECT osuser,username,machine,programFROM v$sessionORDER BY osuser;
Code language: SQL (Structured Query Language) (sql)
SELECT program application, COUNT (program) Numero_SesionesFROM v$sessionGROUP BY programORDER BY Numero_Sesiones DESC;
Code language: SQL (Structured Query Language) (sql)
SELECT username Usuario_Oracle, COUNT (username) Numero_SesionesFROM v$sessionGROUP BY usernameORDER BY Numero_Sesiones DESC;
Code language: SQL (Structured Query Language) (sql)
SELECT owner, COUNT (owner) number_of_objectsFROM dba_objectsGROUP BY ownerORDER BY number_of_objects DESC;
Code language: SQL (Structured Query Language) (sql)
More info: Converting number into words in Oracle
SELECT TO_CHAR (TO_DATE (1526, 'j'), 'jsp') FROM DUAL;
Code language: SQL (Structured Query Language) (sql)
one thousand five hundred twenty-six
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.
--search a string foo_something in package source codeSELECT *FROM dba_sourceWHERE UPPER (text) LIKE '%FOO_SOMETHING%'AND owner = 'USER_NAME';
Code language: SQL (Structured Query Language) (sql)
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.
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;
Code language: SQL (Structured Query Language) (sql)
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.
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);
Code language: SQL (Structured Query Language) (sql)
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 Oracle
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;
Code language: SQL (Structured Query Language) (sql)
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 Oracle
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;
Code language: SQL (Structured Query Language) (sql)
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.
--generate random number between 0 and 100SELECT ROUND (DBMS_RANDOM.VALUE () * 100) + 1 AS random_num FROM DUAL;
Code language: SQL (Structured Query Language) (sql)
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.
SELECT 1FROM TABLE_NAMEWHERE ROWNUM = 1;
Code language: SQL (Structured Query Language) (sql)
If you have some cool query that can make life of other Oracle developers easy, do share in comment section.
Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
View Comments
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 :)
Thank you
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?
Use USER_Views
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...
[code language="sql"]
create table CVT_T1_DAYS as
(select '1' Mon, '0' Tue, '0' Wed, '1' Thu, '1' Fri from dual);
select dd, next_day(sysdate - (rownum * 7), dd) DATE_
from (SELECT 'MON' dd from CVT_T1_DAYS where mon = 1)
connect by rownum <= round((sysdate - to_date('01/01/2012', 'dd/mm/yyyy'))/7)
union
select dd, next_day(sysdate - (rownum * 7), dd) DATE_
from (SELECT 'TUE' dd from CVT_T1_DAYS where tue = 1)
connect by rownum <= round((sysdate - to_date('01/01/2012', 'dd/mm/yyyy'))/7)
union
select dd, next_day(sysdate - (rownum * 7), dd) DATE_
from (SELECT 'WED' dd from CVT_T1_DAYS where wed = 1)
connect by rownum <= round((sysdate - to_date('01/01/2012', 'dd/mm/yyyy'))/7)
union
select dd, next_day(sysdate - (rownum * 7), dd) DATE_
from (SELECT 'THU' dd from CVT_T1_DAYS where thu = 1)
connect by rownum <= round((sysdate - to_date('01/01/2012', 'dd/mm/yyyy'))/7)
union
select dd, next_day(sysdate - (rownum * 7), dd) DATE_
from (SELECT 'FRI' dd from CVT_T1_DAYS where FRI = 1)
connect by rownum <= round((sysdate - to_date('01/01/2012', 'dd/mm/yyyy'))/7)
order by date_
;
[/code]
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.