You are on page 1of 7

Link:

http://sql-plsql.blogspot.sg/2009/04/sql-interview-questions.html

***********************************************************************************
*********

To get the dept name from DEPT table who has no employees assigned in EMP table.

Table Structure:

EMP:
EMPNO ENAME DEPTNO

DEPT:
DEPTNO DNAME

It's only correct with NOT EXISTS

SELECT D.DNAME
FROM DEPT D
WHERE
NOT EXISTS (SELECT * FROM EMP E WHERE D.DEPTNO = E.DEPTNO)

or EXCEPT, more complex in this case

SELECT D.DNAME
FROM DEPT D
EXCEPT
SELECT D.DNAME
FROM DEPT D
JOIN EMP E WHERE D.DEPTNO = E.DEPTNO

Both should give the same plan (with a left anti semi join)

Notes on other answers:

�A LEFT JOIN will give one row per employee. You'd need DISTINCT. Which compromises
the plan compared with NOT EXISTS

�NOT IN will give false results if there is an Employee who has no Department. NOT
IN with a NULL in the list fails

So generally one should use NOT EXISTS or EXCEPT

***********************************************************************************
*********
There are 2 tables, Employee and Department. There are few records in employee
table, for which, the department is not assigned. The output of the query should
contain all th employees names and their corresponding departments, if the
department is assigned otherwise employee names and null value in the place
department name. What is the query?

select Employee.name, Department.name


FROM Employee
where
Employee.Employee_ID=Department.Employee_ID(+)
***********************************************************************************
*********

Pseudo-column

A pseudo-column is an Oracle assigned value (pseudo-field) used in the same context


as an Oracle Database column, but not stored on disk. SQL and PL/SQL recognizes the
following SQL pseudocolumns, which return specific data items: SYSDATE,
SYSTIMESTAMP, ROWID, ROWNUM, UID, USER, LEVEL, CURRVAL, NEXTVAL, ORA_ROWSCN, etc.

Pseudocolumns are not actual columns in a table but they behave like columns. For
example, you can select values from a pseudocolumn. However, you cannot insert
into, update, or delete from a pseudocolumn. Also note that pseudocolumns are
allowed in SQL statements, but not in procedural statements.

Contents
1 SYSDATE and SYSTIMESTAMP
2 UID and USER
3 CURRVAL and NEXTVAL
4 LEVEL
5 ROWID
6 ROWNUM
7 ORA_ROWSCN

SYSDATE and SYSTIMESTAMPReturn the current DATE and TIMESTAMP:

SQL> SELECT sysdate, systimestamp FROM dual;


SYSDATE SYSTIMESTAMP
--------- ----------------------------------------
13-DEC-07 13-DEC-07 10.02.31.956842 AM +02:00

UID and USER Return the User ID and Name of a database user:

SQL> SELECT uid, user FROM dual;


UID USER
---------- ------------------------------
50 MICHEL

CURRVAL and NEXTVALA sequence is a schema object that generates sequential numbers.
When you create a sequence, you can specify its initial value and an increment.
CURRVAL returns the current value in a specified sequence.

Before you can reference CURRVAL in a session, you must use NEXTVAL to generate a
number. A reference to NEXTVAL stores the current sequence number in CURRVAL.
NEXTVAL increments the sequence and returns the next value. To obtain the current
or next value in a sequence, you must use dot notation, as follows:

sequence_name.CURRVAL
sequence_name.NEXTVAL

After creating a sequence, you can use it to generate unique sequence numbers for
transaction processing. However, you can use CURRVAL and NEXTVAL only in a SELECT
list, the VALUES clause, and the SET clause. In the following example, you use a
sequence to insert the same employee number into two tables:

INSERT INTO emp VALUES (empno_seq.NEXTVAL, my_ename, ...);


INSERT INTO sals VALUES (empno_seq.CURRVAL, my_sal, ...);
If a transaction generates a sequence number, the sequence is incremented
immediately whether you commit or roll back the transaction.

LEVELYou use LEVEL with the SELECT CONNECT BY statement to organize rows from a
database table into a tree structure. LEVEL returns the level number of a node in a
tree structure. The root is level 1, children of the root are level 2,
grandchildren are level 3, and so on.

In the START WITH clause, you specify a condition that identifies the root of the
tree. You specify the direction in which the query walks the tree (down from the
root or up from the branches) with the PRIOR operator.

ROWID:
ROWID returns the rowid (binary address) of a row in a database table. You can use
variables of type UROWID to store rowids in a readable format. In the following
example, you declare a variable named row_id for that purpose: DECLARE row_id
UROWID;

When you select or fetch a physical rowid into a UROWID variable, you can use the
function ROWIDTOCHAR, which converts the binary value to an 18-byte character
string. Then, you can compare the UROWID variable to the ROWID pseudocolumn in the
WHERE clause of an UPDATE or DELETE statement to identify the latest row fetched
from a cursor.

ROWNUM
ROWNUM returns a number indicating the order in which a row was selected from a
table. The first row selected has a ROWNUM of 1, the second row has a ROWNUM of 2,
and so on. If a SELECT statement includes an ORDER BY clause, ROWNUMs are assigned
to the retrieved rows before the sort is done.

You can use ROWNUM in an UPDATE statement to assign unique values to each row in a
table. Also, you can use ROWNUM in the WHERE clause of a SELECT statement to limit
the number of rows retrieved, as follows:

DECLARE
CURSOR c1 IS SELECT empno, sal FROM emp
WHERE sal > 2000 AND ROWNUM < 10; -- returns 9 rows
The value of ROWNUM increases only when a row is retrieved, so the only meaningful
uses of ROWNUM in a WHERE clause are

... WHERE ROWNUM < constant;


... WHERE ROWNUM <= constant;

ORA_ROWSCN:
ORA_ROWSCN returns the system change number (SCN) of the last change inside the
block containing a row. It can return the last modification for the row if the
table is created with the option ROWDEPENDENCIES (default is NOROWDEPENDENCIES).
The function SCN_TO_TIMESTAMP allows you to convert SCN to timestamp.

SQL> select ename, ORA_ROWSCN, SCN_TO_TIMESTAMP(ORA_ROWSCN) from emp where


empno=7369;
ENAME ORA_ROWSCN SCN_TO_TIMESTAMP(ORA_ROWSCN)
---------- ----------
----------------------------------------------------------------
SMITH 2113048 20/12/2008 16:59:51.000

link:
http://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns.htm

***********************************************************************************
*********

Partitioning:

Link:
http://docs.oracle.com/cd/B19306_01/server.102/b14220/partconc.htm

Introduction to Partitioning
Partitioning addresses key issues in supporting very large tables and indexes by
letting you decompose them into smaller and more manageable pieces called
partitions. SQL queries and DML statements do not need to be modified in order to
access partitioned tables. However, after partitions are defined, DDL statements
can access and manipulate individuals partitions rather than entire tables or
indexes. This is how partitioning can simplify the manageability of large database
objects. Also, partitioning is entirely transparent to applications.
Each partition of a table or index must have the same logical attributes, such as
column names, datatypes, and constraints, but each partition can have separate
physical attributes such as pctfree, pctused, and tablespaces.
Partitioning is useful for many different types of applications, particularly
applications that manage large volumes of data. OLTP systems often benefit from
improvements in manageability and availability, while data warehousing systems
benefit from performance and manageability.
Note:
All partitions of a partitioned object must reside in tablespaces of a single block
size.

Partitioning offers these advantages:


�Partitioning enables data management operations such data loads, index creation
and rebuilding, and backup/recovery at the partition level, rather than on the
entire table. This results in significantly reduced times for these operations.
�Partitioning improves query performance. In many cases, the results of a query can
be achieved by accessing a subset of partitions, rather than the entire table. For
some queries, this technique (called partition pruning) can provide order-of-
magnitude gains in performance.
�Partitioning can significantly reduce the impact of scheduled downtime for
maintenance operations.
Partition independence for partition maintenance operations lets you perform
concurrent maintenance operations on different partitions of the same table or
index. You can also run concurrent SELECT and DML operations against partitions
that are unaffected by maintenance operations.
�Partitioning increases the availability of mission-critical databases if critical
tables and indexes are divided into partitions to reduce the maintenance windows,
recovery times, and impact of failures.
�Partitioning can be implemented without requiring any modifications to your
applications. For example, you could convert a nonpartitioned table to a
partitioned table without needing to modify any of the SELECT statements or DML
statements which access that table. You do not need to rewrite your application
code to take advantage of partitioning.

Oracle provides the following partitioning methods:


�Range Partitioning
�List Partitioning
�Hash Partitioning
�Composite Partitioning

Range Partitioning
Range partitioning maps data to partitions based on ranges of partition key values
that you establish for each partition. It is the most common type of partitioning
and is often used with dates. For example, you might want to partition sales data
into monthly partitions.
When using range partitioning, consider the following rules:
�Each partition has a VALUES LESS THAN clause, which specifies a noninclusive upper
bound for the partitions. Any values of the partition key equal to or higher than
this literal are added to the next higher partition.
�All partitions, except the first, have an implicit lower bound specified by the
VALUES LESS THAN clause on the previous partition.
�A MAXVALUE literal can be defined for the highest partition. MAXVALUE represents a
virtual infinite value that sorts higher than any other possible value for the
partition key, including the null value.
A typical example is given in the following section. The statement creates a table
(sales_range) that is range partitioned on the sales_date field.
Range Partitioning Example
CREATE TABLE sales_range
(salesman_id NUMBER(5),
salesman_name VARCHAR2(30),
sales_amount NUMBER(10),
sales_date DATE)
PARTITION BY RANGE(sales_date)
(
PARTITION sales_jan2000 VALUES LESS THAN(TO_DATE('02/01/2000','MM/DD/YYYY')),
PARTITION sales_feb2000 VALUES LESS THAN(TO_DATE('03/01/2000','MM/DD/YYYY')),
PARTITION sales_mar2000 VALUES LESS THAN(TO_DATE('04/01/2000','MM/DD/YYYY')),
PARTITION sales_apr2000 VALUES LESS THAN(TO_DATE('05/01/2000','MM/DD/YYYY'))
);

List Partitioning
List partitioning enables you to explicitly control how rows map to partitions. You
do this by specifying a list of discrete values for the partitioning key in the
description for each partition. This is different from range partitioning, where a
range of values is associated with a partition and from hash partitioning, where a
hash function controls the row-to-partition mapping. The advantage of list
partitioning is that you can group and organize unordered and unrelated sets of
data in a natural way.
The details of list partitioning can best be described with an example. In this
case, let's say you want to partition a sales table by region. That means grouping
states together according to their geographical location as in the following
example.
List Partitioning Example
CREATE TABLE sales_list
(salesman_id NUMBER(5),
salesman_name VARCHAR2(30),
sales_state VARCHAR2(20),
sales_amount NUMBER(10),
sales_date DATE)
PARTITION BY LIST(sales_state)
(
PARTITION sales_west VALUES('California', 'Hawaii'),
PARTITION sales_east VALUES ('New York', 'Virginia', 'Florida'),
PARTITION sales_central VALUES('Texas', 'Illinois'),
PARTITION sales_other VALUES(DEFAULT)
);

A row is mapped to a partition by checking whether the value of the partitioning


column for a row falls within the set of values that describes the partition. For
example, the rows are inserted as follows:
�(10, 'Jones', 'Hawaii', 100, '05-JAN-2000') maps to partition sales_west
�(21, 'Smith', 'Florida', 150, '15-JAN-2000') maps to partition sales_east
�(32, 'Lee', 'Colorado', 130, '21-JAN-2000') maps to partition sales_other
Unlike range and hash partitioning, multicolumn partition keys are not supported
for list partitioning. If a table is partitioned by list, the partitioning key can
only consist of a single column of the table.
The DEFAULT partition enables you to avoid specifying all possible values for a
list-partitioned table by using a default partition, so that all rows that do not
map to any other partition do not generate an error.

Hash Partitioning
Hash partitioning enables easy partitioning of data that does not lend itself to
range or list partitioning. It does this with a simple syntax and is easy to
implement. It is a better choice than range partitioning when:
�You do not know beforehand how much data maps into a given range
�The sizes of range partitions would differ quite substantially or would be
difficult to balance manually
�Range partitioning would cause the data to be undesirably clustered
�Performance features such as parallel DML, partition pruning, and partition-wise
joins are important
The concepts of splitting, dropping or merging partitions do not apply to hash
partitions. Instead, hash partitions can be added and coalesced.
See Also:
Oracle Database Administrator's Guide for more information about partition tasks
such as splitting partitionsHash Partitioning Example
CREATE TABLE sales_hash
(salesman_id NUMBER(5),
salesman_name VARCHAR2(30),
sales_amount NUMBER(10),
week_no NUMBER(2))
PARTITION BY HASH(salesman_id)
PARTITIONS 4
STORE IN (ts1, ts2, ts3, ts4);

The preceding statement creates a table sales_hash, which is hash partitioned on


salesman_id field. The tablespace names are ts1, ts2, ts3, and ts4. With this
syntax, we ensure that we create the partitions in a round-robin manner across the
specified tablespaces.

Composite Partitioning
Composite partitioning partitions data using the range method, and within each
partition, subpartitions it using the hash or list method. Composite range-hash
partitioning provides the improved manageability of range partitioning and the data
placement, striping, and parallelism advantages of hash partitioning. Composite
range-list partitioning provides the manageability of range partitioning and the
explicit control of list partitioning for the subpartitions.
Composite partitioning supports historical operations, such as adding new range
partitions, but also provides higher degrees of parallelism for DML operations and
finer granularity of data placement through subpartitioning.
Composite Partitioning Range-Hash Example
CREATE TABLE sales_composite
(salesman_id NUMBER(5),
salesman_name VARCHAR2(30),
sales_amount NUMBER(10),
sales_date DATE)
PARTITION BY RANGE(sales_date)
SUBPARTITION BY HASH(salesman_id)
SUBPARTITION TEMPLATE(
SUBPARTITION sp1 TABLESPACE ts1,
SUBPARTITION sp2 TABLESPACE ts2,
SUBPARTITION sp3 TABLESPACE ts3,
SUBPARTITION sp4 TABLESPACE ts4)
(PARTITION sales_jan2000 VALUES LESS THAN(TO_DATE('02/01/2000','MM/DD/YYYY'))
PARTITION sales_feb2000 VALUES LESS THAN(TO_DATE('03/01/2000','MM/DD/YYYY'))
PARTITION sales_mar2000 VALUES LESS THAN(TO_DATE('04/01/2000','MM/DD/YYYY'))
PARTITION sales_apr2000 VALUES LESS THAN(TO_DATE('05/01/2000','MM/DD/YYYY'))
PARTITION sales_may2000 VALUES LESS THAN(TO_DATE('06/01/2000','MM/DD/YYYY')));

This statement creates a table sales_composite that is range partitioned on the


sales_date field and hash subpartitioned on salesman_id.

***********************************************************************************
*********

Hints:

Link:
http://docs.oracle.com/cd/B19306_01/server.102/b14211/hintsref.htm

16 Using Optimizer HintsOptimizer hints can be used with SQL statements to alter
execution plans. This chapter explains how to use hints to instruct the optimizer
to use specific approaches.

16.1 Understanding Optimizer Hints


Hints let you make decisions usually made by the optimizer. As an application
designer, you might know information about your data that the optimizer does not
know. Hints provide a mechanism to instruct the optimizer to choose a certain query
execution plan based on the specific criteria.
For example, you might know that a certain index is more selective for certain
queries. Based on this information, you might be able to choose a more efficient
execution plan than the optimizer. In such a case, use hints to instruct the
optimizer to use the optimal execution plan.
Note:
The use of hints involves extra code that must be managed, checked, and
controlled.16.1.1 Types of Hints
Hints can be of the following general types:
�Single-table
Single-table hints are specified on one table or view. INDEX and USE_NL are
examples of single-table hints.
�Multi-table
Multi-table hints are like single-table hints, except that the hint can specify one
or more tables or views. LEADING is an example of a multi-table hint. Note that
USE_NL(table1 table2) is not considered a multi-table hint because it is actually a
shortcut for USE_NL(table1) and USE_NL(table2).
�Query block
Query block hints operate on single query blocks. STAR_TRANSFORMATION and UNNEST
are examples of query block hints.
�Statement
Statement hints apply to the entire SQL statement. ALL_ROWS is an example of a
statement hint.

You might also like