Sunteți pe pagina 1din 36

How to remove duplicate rows without using DISTINCT or ROWID or GROUP

BY methods in Oracle?
Make use of SET operators and CTAS (Create Table <> AS) method..
Example:
Create table tmp_tb1
as
Select * from table1
intersect
Select * from table1;
truncate table table1;
insert into table1
select * from tmp_tb1; -- This will now have removed all duplicates in the table...
commit;
*** You can use UNION operator in place of INTERSECT

45 Useful Oracle Queries


by Viral Patel January 14, 2014

Heres 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


1. 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;

2. 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;

3. 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;

4. 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

5. 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') AS INT) number_of_days
FROM DUAL;

6. Get number of days left in current month

Below query calculates number of days left in current month.


SELECT SYSDATE,
LAST_DAY (SYSDATE) "Last",
LAST_DAY (SYSDATE) - SYSDATE "Days left"
FROM DUAL;

7. Get number of days between two dates

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_days
FROM DUAL;

OR

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.
8. 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,
FLOOR (
MONTHS_BETWEEN (
ADD_MONTHS (TRUNC (SYSDATE, 'YEAR') - 1, 12),
SYSDATE)))

COLUMNS i INTEGER PATH '.');

9. Get number of seconds passed since today (since 00:00 hr)


SELECT (SYSDATE - TRUNC (SYSDATE)) * 24 * 60 * 60 num_of_sec_since_morning
FROM DUAL;

10.Get number of seconds left today (till 23:59:59 hr)


SELECT (TRUNC (SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_left
FROM DUAL;

11.

Data dictionary queries

12.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).
SELECT table_name
FROM user_tables
WHERE table_name = 'TABLE_NAME';

13.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
FROM user_tab_cols
WHERE table_name = 'TABLE_NAME' AND column_name = 'COLUMN_NAME';

14.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.

SELECT DBMS_METADATA.get_ddl ('TABLE', 'TABLE_NAME', 'USER_NAME') FROM DUAL;

15.Getting current schema

Yet another query to get current schema name.


SELECT SYS_CONTEXT ('userenv', 'current_schema') FROM DUAL;

16.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.
ALTER SESSION SET CURRENT_SCHEMA = new_schema;

Database administration queries


17.Database version information

Returns the Oracle database version.


SELECT * FROM v$version;

18.Database default information

Some system default information.


SELECT username,
profile,
default_tablespace,
temporary_tablespace
FROM dba_users;

19.Database Character Set information

Display the character set information of database.


SELECT * FROM nls_database_parameters;

20.Get Oracle version


SELECT VALUE

FROM v$system_parameter
WHERE name = 'compatible';

21.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 dont occupy more space. Feel free to experiment with this one.
CREATE TABLE tab (col1 VARCHAR2 (10));

CREATE INDEX idx1


ON tab (UPPER (col1));

ANALYZE TABLE a COMPUTE STATISTICS;

22.Resizing Tablespace without adding datafile

Yet another DDL query to resize table space.


ALTER DATABASE DATAFILE '/work/oradata/STARTST/STAR02D.dbf' resize 2000M;

23.Checking autoextend on/off for Tablespaces

Query to check if autoextend is on or off for a given tablespace.


SELECT SUBSTR (file_name, 1, 50), AUTOEXTENSIBLE FROM dba_data_files;

(OR)

SELECT tablespace_name, AUTOEXTENSIBLE FROM dba_data_files;

24.Adding datafile to a tablespace

Query to add datafile in a tablespace.


ALTER TABLESPACE data01 ADD DATAFILE '/work/oradata/STARTST/data01.dbf'

SIZE 1000M AUTOEXTEND OFF;

25.Increasing datafile size

Yet another query to increase the datafile size of a given datafile.


ALTER DATABASE DATAFILE '/u01/app/Test_data_01.dbf' RESIZE 2G;

26.Find the Actual size of a Database

Gives the actual database size in GB.


SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_data_files;

27.Find the size occupied by Data in a Database or Database usage details

Gives the size occupied by data in this database.


SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_segments;

28.Find the size of the SCHEMA/USER

Give the size of user in MBs.


SELECT SUM (bytes / 1024 / 1024) "size"
FROM dba_segments
WHERE owner = '&owner';

29.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.
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 sqltext

FROM v$sqltext_with_newlines t, V$SESSION s, v$process p


WHERE

t.address = s.sql_address
AND p.addr = s.paddr(+)
AND t.hash_value = s.sql_hash_value

ORDER BY s.sid, t.piece;

Performance related queries


30.CPU usage of the USER

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 IS NOT NULL

ORDER BY VALUE DESC;

31.Long Query progress in database

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 b
WHERE

a.sid = b.sid

AND b.username NOT IN ('SYS', 'SYSTEM')


AND totalwork > 0
ORDER BY elapsed_seconds;

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.
SELECT b.sid,
b.serial#,
a.spid processid,
b.process clientpid
FROM v$process a, v$session b
WHERE a.addr = b.paddr AND b.audsid = USERENV ('sessionid');
o

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.

33.Last SQL Fired from particular Schema or Table:


SELECT CREATED, TIMESTAMP, last_ddl_time
FROM all_objects
WHERE

OWNER = 'MYSCHEMA'
AND OBJECT_TYPE = 'TABLE'
AND OBJECT_NAME = 'EMPLOYEE_TABLE';

34.Find Top 10 SQL by reads per execution


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
FROM v$sqlarea a
ORDER BY 3 DESC)
WHERE ROWNUM < 10;

35.Oracle SQL query over the view that shows actual Oracle connections.
SELECT osuser,
username,
machine,
program
FROM v$session
ORDER BY osuser;

36.Oracle SQL query that show the opened connections group by the program
that opens the connection.
SELECT program application, COUNT (program) Numero_Sesiones
FROM v$session
GROUP BY program
ORDER BY Numero_Sesiones DESC;

37.Oracle SQL query that shows Oracle users connected and the sessions
number for user
SELECT username Usuario_Oracle, COUNT (username) Numero_Sesiones
FROM v$session
GROUP BY username
ORDER BY Numero_Sesiones DESC;

38.Get number of objects per owner

SELECT owner, COUNT (owner) number_of_objects


FROM dba_objects
GROUP BY owner
ORDER BY number_of_objects DESC;

39.

Utility / Math related queries

40.Convert number to words

More info: Converting number into words in Oracle


SELECT TO_CHAR (TO_DATE (1526, 'j'), 'jsp') FROM DUAL;

Output:
one thousand five hundred twenty-six

41.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.
--search a string foo_something in package source code
SELECT *
FROM dba_source
WHERE UPPER (text) LIKE '%FOO_SOMETHING%'
AND owner = 'USER_NAME';

42.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.
WITH csv
AS (SELECT 'AA,BB,CC,DD,EE,FF'
AS csvdata

FROM DUAL)
SELECT REGEXP_SUBSTR (csv.csvdata, '[^,]+', 1, LEVEL) pivot_char
FROM DUAL, csv
CONNECT BY REGEXP_SUBSTR (csv.csvdata,'[^,]+', 1, LEVEL) IS NOT NULL;

43.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 *
FROM employees
WHERE ROWID IN (SELECT MAX (ROWID) FROM employees);

(OR)

SELECT * FROM employees


MINUS
SELECT *
FROM employees
WHERE ROWNUM < (SELECT COUNT (*) FROM employees);

44.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 Oracle
WITH tbl
AS (SELECT -2 num FROM DUAL
UNION
SELECT -3 num FROM DUAL
UNION
SELECT -4 num FROM DUAL),
sign_val

AS (SELECT CASE MOD (COUNT (*), 2) WHEN 0 THEN 1 ELSE -1 END val
FROM tbl
WHERE num < 0)
SELECT EXP (SUM (LN (ABS (num)))) * val
FROM tbl, sign_val
GROUP BY val;

45.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
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)) address
FROM DUAL
CONNECT BY LEVEL < 10000;

46.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 100

SELECT ROUND (DBMS_RANDOM.VALUE () * 100) + 1 AS random_num FROM DUAL;

47.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.
SELECT 1
FROM TABLE_NAME
WHERE ROWNUM = 1;

If you have some cool query that can make life of other Oracle developers easy, do share in
comment section.
Oracle PL/SQL Questions:
1. What is the difference between a view and a materialized view ?
Ans:
i)A View is stored in database as SQL statement. It is created as and when needed.
Materialized view is created as a table and stored physically in the database.
ii) Views created from multiple tables cannot be modified Materialized view can be modified
iii) Views are used to hide the complexity of SQL statement. For Eg: if you have a SQL
statement with 3 tables joined by UNION with different WHERE clauses, it will be faster to have
a view and just select from the view instead of complex SQL stmt.
Materialized views are the tables with pre-calculated joins and aggregated data from multiple
tables. They improve performance as the it precalcutes the joins and aggregations and stores the
results into the database even before the execution. When the query is executed, the query
optimizer rewrites the query to use the materialized view instead of the underlying detail tables.
2. What are outer joins ? Name its types ?
Ans : Outer joins are used to join 2 tables so that the unmatched rows from one table are also
retrived along with the matching rows. There are 3 types of outer joins: Left outer join, right
outer join and Full outer join.

Left Outer Join :unmatched rows from left table, (+) should to attached to the right table.
Right outer join :unmatched rows from right table, (+) should to attached to the left table.
To avoid the confusion with (+) symbol, from oracle 9i, we use the word ' left outer join' Eg:
select....from emp e LEFT OUTER JOIN dept d where emp.deptno = d.deptno;
Full Outer join is a combination of left and right outer join. For eg: you want to see a list of all
projects and the tasks associated with all projects.
Eg: select t.task_name, p.project_name
from all_tasks FULL OUTER JOIN all_projects
where t.project_id = p.project_id;
3. How does the use of a package improves the performance ?
Ans: i) When you call a packaged function or subrpogram, the whole package is called and
stored into the the memory. So the next time when we call any packaged function/subprogram,
there is no need of disk I/O
ii) Packages stop cascading dependencies and unnessasary recompiling. When a packaged
function is compiled, Oracle does not recompile the calling subprogram. That program will be
recompiled only if we made any changes in the specs of the calling program.
4.Can we have a procedure declared in package body but not declared in package specifications?
Ans: Yes.But that procedure will be local and can not be called by other procedures in the
package.When we declare a proc in package spec, it becomes global for the package.
5. Can we have a package spec without a body?
Ans:Yes
6. Can we have a procedure spec without body ?
Ans: No. It should atleast have NULL; inside begin and end.
7. Can we have a commit in trigger?
Ans: Yes. You can commit inside the trigger but you have to declare it as
AUTONOMOUS_TRANSACTION.

8. How do u use variable in code of a trigger ?


Ans: by using':old' and ':new' clauses. Eg :old.salary, :new.salary
9. You wrote a PL/SQL stored procedure. How do u make it hidden so that NOBODY,not even
the DBA or the owner can read the procedure ?
Ans: Use Wrap feature of Oracle 9i. Once wrapped, NO one, can read the code. Eg : Wrap
iname=c:\programs\my_file.sql. OR wrap iname=c:\programs\my_file.plb. .plb extension is
PL/SQL Binary file, output file of the wrap function.
10. What do you know about STANDARD package in Oracle ?
Ans: A package named STANDARD defines the PL/SQL environment. The package spec
includes All the types, functions, procedures, etc which are automaticaly available to
PL/SQLprograms. For eg: ABS(),SUM(),COUNT()
11. Name some Oracle's built-in packages?
Ans:
DBMS_OUTPUT - used to display a messgae, especially while debugging
DBMS_PIPE - This allows 2 different sessions of the database to communicate over the named
pipe.
DBMS_DDL - Contains procedures to wrap single PL/SQL units like package specs, package
body, function, procedure, type specs, type body, etc. Eg :
DBMS_DDL.CREATE_WRAPPED();
DBMS_ALERT - lets you use database triggers to alert an application when some database
values change
UTL_FILE - it allows the PL/SQL program to read from and write into text files.
UTL_SMTP - allows the PL/SQL program to send emails over Simple Mail Transfer Protocol
UTL_HTP, HTF - allows PL/SQL to generate HTML tags.
UTL_HTTP - allows PL/SQL programs to make HTTP calls. It gets the data from Internet. The
inputs ar the URL and the contacts of the website. The return data is usually in HTML format.

DBMS_SQL - Helps you to write stored procedures and anonymous PL/SQL blocks that use
dynamic SQL. For ex: it allows us to create a procedure based on a table, whose name is given at
run-time.
12. What are database trigger? Types of database trigger?
Ans: These are the stored subprograms associated with tables, views , schemas or database
Table level triggers - 3 ways to catagorize these triggers : Before/After , Insert/Update/Delete,
and Row-level (for each row) vs statement-level
View level - We cannot use the Before/After triggers on views, so we use " Instead of " triggers.
Eg: Create or replace trigger trg_cal_sal INSTEAD OF INSERT on v_emp....
System triggers on database or Schema level - event triggers : Eg: LOGON, LOGOFF
13. What are implicit and explicit Cursors? Which one is recommended ?
Ans: A cursor is a handle or a pointer for the memory associated with a specific SQL statement.
A cursor is basically an area allocated by Oracle for executing the Sql Statement. An implicit
cursor statement are managed by Oracle itself and generally used for Single row query. When u
need precise control on the cursor and its processing, use Explcit cursors used for multi row
query.
Implicit cursor is always faster than explicit cursor.Bcoz, expilit cursor will have more no of
lines, and the rule is "Less the no of lines less is the processing time." Also, implicit cursor does
exception handling for NO_DATA_FOUND and TOO_MANY_ROWS by itself . We need not to
write these exceptions. In explicit cursors, we have to write these exceptions.
14. What is mutating error? How do u resolve it?
Ans : When you perform a DML query (like Insert, Update, Delete) on a table,and another query
is accessing the same table at the same time,none of the queries get completed and the table is
called as mutuating table.It will then throw a mutating error. You can perform only 'Select' on
such a table. You can resolve this error by using a PL/SQL table.
15.What is the difference between cursor & ref cursor?
Ans: Cursor is a handle or pointer to the memory location associated with a SQL statement. With
a REF cursor, you can define a cursor variable, which will point to that memory space. With Ref
cursor, we can dynamically retrive data in form of recordset from a PL/SQL stored procedure.
It works very similar to explicit cursor except that we define the query for this cursor at run-time.
The syntax of explicit cursor :

Cursor emp_cur IS
SELECT * from emp;
.......
OPEN emp_cur;
Syntax of REF cursor :
TYPE emp_curtype IS REF CURSOR RETURN emp%ROWTYPE; --cursor type
emp_curvar emp_curtype; --cursor variable
.........
v_state := 'NY'
OPEN emp_curvar FOR select * from emp where state = v_state;
..........
v_state := 'NJ'
OPEN emp_curvar FOR select * from emp where state = v_state;
As you can see, REF cursors can be reused for different SQL queries at runtime.
There are 2 types of REF cursors : Strong and weak.
TYPE emp_curtype IS REF CURSOR RETURN emp%ROWTYPE; --Strong REF cursor
TYPE emp_curtype IS REF CURSOR; --weak REF cursor
Which one is better ? depends on your requirement. In strong cursor, we attach the return
ROWTYPE at the declaration time itself. So, the compiler knows what the cursor variable should
return.So, its less error prone. Weak cursors , on the other hand , are more flexible because they
can be used with any query, any return ROWTYPE , even different ROWTYPES at different
calls to it.

16. What are different options in function declaration ?


Ans:

AUTHID : Specifies how to execute the function. Ex: DEFINER/CURRENT USER


PARALLEL_ENABLE: Specifies if we can run the function parallelly
DETERMINISTIC:
AUTONOMOUS_TRANSACTION: Specifies if this function is an Autonous Transaction
17. What is PRAGMA ? What are the different types of PRAGMA ?
Ans: Pragmas are specially formatted comments. Pragma tells Oracle to use specific rules other
than the default rules for a particular object. They are processed at compile time, not at run time.
1. RESTRICTED_REFERENCES : This pragma checks if the function meets the rules.
create package cal_loans as
function credit_ok return boolean;
PRAGMA RESTRICTED_REFERENCES(credit_ok, RNPS,WNDS );
WNDS - Write No Database State
RNPS - Read No Package State
2. EXCEPTION_INIT : This pragma is used to bind a user-defined exception to a particular
number.
Declare MyExcep exception;
PRAGMA EXCEPTION_INIT(MyExcep,10001);
begin
..
exception
when I then
dbms_output.put_line( 'Duplicate value');
end;
3. AUTONOMOUS_TRANSACTION: Its a kind of PRAGMA which changes the way a
subprogram works within a transaction. A child program marked with this pragma can be
committed and rolled back without committing or rolling back the parent transaction.

Eg : When you declare a trigger as AUTONOMOUS_TRANSACTION, then you can commit


inside the trigger, irrespective of the calling procedure.
CREATE OR REPLACE TRIGGER audit_sal
AFTER UPDATE OF salary ON employees FOR EACH ROW
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
-- bind variables are used here for values
INSERT INTO emp_audit VALUES( :old.employee_id, SYSDATE,
:new.salary, :old.salary );
COMMIT;
END;
4. SERIALLY_REUSABLE: This pragma tells the PL/SQL engine to reuse the package data. By
default, the package level data is available throughout the session, by specifing this pragma, the
data will not persist after the package is executed. You should specify the PRAGMA in both,
package specification and body.
18.How to avoid errors with Autonomous transactions?
Ans:
1. If the autonomous transactions uses the resources used by main transac, a deadlock will occur.
2. The auto transac should be commited or rolled back beforeexiting, or oracle will give error.
3. The maximum no of concurrent transac is set by Oracle. That number might be exceeded as
autonomous transac and main transac run concurrently.
19.What is the difference between Autonomous Transaction and Nested Transaction ?
Ans: As in case of Nested Transaction, Autonomous Transaction :
1. Do not share trasaction resources like variables with main transaction.
2.Have to be commited or rolled back separately.
3. It does not depend on main transaction. When main transaction rolls back, nested transaction
also rolls back but autonomous transaction does not.
4.Exceptions raised in autonomous transaction are transaction-level and not statement-level.
20.What is the difference between ANY and ALL conditions?

Ans:ANY will check for the rows in the right side matching the condition and returns the rows
for which the condition is true. It will not wait and search for all rows.
ALL will check if the condition is true for ALL rows and then only it will return the value.
21.What is the difference between UNION and UNION ALL?
Ans: Both do the same job but UNION ALL will give all rows,whereas UNION will skip the
duplicate rows and give only distinct rows. Hence, UNION is faster than UNION ALL.
22.What is the difference between CHAR and VARCHAR2?
Ans:Char is used for fixed length strings, varchar2 is used for variable length string. Char is
faster than varchar2,so if the length is fixed and not very long, it is recommanded to use Char.
23.What is the difference between EXISTS and IN operator?
Ans:IN works same as OR operator. The IN statement is internally converted into no of OR
statements.It returns all the values for which the condition matches. EXISTS first analyzes the
subquery to check if it returns any rows. If yes, then it returns True, else it returns False.
Exists - always has a subquery, IN- may have a subquery of list of values.
Example:
SELECT e.* from employees e
where exists(select deptno from dept d where e.deptno = d.deptno);
24.What are Global Temporary tables?
Ans: The temporary tables are the database tables or PL/SQL tables. The maintainance and
management of these tables is handled by Global Temporary Tables. They are temporary because
the data is available only to the current session. They are called as Global because the table
definition is available to all sessions.
Example: Create global temporary table my_g_temp_tab(
name varchar2(20), city varchar2(10) )
on commit delete rows /*OR on commit reserve rows*/;
25.
Heres 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


1. 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;

2. 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;

3. 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;

4. 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

5. 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') AS INT) number_of_days
FROM DUAL;

6. Get number of days left in current month

Below query calculates number of days left in current month.


SELECT SYSDATE,
LAST_DAY (SYSDATE) "Last",
LAST_DAY (SYSDATE) - SYSDATE "Days left"
FROM DUAL;

7. Get number of days between two dates

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_days
FROM DUAL;

OR

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.
8. 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,
FLOOR (
MONTHS_BETWEEN (
ADD_MONTHS (TRUNC (SYSDATE, 'YEAR') - 1, 12),
SYSDATE)))

COLUMNS i INTEGER PATH '.');

9. Get number of seconds passed since today (since 00:00 hr)


SELECT (SYSDATE - TRUNC (SYSDATE)) * 24 * 60 * 60 num_of_sec_since_morning
FROM DUAL;

10.Get number of seconds left today (till 23:59:59 hr)


SELECT (TRUNC (SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_left
FROM DUAL;

11.

Data dictionary queries

12.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).
SELECT table_name
FROM user_tables
WHERE table_name = 'TABLE_NAME';

13.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
FROM user_tab_cols
WHERE table_name = 'TABLE_NAME' AND column_name = 'COLUMN_NAME';

14.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.

SELECT DBMS_METADATA.get_ddl ('TABLE', 'TABLE_NAME', 'USER_NAME') FROM DUAL;

15.Getting current schema

Yet another query to get current schema name.


SELECT SYS_CONTEXT ('userenv', 'current_schema') FROM DUAL;

16.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.
ALTER SESSION SET CURRENT_SCHEMA = new_schema;

Database administration queries


17.Database version information

Returns the Oracle database version.


SELECT * FROM v$version;

18.Database default information

Some system default information.


SELECT username,
profile,
default_tablespace,
temporary_tablespace
FROM dba_users;

19.Database Character Set information

Display the character set information of database.


SELECT * FROM nls_database_parameters;

20.Get Oracle version


SELECT VALUE

FROM v$system_parameter
WHERE name = 'compatible';

21.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 dont occupy more space. Feel free to experiment with this one.
CREATE TABLE tab (col1 VARCHAR2 (10));

CREATE INDEX idx1


ON tab (UPPER (col1));

ANALYZE TABLE a COMPUTE STATISTICS;

22.Resizing Tablespace without adding datafile

Yet another DDL query to resize table space.


ALTER DATABASE DATAFILE '/work/oradata/STARTST/STAR02D.dbf' resize 2000M;

23.Checking autoextend on/off for Tablespaces

Query to check if autoextend is on or off for a given tablespace.


SELECT SUBSTR (file_name, 1, 50), AUTOEXTENSIBLE FROM dba_data_files;

(OR)

SELECT tablespace_name, AUTOEXTENSIBLE FROM dba_data_files;

24.Adding datafile to a tablespace

Query to add datafile in a tablespace.


ALTER TABLESPACE data01 ADD DATAFILE '/work/oradata/STARTST/data01.dbf'

SIZE 1000M AUTOEXTEND OFF;

25.Increasing datafile size

Yet another query to increase the datafile size of a given datafile.


ALTER DATABASE DATAFILE '/u01/app/Test_data_01.dbf' RESIZE 2G;

26.Find the Actual size of a Database

Gives the actual database size in GB.


SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_data_files;

27.Find the size occupied by Data in a Database or Database usage details

Gives the size occupied by data in this database.


SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_segments;

28.Find the size of the SCHEMA/USER

Give the size of user in MBs.


SELECT SUM (bytes / 1024 / 1024) "size"
FROM dba_segments
WHERE owner = '&owner';

29.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.
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 sqltext

FROM v$sqltext_with_newlines t, V$SESSION s, v$process p


WHERE

t.address = s.sql_address
AND p.addr = s.paddr(+)
AND t.hash_value = s.sql_hash_value

ORDER BY s.sid, t.piece;

Performance related queries


30.CPU usage of the USER

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 IS NOT NULL

ORDER BY VALUE DESC;

31.Long Query progress in database

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 b
WHERE

a.sid = b.sid

AND b.username NOT IN ('SYS', 'SYSTEM')


AND totalwork > 0
ORDER BY elapsed_seconds;

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.
SELECT b.sid,
b.serial#,
a.spid processid,
b.process clientpid
FROM v$process a, v$session b
WHERE a.addr = b.paddr AND b.audsid = USERENV ('sessionid');
o

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.

33.Last SQL Fired from particular Schema or Table:


SELECT CREATED, TIMESTAMP, last_ddl_time
FROM all_objects
WHERE

OWNER = 'MYSCHEMA'
AND OBJECT_TYPE = 'TABLE'
AND OBJECT_NAME = 'EMPLOYEE_TABLE';

34.Find Top 10 SQL by reads per execution


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
FROM v$sqlarea a
ORDER BY 3 DESC)
WHERE ROWNUM < 10;

35.Oracle SQL query over the view that shows actual Oracle connections.
SELECT osuser,
username,
machine,
program
FROM v$session
ORDER BY osuser;

36.Oracle SQL query that show the opened connections group by the program
that opens the connection.
SELECT program application, COUNT (program) Numero_Sesiones
FROM v$session
GROUP BY program
ORDER BY Numero_Sesiones DESC;

37.Oracle SQL query that shows Oracle users connected and the sessions
number for user
SELECT username Usuario_Oracle, COUNT (username) Numero_Sesiones
FROM v$session
GROUP BY username
ORDER BY Numero_Sesiones DESC;

38.Get number of objects per owner

SELECT owner, COUNT (owner) number_of_objects


FROM dba_objects
GROUP BY owner
ORDER BY number_of_objects DESC;

39.

Utility / Math related queries

40.Convert number to words

More info: Converting number into words in Oracle


SELECT TO_CHAR (TO_DATE (1526, 'j'), 'jsp') FROM DUAL;

Output:
one thousand five hundred twenty-six

41.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.
--search a string foo_something in package source code
SELECT *
FROM dba_source
WHERE UPPER (text) LIKE '%FOO_SOMETHING%'
AND owner = 'USER_NAME';

42.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.
WITH csv
AS (SELECT 'AA,BB,CC,DD,EE,FF'
AS csvdata

FROM DUAL)
SELECT REGEXP_SUBSTR (csv.csvdata, '[^,]+', 1, LEVEL) pivot_char
FROM DUAL, csv
CONNECT BY REGEXP_SUBSTR (csv.csvdata,'[^,]+', 1, LEVEL) IS NOT NULL;

43.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 *
FROM employees
WHERE ROWID IN (SELECT MAX (ROWID) FROM employees);

(OR)

SELECT * FROM employees


MINUS
SELECT *
FROM employees
WHERE ROWNUM < (SELECT COUNT (*) FROM employees);

44.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 Oracle
WITH tbl
AS (SELECT -2 num FROM DUAL
UNION
SELECT -3 num FROM DUAL
UNION
SELECT -4 num FROM DUAL),
sign_val

AS (SELECT CASE MOD (COUNT (*), 2) WHEN 0 THEN 1 ELSE -1 END val
FROM tbl
WHERE num < 0)
SELECT EXP (SUM (LN (ABS (num)))) * val
FROM tbl, sign_val
GROUP BY val;

45.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
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)) address
FROM DUAL
CONNECT BY LEVEL < 10000;

46.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 100

SELECT ROUND (DBMS_RANDOM.VALUE () * 100) + 1 AS random_num FROM DUAL;

47.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.
SELECT 1
FROM TABLE_NAME
WHERE ROWNUM = 1;

If you have some cool query that can make life of other Oracle developers easy, do share in
comment section.

Straightforward method is to query as below..


DELETE
FROM EMP E1
WHERE ROWID <
( SELECT MAX(ROWID) FROM EMP WHERE ENAME=E1.ENAME
);

DELETE
FROM EMP E1
WHERE ROWID >
( SELECT MIN (ROWID) FROM EMP WHERE ENAME=E1.ENAME
);
Query structure:
Delete from Alias
where rowid < ( select max(rowid) from where );
1. A tablespace has a table with 30 extents in it. Is this bad? Why or why not?
Level: Intermediate
Expected answer: Multiple extents in and of themselves aren't bad. However if you also have
chained rows this can hurt performance.

2. How do you set up tablespaces during an Oracle installation?


Level: Low
Expected answer: You should always attempt to use the Oracle Flexible Architecture standard or
another partitioning scheme to ensure proper separation of SYSTEM, ROLLBACK, REDO
LOG, DATA, TEMPORARY and INDEX segments.
3. You see multiple fragments in the SYSTEM tablespace, what should you check first?
Level: Low
Expected answer: Ensure that users don't have the SYSTEM tablespace as their TEMPORARY
or DEFAULT tablespace assignment by checking the DBA_USERS view.
4. What are some indications that you need to increase the SHARED_POOL_SIZE parameter?
Level: Intermediate
Expected answer: Poor data dictionary or library cache hit ratios, getting error ORA-04031.
Another indication is steadily decreasing performance with all other tuning parameters the same.
5. What is the general guideline for sizing db_block_size and db_multi_block_read for an
application that does many full table scans?
Level: High
Expected answer: Oracle almost always reads in 64k chunks. The two should have a product
equal to 64 or a multiple of 64.
6. What is the fastest query method for a table?
Level: Intermediate
Expected answer: Fetch by rowid
7. Explain the use of TKPROF? What initialization parameter should be turned on to get full
TKPROF output?
Level: High
Expected answer: The tkprof tool is a tuning tool used to determine cpu and execution times for
SQL statements. You use it by first setting timed_statistics to true in the initialization file and
then turning on tracing for either the entire database via the sql_trace parameter or for the session
using the ALTER SESSION command. Once the trace file is generated you run the tkprof tool
against the trace file and then look at the output from the tkprof tool. This can also be used to
generate explain plan output.
8. When looking at v$sysstat you see that sorts (disk) is high. Is this bad or good? If bad, how do
you correct it?
Level: Intermediate
Expected answer: If you get excessive disk sorts this is bad. This indicates you need to tune the
sort area parameters in the initialization files. The major sort are parameter is the
SORT_AREA_SIZe parameter.

9. When should you increase copy latches? What parameters control copy latches?
Level: high
Expected answer: When you get excessive contention for the copy latches as shown by the "redo
copy" latch hit ratio. You can increase copy latches via the initialization parameter
LOG_SIMULTANEOUS_COPIES to twice the number of CPUs on your system.
10. Where can you get a list of all initialization parameters for your instance? How about an
indication if they are default settings or have been changed?
Level: Low
Expected answer: You can look in the init.ora file for an indication of manually set parameters.
For all parameters, their value and whether or not the current value is the default value, look in
the v$parameter view.

S-ar putea să vă placă și