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.
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.
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.
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.
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.
SELECT CAST (TO_CHAR (LAST_DAY (SYSDATE),'dd')ASINT) number_of_days
Get number of days left in current month
Below query calculates number of days left in current month.
Use this query to get difference between two dates in number of days.
FROM DUAL;ORSELECT 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.
SELECT ADD_MONTHS (TRUNC (SYSDATE,'MONTH'), i) start_date,
TRUNC (LAST_DAY (ADD_MONTHS (SYSDATE, i))) end_date
FROM XMLTABLE ('for $i in 0 to xs:int(D) return $i'
PASSING XMLELEMENT (d,
ADD_MONTHS (TRUNC (SYSDATE,'YEAR')-1,12),
SYSDATE)))COLUMNS i INTEGER PATH '.');
Get number of seconds passed since today (since 00:00 hr)
SELECT(SYSDATE - TRUNC (SYSDATE))*24*60*60 num_of_sec_since_morning
Get number of seconds left today (till 23:59:59 hr)
SELECT(TRUNC (SYSDATE+1)- SYSDATE)*24*60*60 num_of_sec_left
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).
WHERE 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.
SELECT column_name AS FOUND
WHERE 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.
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.
ALTERSESSIONSET CURRENT_SCHEMA = new_schema;
Database administration queries
Database version information
Returns the Oracle database version.
Database default information
Some system default information.
Database Character Set information
Display the character set information of database.
Get Oracle version
WHERE 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.
CREATETABLE tab (col1 VARCHAR2 (10));CREATEINDEX idx1
ON tab (UPPER (col1));ANALYZETABLEaCOMPUTESTATISTICS;
Displays CPU usage for each User. Useful to understand database load by user.
SELECT ss.username, se.SID,VALUE/100 cpu_usage_seconds
FROM v$session ss, v$sesstat se, v$statname sn
WHERE se.STATISTIC# = sn.STATISTIC#AND NAME LIKE'%CPU used by this session%'AND se.SID = ss.SID
AND ss.status='ACTIVE'AND ss.username ISNOTNULLORDERBYVALUEDESC;
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_source
WHERE 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.
FROM DUAL)SELECT REGEXP_SUBSTR (csv.csvdata,'[^,]+',1, LEVEL) pivot_char
FROM DUAL, csv
CONNECTBY REGEXP_SUBSTR (csv.csvdata,'[^,]+',1, LEVEL)ISNOTNULL;
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.
WHERE ROWID IN(SELECTMAX(ROWID)FROM employees);(OR)SELECT*FROM employees
WHERE ROWNUM <(SELECTCOUNT(*)FROM employees);
AS(SELECT-2 num FROM DUAL
UNIONSELECT-3 num FROM DUAL
UNIONSELECT-4 num FROM DUAL),
AS(SELECTCASE MOD (COUNT(*),2)WHEN0THEN1ELSE-1END val
WHERE num <0)SELECT EXP (SUM(LN (ABS (num))))* val
FROM tbl, sign_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 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.
--generate random number between 0 and 100SELECTROUND(DBMS_RANDOM.VALUE()*100)+1AS 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.
WHERE ROWNUM =1;
If you have some cool query that can make life of other Oracle developers easy, do share in comment section.