Upload
newgenbe
View
39
Download
5
Embed Size (px)
DESCRIPTION
oracle
Citation preview
By Viral Patel on January 14, 2014
Home > Database > Oracle
45 Useful Oracle Queries
Here’s a list of 40+ Useful Oracle queries that every Oracle developer must bookmark. These queriesrange from date manipulation, getting server info, get execution status, calculate database size etc.
Date / Time related queriesGet the first day of the monthQuickly returns the first day of current month. Instead of current month you want to find first day of
1.
Subscribe
Get our Articles via Email. Enter your email.
Your E-Mail
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
1 of 23 15-12-2014 16:32
Get the last day of the monthThis query is similar to above but returns last day of current month. One thing worth noting is that itautomatically takes care of leap year. So if you have 29 days in Feb, it will return 29/2. Also similarto above query replace SYSDATE with any other date column/value to find last day of that particularmonth.
2.
Get the first day of the YearFirst day of year is always 1-Jan. This query can be use in stored procedure where you quickly wantfirst day of year for some calculation.
3.
Get the last day of the yearSimilar to above query. Instead of first day this query returns last day of current year.
4.
Get number of days in current monthNow this is useful. This query returns number of days in current month. You can change SYSDATEwith any date/value to know number of days in that month.
5.
Get number of days left in current month6.
Latest Posts
Getting Started With Yeoman (Introduction toYeoman)
1.
Navigating Spring Security from thick Client toREST Webservice
2.
HTML5 DataList Example3.
Auditing DML changes in Oracle4.
Java 8 Lambda Expressions Tutorial withExamples
5.
Java 8 Default Methods Tutorial6.
Compound Triggers in Oracle 11g - Tutorial with7.
SELECT TRUNC (SYSDATE, 'MONTH') "First day of current month"FROM DUAL;
SELECT TRUNC (LAST_DAY (SYSDATE)) "Last day of current month"FROM DUAL;
SELECT TRUNC (SYSDATE, 'YEAR') "Year First Day" FROM DUAL;
SELECT ADD_MONTHS (TRUNC (SYSDATE, 'YEAR'), 12) - 1 "Year Last Day" FROM DUAL
SELECT CAST (TO_CHAR (LAST_DAY (SYSDATE), 'dd') AS INT) number_of_daysFROM DUAL;
Follow on Twitter @viralpatelnet
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
2 of 23 15-12-2014 16:32
Get number of days between two datesUse this query to get difference between two dates in number of days.
Use second query if you need to find number of days since some specific date. In this examplenumber of days since any employee is hired.
7.
Display each months start and end date upto last month of the yearThis clever query displays start date and end date of each month in current year. You might want touse this for certain types of calculations.
8.
Get number of seconds passed since today (since 00:00 hr)9.
Sponsors
How to pass CLOB argument in EXECUTEIMMEDIATE
8.
How to get Eclipse current workspace path9.
jQuery window height is not correct10.
SELECT SYSDATE,LAST_DAY (SYSDATE) "Last",LAST_DAY (SYSDATE) - SYSDATE "Days left"
FROM DUAL;
SELECT ROUND ( (MONTHS_BETWEEN ('01-Feb-2014', '01-Mar-2012') * 30), 0)num_of_days
FROM DUAL;
OR
SELECT TRUNC(sysdate) - TRUNC(e.hire_date) FROM employees;
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,FLOOR (
MONTHS_BETWEEN (ADD_MONTHS (TRUNC (SYSDATE, 'YEAR') - 1, 12),SYSDATE)))
COLUMNS i INTEGER PATH '.');
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
3 of 23 15-12-2014 16:32
Get number of seconds left today (till 23:59:59 hr)
Data dictionary queries
10.
Check if a table exists in the current database schemaA simple query that can be used to check if a table exists before you create it. This way you canmake your create table script rerunnable. Just replace table_name with actual table you want tocheck. This query will check if table exists for current user (from where the query is executed).
11.
Check if a column exists in a tableSimple query to check if a particular column exists in table. Useful when you tries to add newcolumn in table using ALTER TABLE statement, you might wanna check if column already existsbefore adding one.
12.
Showing the table structureThis query gives you the DDL statement for any table. Notice we have pass ‘TABLE’ as firstparameter. This query can be generalized to get DDL statement of any database object. Forexample to get DDL for a view just replace first argument with ‘VIEW’ and second with your viewname and so.
13.
FROM DUAL;
SELECT (TRUNC (SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_leftFROM DUAL;
SELECT table_nameFROM user_tablesWHERE table_name = 'TABLE_NAME';
SELECT column_name AS FOUNDFROM user_tab_colsWHERE table_name = 'TABLE_NAME' AND column_name = 'COLUMN_NAME';
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
4 of 23 15-12-2014 16:32
Getting current schemaYet another query to get current schema name.
14.
Changing current schemaYet another query to change the current schema. Useful when your script is expected to run undercertain user but is actually executed by other user. It is always safe to set the current user to whatyour script expects.
Database administration queries
15.
Database version informationReturns the Oracle database version.
16.
Database default informationSome system default information.
17.
Database Character Set informationDisplay the character set information of database.
18.
SELECT SYS_CONTEXT ('userenv', 'current_schema') FROM DUAL;
ALTER SESSION SET CURRENT_SCHEMA = new_schema;
SELECT * FROM v$version;
SELECT username,profile,default_tablespace,temporary_tablespace
FROM dba_users;
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
5 of 23 15-12-2014 16:32
Get Oracle version19.
Store data case sensitive but to index it case insensitiveNow 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. Nowin such cases, you might want to make your index case insensitive so that they don’t occupy morespace. Feel free to experiment with this one.
20.
Resizing Tablespace without adding datafileYet another DDL query to resize table space.
21.
Checking autoextend on/off for TablespacesQuery to check if autoextend is on or off for a given tablespace.
22.
SELECT VALUEFROM v$system_parameterWHERE name = 'compatible';
CREATE TABLE tab (col1 VARCHAR2 (10));
CREATE INDEX idx1ON tab (UPPER (col1));
ANALYZE TABLE a COMPUTE STATISTICS;
ALTER DATABASE DATAFILE '/work/oradata/STARTST/STAR02D.dbf' resize 2000M;
SELECT SUBSTR (file_name, 1, 50), AUTOEXTENSIBLE FROM dba_data_files;
(OR)
SELECT tablespace_name, AUTOEXTENSIBLE FROM dba_data_files;
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
6 of 23 15-12-2014 16:32
Query to add datafile in a tablespace.
Increasing datafile sizeYet another query to increase the datafile size of a given datafile.
24.
Find the Actual size of a DatabaseGives the actual database size in GB.
25.
Find the size occupied by Data in a Database or Database usage detailsGives the size occupied by data in this database.
26.
Find the size of the SCHEMA/USERGive the size of user in MBs.
27.
Last SQL fired by the User on DatabaseThis query will display last SQL query fired by each user in this database. Notice how this querydisplay last SQL per each session.
28.
ALTER TABLESPACE data01 ADD DATAFILE '/work/oradata/STARTST/data01.dbf'SIZE 1000M AUTOEXTEND OFF;
ALTER DATABASE DATAFILE '/u01/app/Test_data_01.dbf' RESIZE 2G;
SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_data_files;
SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_segments;
SELECT SUM (bytes / 1024 / 1024) "size"FROM dba_segmentsWHERE owner = '&owner';
SELECT S.USERNAME || '(' || s.sid || ')-' || s.osuser UNAME,
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
7 of 23 15-12-2014 16:32
Performance related queriesCPU usage of the USERDisplays CPU usage for each User. Useful to understand database load by user.
29.
Long Query progress in databaseShow the progress of long running queries.
30.
s.sid || '/' || s.serial# sid,s.status "Status",p.spid,sql_text sqltext
FROM v$sqltext_with_newlines t, V$SESSION s, v$process pWHERE t.address = s.sql_address
AND p.addr = s.paddr(+)AND t.hash_value = s.sql_hash_value
ORDER BY s.sid, t.piece;
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 NULL
ORDER BY VALUE DESC;
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.sid
AND b.username NOT IN ('SYS', 'SYSTEM')AND totalwork > 0
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
8 of 23 15-12-2014 16:32
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.
V$SESSION.SID AND V$SESSION.SERIAL# is database process idV$PROCESS.SPID is shadow process id on this database server
V$SESSION.PROCESS is client PROCESS ID, ON windows it IS : separated THE FIRST # ISTHE PROCESS ID ON THE client AND 2nd one IS THE THREAD id.
31.
Last SQL Fired from particular Schema or Table:32.
Find Top 10 SQL by reads per execution33.
SELECT b.sid,b.serial#,a.spid processid,b.process clientpid
FROM v$process a, v$session bWHERE a.addr = b.paddr AND b.audsid = USERENV ('sessionid');
SELECT CREATED, TIMESTAMP, last_ddl_timeFROM all_objectsWHERE OWNER = 'MYSCHEMA'
AND OBJECT_TYPE = 'TABLE'AND OBJECT_NAME = 'EMPLOYEE_TABLE';
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.address
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
9 of 23 15-12-2014 16:32
Oracle SQL query over the view that shows actual Oracle connections.34.
Oracle SQL query that show the opened connections group by the program that opens theconnection.
35.
Oracle SQL query that shows Oracle users connected and the sessions number for user36.
Get number of objects per owner
Utility / Math related queries
37.
ORDER BY 3 DESC)WHERE ROWNUM < 10;
SELECT osuser,username,machine,program
FROM v$sessionORDER BY osuser;
SELECT program application, COUNT (program) Numero_SesionesFROM v$session
GROUP BY programORDER BY Numero_Sesiones DESC;
SELECT username Usuario_Oracle, COUNT (username) Numero_SesionesFROM v$session
GROUP BY usernameORDER BY Numero_Sesiones DESC;
SELECT owner, COUNT (owner) number_of_objectsFROM dba_objects
GROUP BY ownerORDER BY number_of_objects DESC;
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
10 of 23 15-12-2014 16:32
More info: Converting number into words in Oracle
Output:
Find string in package source codeBelow query will search for string ‘FOO_SOMETHING’ in all package source. This query comeshandy when you want to find a particular procedure or function call from all the source code.
39.
Convert Comma Separated Values into TableThe query can come quite handy when you have comma separated data string that you need toconvert 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 thistable you can join it with other table to quickly do some useful stuffs.
40.
Find the last record from a tableThis ones straight forward. Use this when your table does not have primary key or you cannot be
41.
SELECT TO_CHAR (TO_DATE (1526, 'j'), 'jsp') FROM DUAL;
one thousand five hundred twenty-six
--search a string foo_something in package source codeSELECT *FROM dba_sourceWHERE UPPER (text) LIKE '%FOO_SOMETHING%'
AND owner = 'USER_NAME';
WITH csvAS (SELECT 'AA,BB,CC,DD,EE,FF'
AS csvdataFROM DUAL)
SELECT REGEXP_SUBSTR (csv.csvdata, '[^,]+', 1, LEVEL) pivot_charFROM DUAL, csv
CONNECT BY REGEXP_SUBSTR (csv.csvdata,'[^,]+', 1, LEVEL) IS NOT NULL;
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
11 of 23 15-12-2014 16:32
Row Data Multiplication in OracleThis query use some tricky math functions to multiply values from each row. Read below article formore details.More info: Row Data Multiplication In Oracle
42.
Generating Random Data In OracleYou might want to generate some random data to quickly insert in table for testing. Below query helpyou do that. Read this article for more details.More info: Random Data in Oracle
43.
SELECT *FROM employeesWHERE ROWID IN (SELECT MAX (ROWID) FROM employees);
(OR)
SELECT * FROM employeesMINUSSELECT *FROM employeesWHERE ROWNUM < (SELECT COUNT (*) FROM employees);
WITH tblAS (SELECT -2 num FROM DUAL
UNIONSELECT -3 num FROM DUALUNIONSELECT -4 num FROM DUAL),
sign_valAS (SELECT CASE MOD (COUNT (*), 2) WHEN 0 THEN 1 ELSE -1 END val
FROM tblWHERE num < 0)
SELECT EXP (SUM (LN (ABS (num)))) * valFROM tbl, sign_val
GROUP BY val;
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
12 of 23 15-12-2014 16:32
Random number generator in OraclePlain old random number generator in Oracle. This ones generate a random number between 0 and100. Change the multiplier to number that you want to set limit for.
44.
Check if table contains any dataThis one can be written in multiple ways. You can create count(*) on a table to know number ofrows. But this query is more efficient given the fact that we are only interested in knowing if tablehas any data.
45.
If you have some cool query that can make life of other Oracle developers easy, do share in commentsection.
Related Articles
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 DUAL
CONNECT BY LEVEL < 10000;
--generate random number between 0 and 100SELECT ROUND (DBMS_RANDOM.VALUE () * 100) + 1 AS random_num FROM DUAL;
SELECT 1FROM TABLE_NAMEWHERE ROWNUM = 1;
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
13 of 23 15-12-2014 16:32
21 January, 2014, 7:31
Generating Random Data in Oracle2.
Fetch Random rows from Database (MySQL, Oracle, MS SQL, PostgreSQL)3.
Row Data Multiplication in Oracle4.
Oracle Skip Locked5.
Invisible Indexes in Oracle 11g6.
Oracle XMLTable Tutorial with Example7.
Get our Articles via Email. Enter your email address.
Send Me Tutorials
Tags: ORACLE, PL-SQL, SQL
22 Comments
Madiraju Krishna Chaitanya
Hi Viral Patel,Thanks a LOT for providing these useful Oracle Queries for us.Please keep up theGood Work.All the Best.
Reply
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
14 of 23 15-12-2014 16:32
21 January, 2014, 14:38
21 January, 2014, 18:05
20 February, 2014, 16:01
18 March, 2014, 17:24
9 April, 2014, 1:29
12 April, 2014, 11:34
Praveen
very useful queries, thanks for sharing :)
Reply
Tushar
Excellent compilation of queries Viral!.You rock bhai :)
Reply
krunal
Thank youusing above database queries i will solve db related problems in my many project.
Reply
Harshita
Good Job Viral, really useful article. Looking forward to more such stuff. :)
Reply
Chandra
Really Some useful queries …
Reply
junaid ahmad
Can you please give 50 different views of Data Dictionary in form of SQL Queries?
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
15 of 23 15-12-2014 16:32
16 April, 2014, 16:34
16 April, 2014, 16:34
17 April, 2014, 11:05
15 May, 2014, 18:57
Nishant Mishra
Use USER_Views
Reply
Nishant Mishra
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
Reply
David
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 Fridaysfrom a given date to sysdate.Similarly, If Monday, Wednesday and Thursday are set to Yes, I need all the Mondays, Wednesdaysand Thursday from a given date(passed as parameter) to sysdate.Could anyone please help me in writing this query?
Reply
Kevin
for David’s question on April 17th..I’m sure this could probably be cleaned up some more andI see that the Friday portion of this returns a friday before 01/01/2012 but this is a start…
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)
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
16 of 23 15-12-2014 16:32
15 May, 2014, 19:00
6 May, 2014, 3:59
7 May, 2014, 12:55
Reply
Kevin
note, the “<=” should be <=or "less than or equal to"it didn't format correctly in my cut/paste
Reply
Fernando Tlatilolpa
Hello and thanks Viral, I think you can include a query which return number of columns result of adynamic query, these usefull when you send a script inside a function and you don’t know exactlyhow many columns you obtain.Once again thaks for your effort.
Reply
salim
unionselect 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)unionselect 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)unionselect 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)unionselect 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_;
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
17 of 23 15-12-2014 16:32
16 May, 2014, 2:49
Thank you dear for sharing knowledge
Reply
Kevin
in response to David’s query….cleaned up the dates that come out prior to the date entered as wellas 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
select dd, next_day(sysdate - (rownum * 7), dd) DATE_from (SELECT 'MON' dd from CVT_T1_DAYS where mon = 1)where to_date('&indate', 'mm/dd/yyyy') <= sysdate
and next_day(sysdate - (rownum * 7), dd) >= to_date('&indate', 'mm/dd/yyyy'connect by rownum <= round((sysdate - to_date('&indate', 'mm/dd/yyyy'))/7)
and next_day(sysdate - (rownum * 7), dd) >= to_date('&indate', 'mm/dd/yyyy'unionselect dd, next_day(sysdate - (rownum * 7), dd) DATE_from (SELECT 'TUE' dd from CVT_T1_DAYS where tue = 1)where to_date('&indate', 'mm/dd/yyyy') <= sysdate
and next_day(sysdate - (rownum * 7), dd) >= to_date('&indate', 'mm/dd/yyyy'connect by rownum <= round((sysdate - to_date('&indate', 'mm/dd/yyyy'))/7)
and next_day(sysdate - (rownum * 7), dd) >= to_date('&indate', 'mm/dd/yyyy'unionselect dd, next_day(sysdate - (rownum * 7), dd) DATE_from (SELECT 'WED' dd from CVT_T1_DAYS where wed = 1)where to_date('&indate', 'mm/dd/yyyy') <= sysdate
and next_day(sysdate - (rownum * 7), dd) >= to_date('&indate', 'mm/dd/yyyy'connect by rownum <= round((sysdate - to_date('&indate', 'mm/dd/yyyy'))/7)
and next_day(sysdate - (rownum * 7), dd) >= to_date('&indate', 'mm/dd/yyyy'unionselect dd, next_day(sysdate - (rownum * 7), dd) DATE_from (SELECT 'THU' dd from CVT_T1_DAYS where thu = 1)where to_date('&indate', 'mm/dd/yyyy') <= sysdate
and next_day(sysdate - (rownum * 7), dd) >= to_date('&indate', 'mm/dd/yyyy'connect by rownum <= round((sysdate - to_date('&indate', 'mm/dd/yyyy'))/7)
and next_day(sysdate - (rownum * 7), dd) >= to_date('&indate', 'mm/dd/yyyy'unionselect dd, next_day(sysdate - (rownum * 7), dd) DATE_from (SELECT 'FRI' dd from CVT_T1_DAYS where FRI = 1)where to_date('&indate', 'mm/dd/yyyy') <= sysdate
and next_day(sysdate - (rownum * 7), dd) >= to_date('&indate', 'mm/dd/yyyy'connect by rownum <= round((sysdate - to_date('&indate', 'mm/dd/yyyy'))/7)
and next_day(sysdate - (rownum * 7), dd) >= to_date('&indate', 'mm/dd/yyyy'order by date_;
declarev_datechosen date := to_date('&indate', 'mm/dd/yyyy');
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
18 of 23 15-12-2014 16:32
v_sysdate date := sysdate;
v_dd char(5);v_date date;
cursor dates isselect dd, next_day(v_sysdate - (rownum * 7), dd) DATE_from (SELECT 'MON' dd from CVT_T1_DAYS where mon = 1)where v_datechosen <= v_sysdateand next_day(v_sysdate - (rownum * 7), dd) >= v_datechosenconnect by rownum <= v_weeksdiff and
next_day(v_sysdate - (rownum * 7), dd) >= v_datechosenunionselect dd, next_day(v_sysdate - (rownum * 7), dd) DATE_from (SELECT 'TUE' dd from CVT_T1_DAYS where tue = 1)where v_datechosen <= v_sysdateand next_day(v_sysdate - (rownum * 7), dd) >= v_datechosenconnect by rownum <= v_weeksdiff and
next_day(v_sysdate - (rownum * 7), dd) >= v_datechosenunionselect dd, next_day(v_sysdate - (rownum * 7), dd) DATE_from (SELECT 'WED' dd from CVT_T1_DAYS where wed = 1)where v_datechosen <= v_sysdateand next_day(v_sysdate - (rownum * 7), dd) >= v_datechosenconnect by rownum <= v_weeksdiff and
next_day(v_sysdate - (rownum * 7), dd) >= v_datechosenunionselect dd, next_day(v_sysdate - (rownum * 7), dd) DATE_from (SELECT 'THU' dd from CVT_T1_DAYS where thu = 1)where v_datechosen <= v_sysdateand next_day(v_sysdate - (rownum * 7), dd) >= v_datechosenconnect by rownum <= v_weeksdiff and
next_day(v_sysdate - (rownum * 7), dd) >= v_datechosenunionselect dd, next_day(v_sysdate - (rownum * 7), dd) DATE_from (SELECT 'FRI' dd from CVT_T1_DAYS where FRI = 1)where v_datechosen <= v_sysdateand next_day(v_sysdate - (rownum * 7), dd) >= v_datechosenconnect by rownum <= v_weeksdiff and
next_day(v_sysdate - (rownum * 7), dd) >= v_datechosenorder by date_;
begindbms_output.enable(1000000);dbms_output.put_line(v_weeksdiff||' '||to_date('&indate', 'mm/dd/yyyy'));
open dates;
LOOPFETCH dates into v_dd, v_date;EXIT WHEN dates%NOTFOUND;dbms_output.put_line(v_dd ||' '||v_date);
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
19 of 23 15-12-2014 16:32
6 June, 2014, 12:07
8 July, 2014, 17:33
10 July, 2014, 19:40
11 July, 2014, 15:12
Reply
Bharani
ans for q 8WITH 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
Reply
MVVSSARMA
pl answer to my query, I have a table emp (empno,login)—- in my table an employee can login manytimes in a day. Assume each employee 4 times logged into the table with employeeno 11,22,33,44since one week. Now I want a query to list all employees 11,22,33,44 once per day.(total I need to get7 records for each employee)….please suggest the ansewr
Reply
Dayanandsm
please try this !select empno,login from emp where to_Date(login) >= to_date(sysdate – 7) order by logindesc;
Reply
Daniel
close dates;end;
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
20 of 23 15-12-2014 16:32
16 July, 2014, 10:08
3 September, 2014, 20:51
6 November, 2014, 18:47
very usefull !I really appreciate that !
Reply
Malshan
Hi,I want to select 1st,10th and 20th of the month by giving 1,10,20 as the parameters. is there the apossible way?plz help
Reply
Makal
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 lastmonth salary is not same. I tried the samethe below query works for unique record but not for the lastselect * From demo_orders awhere order_id not IN (select order_id from demo_orders bwhere b.customer_id = a.customer_id and rownum=1);logically I want theselect * From demo_orders awhere order_id IN (select b.order_id from demo_orders bwhere a.customer_id = b.customer_id and rownum=1 order by a.customer_id );
Reply
rk goud
very usefull …… looking forward to see much stufff……………………………
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
21 of 23 15-12-2014 16:32
Leave a Reply
Your email address will not be published. Required fields are marked *Name *
Email *
Website
Comment
NoteTo post source code in comment, use [code language] [/code] tag, for example:
[code java] Java source code here [/code]
[code html] HTML here [/code]
Post Comment
Home page Struts Spring AJAX PHP Java JavaEE
Categories
About viralpatel.net Join Us Search Advertise Posts Feed
Site Pages Back to top
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
22 of 23 15-12-2014 16:32
General Featured Play Framework AndroidFreeMarker Template HTML5
Copyright © 2014 ViralPatel.net. All rights reserved :)
Home Android Java Spring Frameworks Database JavaScript Web More…
45 Useful Oracle Queries for Oracle Developers http://viralpatel.net/blogs/useful-oracle-queries/
23 of 23 15-12-2014 16:32