Professional Documents
Culture Documents
SQLs
SQLs
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
SELECT D.DNAME
FROM DEPT D
WHERE
NOT EXISTS (SELECT * FROM EMP E WHERE D.DEPTNO = E.DEPTNO)
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)
�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
***********************************************************************************
*********
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?
Pseudo-column
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
UID and USER Return the User ID and Name of a database user:
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:
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
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.
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.
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)
);
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);
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')));
***********************************************************************************
*********
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.