Documente Academic
Documente Profesional
Documente Cultură
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
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.
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;
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;
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;
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
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;
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
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)))
11.
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';
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';
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.
ALTER SESSION SET CURRENT_SCHEMA = new_schema;
FROM v$system_parameter
WHERE name = 'compatible';
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));
(OR)
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
t.address = s.sql_address
AND p.addr = s.paddr(+)
AND t.hash_value = s.sql_hash_value
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
a.sid = b.sid
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
OWNER = 'MYSCHEMA'
AND OBJECT_TYPE = 'TABLE'
AND OBJECT_NAME = 'EMPLOYEE_TABLE';
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;
39.
Output:
one thousand five hundred twenty-six
Below query will search for string FOO_SOMETHING in all package source. This
query comes handy when you want to find a particular procedure or function call from all
the source code.
--search a string foo_something in package source code
SELECT *
FROM dba_source
WHERE UPPER (text) LIKE '%FOO_SOMETHING%'
AND owner = 'USER_NAME';
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;
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)
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;
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;
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
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.
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.
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.
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;
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;
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;
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
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;
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
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)))
11.
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';
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';
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.
ALTER SESSION SET CURRENT_SCHEMA = new_schema;
FROM v$system_parameter
WHERE name = 'compatible';
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));
(OR)
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
t.address = s.sql_address
AND p.addr = s.paddr(+)
AND t.hash_value = s.sql_hash_value
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
a.sid = b.sid
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
OWNER = 'MYSCHEMA'
AND OBJECT_TYPE = 'TABLE'
AND OBJECT_NAME = 'EMPLOYEE_TABLE';
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;
39.
Output:
one thousand five hundred twenty-six
Below query will search for string FOO_SOMETHING in all package source. This
query comes handy when you want to find a particular procedure or function call from all
the source code.
--search a string foo_something in package source code
SELECT *
FROM dba_source
WHERE UPPER (text) LIKE '%FOO_SOMETHING%'
AND owner = 'USER_NAME';
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;
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)
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;
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;
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
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.
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.
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.