45 Useful Oracle Queries--ref
http://viralpatel.net/blogs/useful-oracle-queries/
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.
SELECTTRUNC (SYSDATE,'MONTH')"First day of current month"FROMDUAL;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.
SELECTTRUNC (LAST_DAY (SYSDATE))"Last day of current month"FROMDUAL;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.
SELECTTRUNC (SYSDATE,'YEAR')"Year First Day"FROMDUAL;Get the last day of the year
Similar to above query. Instead of first day this query returns last day of current year.
SELECTADD_MONTHS (TRUNC (SYSDATE,'YEAR'), 12) - 1"Year Last Day"FROMDUALGet 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.
SELECTCAST(TO_CHAR (LAST_DAY (SYSDATE),'dd')ASINT) number_of_daysFROMDUAL;Get number of days left in current month
Below query calculates number of days left in current month.
SELECTSYSDATE,LAST_DAY (SYSDATE)"Last",LAST_DAY (SYSDATE) - SYSDATE"Days left"FROMDUAL;Get number of days between two dates
Use this query to get difference between two dates in number of days.
SELECTROUND ( (MONTHS_BETWEEN ('01-Feb-2014','01-Mar-2012') * 30), 0)num_of_daysFROMDUAL;ORSELECTTRUNC(sysdate) - TRUNC(e.hire_date)FROMemployees;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.
SELECTADD_MONTHS (TRUNC (SYSDATE,'MONTH'), i) start_date,TRUNC (LAST_DAY (ADD_MONTHS (SYSDATE, i))) end_dateFROMXMLTABLE ('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 iINTEGERPATH'.');Get number of seconds passed since today (since 00:00 hr)
SELECT(SYSDATE - TRUNC (SYSDATE)) * 24 * 60 * 60 num_of_sec_since_morningFROMDUAL;Get number of seconds left today (till 23:59:59 hr)
SELECT(TRUNC (SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_leftFROMDUAL;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).
SELECTtable_nameFROMuser_tablesWHEREtable_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.
SELECTcolumn_nameASFOUNDFROMuser_tab_colsWHEREtable_name ='TABLE_NAME'ANDcolumn_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.
SELECTDBMS_METADATA.get_ddl ('TABLE','TABLE_NAME','USER_NAME')FROMDUAL;Getting current schema
Yet another query to get current schema name.
SELECTSYS_CONTEXT ('userenv','current_schema')FROMDUAL;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.
ALTERSESSIONSETCURRENT_SCHEMA = new_schema;Database administration queries
Database version information
Returns the Oracle database version.
SELECT*FROMv$version;Database default information
Some system default information.
SELECTusername,profile,default_tablespace,temporary_tablespaceFROMdba_users;Database Character Set information
Display the character set information of database.
SELECT*FROMnls_database_parameters;Get Oracle version
SELECTVALUEFROMv$system_parameterWHEREname='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.
CREATETABLEtab (col1 VARCHAR2 (10));CREATEINDEXidx1ONtab (UPPER(col1));ANALYZETABLEa COMPUTESTATISTICS;Resizing Tablespace without adding datafile
Yet another DDL query to resize table space.
ALTERDATABASEDATAFILE'/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.
SELECTSUBSTR (file_name, 1, 50), AUTOEXTENSIBLEFROMdba_data_files;(OR)SELECTtablespace_name, AUTOEXTENSIBLEFROMdba_data_files;Adding datafile to a tablespace
Query to add datafile in a tablespace.
ALTERTABLESPACE data01ADDDATAFILE'/work/oradata/STARTST/data01.dbf'SIZE1000M AUTOEXTENDOFF;Increasing datafile size
Yet another query to increase the datafile size of a given datafile.
ALTERDATABASEDATAFILE'/u01/app/Test_data_01.dbf'RESIZE 2G;Find the Actual size of a Database
Gives the actual database size in GB.
SELECTSUM(bytes) / 1024 / 1024 / 1024ASGBFROMdba_data_files;Find the size occupied by Data in a Database or Database usage details
Gives the size occupied by data in this database.
SELECTSUM(bytes) / 1024 / 1024 / 1024ASGBFROMdba_segments;Find the size of the SCHEMA/USER
Give the size of user in MBs.
SELECTSUM(bytes / 1024 / 1024)"size"FROMdba_segmentsWHEREowner ='&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.
SELECTS.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 sqltextFROMv$sqltext_with_newlines t, V$SESSION s, v$process pWHEREt.address = s.sql_addressANDp.addr = s.paddr(+)ANDt.hash_value = s.sql_hash_valueORDERBYs.sid, t.piece;Performance related queries
CPU usage of the USER
Displays CPU usage for each User. Useful to understand database load by user.
SELECTss.username, se.SID, VALUE / 100 cpu_usage_secondsFROMv$session ss, v$sesstat se, v$statname snWHEREse.STATISTIC# = sn.STATISTIC#ANDNAMELIKE'%CPU used by this session%'ANDse.SID = ss.SIDANDss.status ='ACTIVE'ANDss.usernameISNOTNULLORDERBYVALUEDESC;Long Query progress in database
Show the progress of long running queries.
SELECTa.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 (%)"FROMv$session_longops a, v$session bWHEREa.sid = b.sidANDb.usernameNOTIN('SYS','SYSTEM')ANDtotalwork > 0ORDERBYelapsed_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.
SELECTb.sid,b.serial#,a.spid processid,b.process clientpidFROMv$process a, v$session bWHEREa.addr = b.paddrANDb.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:
SELECTCREATED,TIMESTAMP, last_ddl_timeFROMall_objectsWHEREOWNER ='MYSCHEMA'ANDOBJECT_TYPE ='TABLE'ANDOBJECT_NAME ='EMPLOYEE_TABLE';Find Top 10 SQL by reads per execution
SELECT*FROM(SELECTROWNUM,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.addressFROMv$sqlarea aORDERBY3DESC)WHEREROWNUM < 10;Oracle SQL query over the view that shows actual Oracle connections.
SELECTosuser,username,machine,programFROMv$sessionORDERBYosuser;Oracle SQL query that show the opened connections group by the program that opens the connection.
SELECTprogram application,COUNT(program) Numero_SesionesFROMv$sessionGROUPBYprogramORDERBYNumero_SesionesDESC;Oracle SQL query that shows Oracle users connected and the sessions number for user
SELECTusername Usuario_Oracle,COUNT(username) Numero_SesionesFROMv$sessionGROUPBYusernameORDERBYNumero_SesionesDESC;Get number of objects per owner
SELECTowner,COUNT(owner) number_of_objectsFROMdba_objectsGROUPBYownerORDERBYnumber_of_objectsDESC;Utility / Math related queries
Convert number to words
More info: Converting number into words in Oracle
SELECTTO_CHAR (TO_DATE (1526,'j'),'jsp')FROMDUAL;Output:
one thousand five hundred twenty-sixFind 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.
--search a string foo_something in package source codeSELECT*FROMdba_sourceWHEREUPPER(text)LIKE'%FOO_SOMETHING%'ANDowner ='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.
WITHcsvAS(SELECT'AA,BB,CC,DD,EE,FF'AScsvdataFROMDUAL)SELECTREGEXP_SUBSTR (csv.csvdata,'[^,]+', 1,LEVEL) pivot_charFROMDUAL, csvCONNECTBYREGEXP_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.
SELECT*FROMemployeesWHEREROWIDIN(SELECTMAX(ROWID)FROMemployees);(OR)SELECT*FROMemployeesMINUSSELECT*FROMemployeesWHEREROWNUM < (SELECTCOUNT(*)FROMemployees);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 OracleWITHtblAS(SELECT-2 numFROMDUALUNIONSELECT-3 numFROMDUALUNIONSELECT-4 numFROMDUAL),sign_valAS(SELECTCASEMOD (COUNT(*), 2)WHEN0THEN1ELSE-1ENDvalFROMtblWHEREnum < 0)SELECTEXP (SUM(LN (ABS(num)))) * valFROMtbl, sign_valGROUPBYval;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 OracleSELECTLEVELempl_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)) addressFROMDUALCONNECTBYLEVEL< 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.--generate random number between 0 and 100SELECTROUND (DBMS_RANDOM.VALUE () * 100) + 1ASrandom_numFROMDUAL;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.SELECT1FROMTABLE_NAMEWHEREROWNUM = 1;
If you have some cool query that can make life of other Oracle developers easy, do share in comment section.
Related Articles
45 Useful Oracle Queries--ref的更多相关文章
- oracle中REF Cursor用法
from:http://www.111cn.net/database/Oracle/42873.htm 1,什么是 REF游标 ? 动态关联结果集的临时对象.即在运行的时候动态决定执行查询. 2,RE ...
- Index Skip Scan in Oracle in 11g
http://viralpatel.net/blogs/oracle-index-skip-scan/ in 11g the same sql use index skip scan but in 1 ...
- Oracle笔试题库 附参考答案
1. 下列不属于ORACLE的逻辑结构的是(C) 区 段 数据文件 表空间 2. 下面哪个用户不是ORACLE缺省安装后就存在的用户(A) A . SYSDBA B. SYSTEM C. SCOTT ...
- OCM_第二天课程:Section1 —》配置 Oracle 网络环境
注:本文为原著(其内容来自 腾科教育培训课堂).阅读本文注意事项如下: 1:所有文章的转载请标注本文出处. 2:本文非本人不得用于商业用途.违者将承当相应法律责任. 3:该系列文章目录列表: 一:&l ...
- oracle学习笔记(二)
1. Oracle字符串操作 1.1. 字符串类型 1.1.1. CHAR和VARCHAR2类型 CHAR和VARCHAR2类型都是用来表示字符串数据类型,用来在表中存放字符串信息, 比如姓名.职业. ...
- ORACLE定期清理INACTIVE会话
ORACLE数据库会话有ACTIVE.INACTIVE.KILLED. CACHED.SNIPED五种状态.INACTIVE状态的会话表示此会话处于非活动.空闲.等待状态.例如PL/SQL Dev ...
- Linux下Oracle 10.2.0.1升级到10.2.0.4总结
最近部署测试环境时,将测试环境ORACLE数据库从10.2.0.1升级到了10.2.0.4,顺便整理记录一下升级过程. 实验环境: 操作系统:Oracle Linux Server release 5 ...
- rhel5.8安装oracle 10g ASM
1.所有的配置和文件系统一样 2.规划: 加了8块小盘,ASM为了实验使用asmlib驱动(rhel6不再支持asmlib驱动),裸设备的2种方法(rowdevice和udev) 三块盘使用asmli ...
- 【转】ORACLE定期清理INACTIVE会话
源地址:http://www.cnblogs.com/kerrycode/p/3636992.html ORACLE数据库会话有ACTIVE.INACTIVE.KILLED. CACHED.SNIPE ...
随机推荐
- 【原创翻译】ArcGis Android 10.2.4更新内容简介
翻译不当和错误之处敬请指出 更新内容官方描述 https://developers.arcgis.com/android/guide/release-notes-10-2-4.htm 10.2.4的版 ...
- Mac安装Tomcat
1. 到Tomcat官网下载,如下找tar格式文件: http://ftp.twaren.net/Unix/Web/apache/tomcat/tomcat-8/v8.0.41/bin/apache- ...
- Mvc 项目中使用Bootstrap以及基于bootstrap的 Bootgrid
官方地址参考http://www.jquery-bootgrid.com/Examples Bootgrid 是一款基于BootStrap 开发的带有查询,分页功能的列表显示组件.可以在像MVC中开发 ...
- ASP.NET MVC实现一个用户只能登录一次 单用户登录
现在许多网站都要求登录后才能进行进一步的操作,当不允许多用户同时登录一个帐号时,就需要一种机制,当再登录一个相同的帐号时,前面登录的人被挤下线,或者禁止后面的人登录.这里实现的是前一种功能. 网上有许 ...
- 如何为 smartraiden 贡献代码
如何为 smartRaiden 贡献代码 1.Fork 项目 登录 github 账号,并访问https://github.com/SmartMeshFoundation/SmartRaiden,然后 ...
- 浅谈K8S cni和网络方案
此文已由作者黄扬授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 在早先的k8s版本中,kubelet代码里提供了networkPlugin,networkPlugin是一组接 ...
- “全栈2019”Java第五十七章:多态与构造方法详解
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...
- HTTP请求的两种方式get和post的区别
1,get从服务器获取数据:post向服务器发送数据: 2,安全性,get请求的数据会显示在地址栏中,post请求的数据放在http协议的消息体: 3,从提交数据的大小看,http协议本身没有限制数据 ...
- logstash--使用ngxlog收集windows日志
收集流程 1nxlog => 2logstash => 3elasticsearch 1. nxlog 使用模块 im_file 收集日志文件,开启位置记录功能 2. nxlog 使用模块 ...
- python 注释 与 windows 上用tab 自动补齐设置
python的注释 单行注释:用# 多行代码用:“”“ 中间为你要注释的解释 ”“” # 我是单行注释 我是一个#号 print("hello,word") "&quo ...