You are on page 1of 65

What is SQL?

Structured Query Language (SQL) is a language that provides an interface to relational database
systems. SQL was developed by IBM in the 1970s for use in System R. SQL is a de facto standard, as
well as an ISO and ANSI standard. SQL is often pronounced SEQUEL.
What is the difference between SQL and SQL*PLUS?
SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and reporting tool.
Its a command line tool that allows user to type SQL commands to be executed directly against an
Oracle database. SQL is a language used to query the relational database (DML, DDL, DCL).
SQL*PLUS commands are used to format query result, Set options, Edit SQL commands & PL/SQL.
What is the difference between SQL and SQL*PLUS commands?
SQL commands are stored in a buffer where as SQL*PLUS are not.
Name some SQL*PLUS commands?
DESC[RIBE], START, DEFINE, GET, SAVE.
What are the SQL*PLUS reporting commands?
SPOOL. TTITLE, BTITLE, BREAK ON.
What is Schema and Schema Objects?
Schema is a collection of logical structure of data or Schema Objects. A Schema is owned by a
database user and has the same name as that of user. Each user owns a single Schema.
Schema Objects include the following type of objects Clusters, Database Links, Tables, Indexes,
Sequence, Synonyms, Views, Functions, Procedures, Database Triggers and Packages.
What is a Session?
The period between Login and Log-off on Schema.
How to display data Page Wise in SQL?

By using SET PAUSE ON command.


How to change Line Size and Page Size and SQL Prompt?
By using SET LINESIZE <value>, SET PAGESIZE <value>, SET SQLPROMPT <new prompt>.
What is Database?
The Collection of Interrelated Data is called Data Base.
What is Database Management System (DBMS) Package?
The Collection of Interrelated Data and some Programs to access the Data is Called Data Base
Management System (DBMS).
Describe Oracle database's physical and logical structure?
Physical: Data files, Redo Log files, Control file.
Logical: Tables, Views, Table spaces, etc.
What is database link?
A database link is a pointer that defines a one-way communication path from an oracle database server
to another database server
Ex: scott>Create database link <link name>
Connect to scott
Identified by tiger
Using '<link name>'
/
Scott> select * from dual@<link name>;
What are the types of Locks?
1) Share Lock
--- It allows the other users for only reading not to insert or update or delete.
2) Exclusive Lock
--- Only one user can have the privileges of insert or update and delete of particular object
--- Others can only read.
3) Update Lock
--- Multiple user can read, update delete

What are the types of Lock Levels?


(i)

Table level

(ii)

Table space

(iii)

Data base level.

What is Deadlock?
A deadlock can occur when two or more user are waiting for data locked by each other. Deadlocks
prevent some transactions from continuing to work.
What are the large OBJECT types supported by the Oracle?
BLOB
CLOB
What are the data types allowed in a table?
CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW
How many LONG columns are allowed in a table? Is it possible to use LONG columns in
WHERE clause or ORDER BY?
Only one LONG column is allowed. It is not possible to use LONG column in WHERE or ORDER
BY clause.
Which datatype is used for storing graphics and images?
LONG RAW data type is used for storing BLOB's (binary large objects).
What is the difference between CHAR, VARCHAR, VARCHAR2 data types?
CHAR

: CHAR is used for storing Fixed Length Character String.

VARCHAR

: It behaves exactly same as VARCHAR2. This type should not be


Used as it is reserved for future usage.

VARCHAR2 : VARCHAR2 is used for storing Variable Length Character String.


What is a DUAL table?
Dual is a table owned by SYS. It is a pseudo table, which consist of only one row and one column. The
column name is DUMMY and it holds the value X.
Can dual table be deleted, dropped or altered or updated or inserted?

Yes
If content of dual is updated to some value computation takes place or not?
Yes
If any other table same as dual is created would it act similar to dual?
Yes
What is ROWID?
ROWID is a pseudo column attached to each row of a table. It is 18 character long, block no, row
number are the components of ROWID
What is the difference between rowid and rownum?
ROWID is an internal representation of a row in a table, it is effectively the primary key and can be
used for fast access to the row
ROWNUM is a function of a result set of your query:
select * from emp where rownum = 1 will get the first row of your result set.
So rowid is a function of the table. rownum is a function of the result set.
What are the difference between DDL, DML, DQL, TCL and DCL commands?
DDL: DDL statements are used to define the data base structure or schema.
(A) CREATE
(B) ALTER
(C) DROP
DML: DML statements are used to manage the data with in the schema objects.
(A) INSERT
(B) UPDATE
(C) DELETE
DQL: DQL is used to get the data from data base objects for read only purpose
DCL: It is used to share information between users
(A) GRANT - It is used to give permission
(B) REVOKE - It is used to cancel the permission
TCL: It is used to control the DML operation.
(A) COMMIT

- It is used to save the data dynamically.

(B) ROLL BACK - It is used to cancel the changes.

(C) SAVEPOINT - It is used to mark the transactions.


What is a transaction?
A transaction is a set of SQL statements between any two COMMIT and ROLLBACK statements.
What is the maximum no. of columns a table can have?
1000
Is SYSDATE a system variable or a system function?
System Function
How can i see the time of execution of a sql statement?
SET TIME ON
IS 'DEFINE' a valid SQL statement?
DEFINE is a command of SQL * PLUS Tool. This is only valid in SQL * PLUS.
With DEFINE command, user can define the session variables.
What are pseudo-columns in SQL? Provide examples?
A pseudo column behaves like a table column, but is not actually stored in the table. You can select
from pseudo columns, but you cannot insert, update, or delete their values.
Ex: CURRVAL, NEXTVAL, ROWID, LEVEL
What is a dynamic SQL?
DDL statement used within PL/SQL using Execute Immediate
What is INDEX and what are the advantages?
An Index is a database object used to retrieve the data fastly from the Tables.
An Index increases the performance of the database.
How Oracle identifies each record of Table uniquely?
By Creating indexes and reference IDs.
What is the use of CLUSTER?

Clusters are an optional method of storing table data. A Cluster is a group of tables that share the same
data blocks because they share common columns and are often used together. It improves access time
for joins of clustered tables.
What are the Disadvantages of a CLUSTER?
Low performance in case of DML operations
Example: The EMPLOYEE and DEPARTMENT table share the DEPT_ID column. When you cluster
the employees and departments tables, Oracle physically stores all rows for each department from both
the tables.
Ex:
Step:1 Create a Cluster
Create CLUSTER c1(deptno number(2));
Step:2 Create a Employee table
Sql> Create table emp(empno number(4),
ename varchar2(15),
sal number(7),
deptno number(2)) cluster
c1(deptno);
Step:3 Create a Department table
Sql> Create table dept(dname varchar2(15),
deptno number(2),
loc varchar2(15)) cluster c1(deptno);
Step:4 Create a Index on Cluster
Sql> Create index id_c1 on cluster c1;
How to drop a CLUSTER when CLUSTERED table exists?
When cluster table exists it is not possible to drop the cluster, if we want drop the table first then only
cluster to be dropped.
What are the advantages of clusters?
Access time reduced for joins.
What are the disadvantages of clusters?
The time for Insert increases.

Can Long/Long RAW be clustered?


No
Can null keys be entered in cluster index, normal index?
Yes
What is ALTER command? How we use it to Add a new column?
ALTER command is used to modify the structure of table. By using alter we can add, modify & delete
columns. to change the data type or decrease the size of a column the column must be empty. For
ALTER a table we need ALTER, INSERT & CREATE privileges.
Ex: ALTER table <table_name> ADD <column_name> type(size);
Can we change the data type and size in a table when data is there and when data is not there?
When there is data we can increase the size, we can not decrease the size but we cannot change the
data type.
Yes we can change the data type and size when there is no data
What is difference between Update and Alter commands?
Alter command is used to modify the database objects where as the Update command is used to
modify the values of a data base object.
What is the use of INSERT ALL?
Is used for multiple insert more than one rows to more than one table.
Ex: INSERT ALL into emp2 values(empno,ename,job,sal,deptno,comm,hire_date) select * from emp;
What is the difference Rename and Alias?
Rename is a permanent name given to a table or column where as Alias is a temporary name given to a
table or column which does not exist once the SQL statement executed.
What is the use of AND condition?
The AND condition allows to create a SQL statement based on 2 or more conditions being met.
What is the use of OR condition?
The OR condition allows to create a SQL statement when any one of the conditions are met based on
the records returned.

What is the use of WHERE clause?


The WHERE clause allows to filter the results from an SQL statement. We can also the WHERE
clause to join multiple tables together in a single SQL statement.

What is the significance of the & and && operators in PL SQL?


The & operator means that the PL SQL block requires user input for a variable.
The && operator means that the value of this variable should be the same as Inputted by the user
previously for this same variable.
When do you use WHERE clause and when do you use HAVING clause?
HAVING clause is used when you want to specify a condition for a group function and it is written
after GROUP BY clause. The WHERE clause is used when you want to specify a condition for
columns, single row functions except group functions and it is written before GROUP BY clause if it
is used.
What is the use of GROUP BY clause?
The group by clause is another section of select statement. This option tells oracle to group rows based
on distinct values that exits or specified columns. The GROUP BY clause creates a data set, contained
several sets of records grouped tighter based on condition.
What is the use of HAVING clause?
The having clause can be used in conjunction with the GROUP BY clause. HAVING imposes a
condition on the GROUP BY clause, which further filters the groups created by GROUP BY clause.
What is the use of ORDER BY clause?
For sorting we use order by clause in select statement. This is used to sort data in
Ascending order or Descending order.
What is the use of LIKE condition?
The LIKE condition allows to perform pattern matching.
% It allows to match any string of any length (including zero length)
_ It allows to match on a single character

How does one escape special characters when building SQL queries?
The LIKE keyword allows for string searches. The '_' wild card character is used to match exactly one
character, '%' is used to match zero or more occurrences of any characters. These characters can be
escaped in SQL.
Ex: SELECT ename FROM emp WHERE empno LIKE '%_%' ESCAPE '\';
How does one escape special characters when writing SQL queries?
Use tow quotes for every one displayed.
Ex: SELECT 'franks Oracle Site' as text from dual;
What is meant by SORTING and GROUPING?
For sorting we use order by clause in select statement. This is used to sort data in Ascending order or
Descending order.
To group the data based on particular column we use group by clause.
What is the Difference between TRUNCATE, DELETE and DROP?
TRUNCATE : Truncate removes all rows from a table. The operation cannot be
rollback and no Triggers will be fired. It is faster than delete command.
DELETE

: Delete command is used to remove the rows from a table. A WHERE


clause can also be used to remove only some rows. After performing
delete operation you need to COMMIT or ROLLBACK the transaction
to make the changes permanent or to undo it.
For this delete operation all Delete triggers will be fire on the table.

DROP

: Drop command will removes a table from the database. All the Table
rows, Indexes and privileges will also be removed. No DML triggers
will be fired. The operation cannot be roll backed.

What is the use of GRANT?


Using GRANT command we can provide various privileges to users on tables.
What is the use of REVOKE?
Once we granted the privileges, we may need to cancel/revoke some or all privileges. To do this we
execute REVOKE command.

How to see what privileges given by user to other users?


Using USER_TAB_PRIVS_MADE
USER_COL_PRIVS_MADE
How to see what privileges received to user by owner user?
Using USER_TAB_PRIVS_RECD
USER_COL_PRIVS_RECD
What are the System and Object Privileges?
Connect and Resource etc are System Privileges.
Create <object>, Select, Insert, Alter etc are Object Privileges.
What is the GRANT command with "WITH GRANT OPTION"?
With Grant Option with Grant Command gives privileges to the user to grant privileges to other
user(s) among the privileges he/she has.
What are various privileges that a user can grant to another user?
(i)

SELECT

(ii)

CONNECT

(iii)

RESOURCES

What is the use of ROLLBACK?


The rollback statement undoes all the changes for the current session up to the save point specified. If
no save point specified then all changes are undone.
What is the use of COMMIT?
A commit is used to ends the current transaction and makes permanent any changes made during the
transaction. All transactional locks acquired on the tables are released.
What is SAVEPOINT?
A SAVEPOINT is a mark with in a transaction that allows for a partial rollback.
How Multiple Transactions can be controlled?
By using SAVEPOINT

An insert statement followed by a create table statement followed by rollback? Will the rows be
inserted?
No.
Can you define multiple savepoints?
Yes.
How to make every DML operations as AUTO COMMIT?
By using SET AUTOCOMMIT ON command.
What happens when commit is given in executable section when an error occurs?
It Rollback the transactions
If you insert a row in a table, then create another table and then say Rollback. In this case will
the row be inserted?
Yes, because Create table is a DDL which commits automatically as soon as it is executed.
The DDL commits the transactions even if the create statement fails internally.
What is the difference between Transaction and a Query?
A Transaction is unit of some commands where as Query is a single line request for the information
from the database.
What are the BUILT-IN's?
DISTINCT

: It scans through entire rows and displays only unique values.

SUM

: Sum total of a numerical column.

COUNT

: Count of the total number of rows satisfied by some query condition.

MIN

: Returns the minimum value of exp.

MAX

: Returns the maximum value of exp.

AVG

: Returns the average value of exp.

ABS

: Returns the absolute value of value.

POWER

: Returns m raised to the nth power, n must be an integer, else an error is


returned.

Syntax : POWER(3,2)
ROUND

: It is used to define the round value for the expr.

TRUNC

: Returns a number truncated to a certain number of decimal places.

CEIL

: Returns the smallest integer value that is greater than or equal to a


number.

FLOOR

: Returns the largest integer value that is equal to or less than a number.

MOD

: Returns remainder of a first number divided by second number.

SQRT

: Returns square root of given number.

EXP

: Returns exponential value for the given number.

LEAST

: Returns the lowest value in a list.

GREATEST

: Returns the greatest value in a list.

LOWER

: Converts a string to all lowercase letters.

UPPER

: Converts a string to all UPPERCASE letters.

INITCAP

: Returns a string with the first letter of each word in upper case.

SUBSTR

: Returns a portion of characters.

Syntax : SUBSTR (<string>,<start_position>,[<length>])


INSTR

: Returns the location of a substring in a string.

Syntax : INSTR(<string>,<searching char>,<search position>,<occurrence>)


ASCII

: Returns the number code that represents the specified character.

EXTRACT

: Returns a value extracted from a date or an interval value. A date can


be used only to extract year, month and day.

EX: SELECT extract (year from date 2004-07-02') year from dual;
LTRIM

: Removes characters from the left of char with initial characters


removed up to the first character

RTRIM

: It is used to remove spaces after the string.

TRIM

: Removes all specified characters from the beginning or the ending of a


string.

LPAD

: Returns char1 left padded to length n with the sequence of characters


specified in char2. If char2 is not specified oracle uses blanks by
default.

RPAD

: Returns char1 right padded to length n with the sequence of characters


specified in char2. If char2 is not specified oracle uses blanks by
default.

TRANSLATE
REPLACE
LENGTH

: It replace char by char in a given string.


: It replace word by word.
: It returns no of characters in a given string.

TO_CHAR

: Converts a DATE value or a NUMBER value into a character string.

TO_DATE

: Converts a character string into a DATE value.

TO_NUMBER

: Converts a character string or DATE into a number (ascii conversion).

ADD_MONTH

: Returns date after adding the number of months specified in the


function

LAST_DAY

: Returns the last date of the month specified in the function.

MONTHS_BETWEEN

: Returns number of months between two dates.

NEXT_DAY

: Returns the date of the first weekday named by char that is after the
date named by date.

VSIZE

: Returns the number of bytes in the internal representation of an


expression.

NVL

: NVL is used when we are dealing with null values if we want to show
any another value instead of NULL then we will use NVL.

DECODE

: Decode is a function in sql it works like an IF-ELSE statement.

What is DISTINCT?
The DISTINCT clause removes the duplicate values from the result set.
What is the difference between COUNT (), COUNT (*) Functions?
Count () will restrict the NULL values whereas count (*) will retrieve all the rows including NULL
values in a table.
What is the difference between SUBSTR () and INSTR () Functions?
Substr() will return the specified part of a string whereas
Instr() return the position of the specified part of the string.
What is the use of EXTRACT?
EXTRACT extracts and returns the value of a specified date time field from a date time or interval
value expression.
Example:
SELECT EXTRACT(YEAR FROM DATE '1998-03-07') FROM DUAL;
SELECT EXTRACT(MONTH FROM DATE '1998-03-07') FROM DUAL;
SELECT EXTRACT(DAY FROM DATE '1998-03-07') FROM DUAL;
Which date function returns number value?
MONTHS_BETWEEN this date function takes 2 valid dates and returns number of months in between
them.

What for NVL () Function?


NVL Function helps in substituting a value in place of a NULL.
What is the use of NVL2?
It lets you determine the value returned by a query based on whether a specified expression is null or
not null. If exp1 is not null then nvl2 returns exp2. If exp1 is null then nvl2 returns exp3.
What is the use of NULLIF?
It compares two strings expr, if they are equal then the function returns null. If they are not equal then
the function returns exp1.
Ex: SELECT e.ename,nullif(e.job,j.job) FROM emp e,emp j
WHERE e.empno = j.empno;
What is the use of COALESCE?
It returns the first not null expr in the expression list. At least one expr must not be the null. If all the
occurrences of expr evaluate to null then the function return null.
Ex: COALESCE (exp1,exp2,exp3,----)
If exp1 is null then exp2
If exp2 is null then exp3 and so on
For which relational operators in where clause, index is not used?
<>, like '% ...' is NOT functions, field +constant, field || ''
What is the difference between TO_DATE () and TO_CHAR () conversion Functions?
To_date converts character date to date format whereas
To_char function converts date or numerical values to characters.
What is the use of DECODE?
Decode statement is used to translate one value to another. Decode compares expr to each search value
one by one. If expr is equal to search then Oracle returns the corresponding result. If no match is
found then Oracle returns default.
Example:
SELECT ename,
sal,
decode(job,'marketing',0.10*sal,'clerk',0.5*sal,sal) "salary"

FROM

emp;

Display the records between two range I know the nvl function only allows the same data type(ie.
number or char or date Nvl(comm, 0)), if commission is null then the text Not Applicable want
to display, instead of blank space. How do I write the query?
You can use the decode function for the above requirement. Please find the query as below:
Ex: select ename,DECODE(NVL(comm,0),0,'Not Applicable',comm) from scott.emp;
What is the use of CASE?
CASE expression is used like IF..THEN...ELSE logic in SQL statement without invoking procedures.
Example:
SELECT

ename,
sal,
CASE sal WHEN 1000 THEN 'Low'
WHEN 5000 THEN 'High'
ELSE 'Medium'
END

FROM

emp;

What is the difference between MAX () and GREATEST () Functions?


MAX is an aggregate function which takes only one column name of a table as parameter whereas
Greatest is a general function which can take any number of values and column names from dual and
table respectively.
What is the use of ROLLUP?
ROLLUP enables a SELECT statement to calculate multiple levels of subtotals across a specified
group of dimensions. It also calculates a Grand Total.
Example:
SELECT

deptno,
job,
sum(sal)

FROM

emp

GROUP BY

ROLLUP(deptno,job);

What is the use of CUBE?

CUBE takes a specified set of grouping columns and creates subtotals for all the possible
combinations. The result set will include all the values that would be included in an equivalent
ROLLUP statement plus additional combinations.
Example:
SELECT

deptno, job, sum(sal)

FROM

emp

GROUP BY CUBE(deptno,job);
What is MERGE statement (9i)?
Merge statement enables us to do either UPDATE or INSERT a row into a target table using a single
statement.
Example:
merge into dept d
using emp e
on(d.deptno=e.deptno)
when matched found then
update set d.name=e.ename,
d.job=e.job,
d.salary=e.salary,
d.deptno=e.deptno
when not matched then
insert(d.name,d.job,d.salary,d.deptno)
values(e.ename,e.job,e.salary,e.deptno);
What are set operator?
Set operators combine the result of two component queries into a single result queries containing set
operator are called components queries
UNION

: all rows selected by either query, restricts the Duplicate rows.

UNION ALL : All rows selected by either query, including all duplicate
INTERSECT : All distinct rows selected by both queries
MINUS

: All distinct rows selected by the first query but not the second.

What are the various types of queries?


(i)

Normal Queries

(ii)

Sub Queries

(iii)

Co-related queries

(iv)

Compound queries

What is a Sub Query?


A sub query is a query with in a query. These sub query can reside in where clause, from clause or
select clause. It is also called nested query.
(i) A sub query used in the from clause of a select statement is called INLINE VIEW.
(ii) A sub query used in the where clause of a select statement is called NESTED sub Query.
What are the Limitations of sub query?
(i)

Data displayed only from parent table.

(ii)

Parent query can use only one table.

Special operators used for sub query:


EXISTS

: The exists condition is considered to be met if the sub query returns at least one row.
The below statement will return all the records from the emp table.

Ex: SELECT * FROM emp WHERE EXISTS(select *from dept where emp.deptno=dept.deptno);
NOT EXISTS : This will return all records from emp where there are no records in the dept table for
the given deptno.
ANY

: The any operator computes the lowest value from the set & compares a value to each
returned by a sub query.

ALL

: All compares a value to every value returned by a sub query.

What is the difference b/w sub query and correlated sub query?
In a normal sub query the child query does not depends upon parent query for the conditional value.
Here child query processes first and returns values to parent query.
In a correlated sub query the child query depends upon the parent query for the conditional value. Here
parent query processed first then child query processed one by one for each row of parent query.
What is the difference between IN & Exist?
IN

: We will use this IN operator if we want to find out a value in a list of values.

EXIST : We will use exist operator when we want to find out a value from Result of the sub query.
Which is faster - IN or EXISTS?
Exists is more than IN because Exists returns a Boolean value where as IN returns a value.

What is a JOIN?
It is used to display data from more than one table in single query.
A join is a query that combines rows from two or more tables, views or materialized views.
What are the types of JOINS?
Cross join (or) Cartesian join
Equi join (or) Natural join (or) INNER JOIN
Outer join (LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN)
Non- Equi join
Self join
What is SELF-JOIN?
SELF JOIN is nothing but EQUI JOIN on same table. For self join the table must have at least two
common columns.
Select

e.ename "E_NAME",
m.ename "M_NAME"

FROM

emp e,
emp m

WHERE

e.mgr = m.empno;

What is EQUI-JOIN?
It is used to retrieve data from different tables based on the join condition.
For this condition we need to have at least common column between the tables.
For this join we use '=' operator
SELECT

e.empno,
d.dname

FROM

emp e,
dept d

WHERE

e.deptno = d.deptno;

What Is INNER-JOIN?
It is also same as EQUI-JOIN but syntax is different.
SELECT

e.empno, d.dname

FROM

emp e

INNER JOIN dept d

ON

e.deptno = d.deptno;

What is NON-EQUI JOIN?


It is used for range of values when one column of a table falls in the range of two columns of other
table. Here <, >, between operators used.
Ex: SELECT e.ename, e.job, e.sal, g.grade
FROM

emp e, salgrade g

WHERE e.sal between g.losal and g.hisal


What is OUTER JOIN?
An inner join's ON condition retrieves only those records that satisfy the join condition. An outer join
does the same thing but with the addition of returning records for one table in which there were no
matching records in the other table
(i) LEFT OUTER JOIN

: This join returns all the rows from the first table even if there are no
matches in the second table.

Ex: SELECT e.empno,e.ename,d.dname


FROM emp e LEFT OUTER JOIN detp d
ON e.deptno = d.deptno
[or]
SELECT e.empno,e.ename,d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno(+)
(ii) RIGHT OUTER JOIN

: This join returns all the rows from the second table even if there are no
matches in the first table.

Ex: SELECT e.empno,e.ename,d.dname


FROM emp e RIGHT OUTER JOIN detp d
ON e.deptno = d.deptno
(or)
SELECT e.empno,e.ename,d.dname
FROM emp e, dept d
WHERE e.deptno(+) = d.deptno
(iii) FULL OUTER JOIN

: The full outer join retrieves all records from both the left and the right
table. Most likely, you won't run into a need for this join very often.

Ex: SELECT e.empno, e.ename, d.dname


FROM emp e FULL OUTER JOIN detp d

ON e.deptno = d.deptno
What is CROSS JOIN?
A CROSS JOIN returns a Cartesian product. This means that the join combines every row from the left
table with every row in the right table.
Ex: SELET * FROM emp,dept;
[or]
SELECT e.empno,e.ename,d.deptno FROM emp CROSS JOIN dept;
What is a CONSTRAINT? What are its various levels?
CONSTRAINTS are used to check validations before inserting data into Table and also provide
relationship between tables.
TABLE LEVEL CONSTRAINTS

: 1. UNIQUE CONSTRAINT
2. PRIMARY KEY CONSTRAINT
3. CHECK CONSTRAINT
4. FOREIGN KEY CONSTRAINT

COLUMNLEVEL CONSTRAINTS

: 1. UNIQUE CONSTRAINT
2. PRIMARY KEY CONSTRAINT
3. CHECK CONSTRAINT
4. FOREIGN KEY CONSTRAINT
5. NOT NULL CONSTRAINT
6. DEFAULT CONSTRAINT.

NOT NULL Constraint

- Disallows NULL values in a table's column.

UNIQUE Constraint

- Disallows duplicate values in a column or set of columns.

PRIMARY KEY Constraint - Disallows duplicate values and NULL values in a column or set
of columns.
FOREIGN KEY Constraint - Require each value in a column or set of columns match a
value in a related table's UNIQUE or PRIMARY KEY.
CHECK Constraint

- Disallows values that do not satisfy the logical expression of


the constraint.

What is difference between UNIQUE and PRIMARY KEY constraints?


A table can have only one PRIMARY KEY where as it can have number of UNIQUE KEYS.
PRIMARY KEY is a combination of UNIQUE KEY and NOT NULL.

What is ON DELETE CASCADE?


When this key word is included in the definition of a child table then whenever the records from the
parent table is deleted automatically the corresponding values in the child table will be deleted.
Where the integrity constraints are stored in Data Dictionary?
The integrity constraints are stored in USER_CONSTRAINTS.

If a unique key constraint on DATE column is created, will it validate the rows that are inserted
with sysdate?
It won't, Because SYSDATE format contains time attached with it.
What is the difference between REFERENCES and FOREIGN KEY Constraint?
Foreign key is the key which refers to another table primary key.
Reference key is the primary key of table referred by another table.
What is Composite PRIMARY KEY?
A Primary key created on combination of columns is called Composite Primary Key.
What is created implicitly for every UNIQUE and PRIMARY KEY column?
INDEX
What are the limitations for CHECK constraint?
In this we can't specify Pseudo Columns like sysdate etc.
What are the pre-requisites to (i) modify data type of a column (ii) add a column with NOT
NULL constraint?
To Modify the data type of a column the column must be empty.
To add a column with NOT NULL constrain, the table must be empty
What is the fastest way of accessing a row in a table?
Using ROWID, CONSTRAINTS
What is a sequence?

Sequence is a database object. It is used to generate number in order. It is not related to table. By using
sequence the retrieve data from table is very fast.
It has two pseudo columns.
NEXTVAL (holds the next generated value)
CURRVAL (holds the current available value)
What are the parameters in SEQUENCE?
INCREMENT BY
START WITH
MAXVALUE | NOMAXVALUE
MINVALUE | NOMINVALUE
CYCLE

| NOCYCLE

CACHE

| NOCACHE

ORDER

| NOORDER

What are CYCLE/NO CYCLE in a sequence?


When you create a sequence with cycle option, when the sequence reaches its MAXVALUE it will
start over at the MINVALUE. This is not recommended if sequence is for primary key creation.
When you create a sequence with no cycle option, when the sequence reaches its MAXVALUE it will
not start over at the MINVALUE. This option is safest if sequence is for primary key creation. When
the sequence reaches its MAXVALUE an oracle error will shown.
Consider a sequence whose currval is 1 and gets incremented by 1 by using the nextval reference
we get the next number 2. Suppose at this point we issue a rollback and again issue a nextval.
What will the output be?
The output will be 3
What is a view?
View is a logical table based on one or more tables or views. It contains no data, it contains only
SELECT statement. The view is logically & physically independent from table.
Syntax : CREATE or REPLACE view <view_name> AS select * from <table name>;
Provide an additional level of table security by restricting access to a predetermined set of
rows and/or columns of a table
Hide data complexity

Simplify commands for the user


Present the data in a different perspective from that of the base table
Isolate applications from changes in definitions of base tables
Express a query that cannot be expressed without using a view
What are the advantages of VIEW?
(i)

To protect some of the columns of a table from other users.

(ii)

To hide complexity of a query.

(iii)

To hide complexity of calculations.

What is the difference between SIMPLE and COMPLEX VIEWS?


Simple views can be modified whereas Complex views (created based on more than one table) cannot
be modified.
How to update COMPLEX VIEW?
Using 'INSTEAD OF' TRIGGERS Complex views can be updated.
What are the types of views?
There are 4 types of views
(i)

Inline view

: When we write a query inside of another query from clause


then we will call it as inline view.

(ii)

Updateable view

: if the view is created from a single table and if doesn't contain


any aggregate functions then that view is called as updateable
view.

(iii)

Non updateable view : if the view is created from two or more tables and if it contains
any aggregate functions, joins, union commands then that view
is called as non updateable view.

(iv)

Materialized view

: MATERIALISED view definition includes any no of


aggregates as well as any no of joins in several ways. Behaves
like an index. It is used to increase the query execution
performance.

How can you find out View is updatable or not?


We can find out the view is up datable or not by seeing the definition of that view.

If the view is create base on a single table and it doesn't contain any aggregate functions then that view
is 'Updatable'.
If the view is created based on a join statement or it contains any aggregate functions then that view
is 'not updateable'.
Can a view be updated/inserted/deleted
A simple view can be updated/inserted/deleted but the complex view which is constructed by using
multiple tables or by using group functions can't be updated.
If a View on a single base table is manipulated will the changes be reflected on the base table?
If changes are made to the tables which are base tables of a view then the changes effected on view.
What is the function of 'force' in view?
FORCE function is used to create view with out table. When we create the corresponding tables the
forced view become valid. When we drop the base table the view exists but becomes forced view.
What is the difference between a View and Materialized View?
View
1. View can be created based on

Materialized View
1. Materialized can be creates based on

Tables, Sequences and other

Tables, Views and other Materialized

views.

views.

2. View will have only the select

2. Materialized view will have the result of

statement.

the query

3. If the source table dropped

3. If the source table dropped then

then view will be invalid.

Materialized View will exist.

4. Manipulations on view will be

4. Manipulations on this view will be

reflected automatically in table.

reflected in table by using REFRESH' on


commit option only.

What is the difference between view and table?


View is a virtual table. Every view has a Query attached to it. It has only structure, data is not there in
views. It gets data from base table.
A table is the basic unit of data storage in an ORACLE database. The tables of a database hold all of
the user accessible data. Table data is stored in rows and columns.
Can a trigger written for a view?

Yes
Can you create index on view
No.
What is a SNAPSHOT?
It is a static picture of table, snapshot is a table that contains the results of a query of one or more
tables or views, and it contains structure and data also.
Data retrieval is faster in snapshot than view.
Syntax: CREATE snapshot <snapshot_name> AS select statement
What is the difference between snap shots and materialized views?
SNAP SHOT

: A Snap Shot is a replication of master table from a single point-in-time


Snapshots are updated by one or more master tables via individual
batch updates are known as refresh.

MATERIALIZED VIEW

: Materialized view will be created to access the base table information


and it is not possible to do DML operations on that

What is the difference between view and Snapshot?


View stores the select statement only. View is a virtual table to join one or more table or to prevent
access from users on complete data on table. Whenever we will access the view that brings the data
from tables only, not from view(it won't store any kind of data).
The snapshot stores the query result data. Usually we will use to get remote data to replicate the
changes made at remote site.
What is a SYNONYM?
A synonym is an alternative name for objects such as tables, views, sequences, stored procedures and
other database objects. Generally when we have more than one schema and we wish to access an
object of a different schema then we create synonyms for that object in the schema where we wish to
access the object.
It is used to hide the information, some times we create synonym to give short name of the object.
Types of synonym:
Private created by user--default
Public created by DBA

Syntax: CREATE synonym <synonym_name> for <object_name>


What is the difference between PRIVATE AND PUBLIC SYNONYM?
Only the user or table owner can reference Private synonym whereas any user can reference the Public
synonym.
What is the difference between alias and synonym?
Alias is temporary and used with one query. Synonym is permanent and not used as alias
If we delete the base table whether the synonym will exists or not? If we use that synonym what
type of error we will get?
The SYNONYM will be exists even though the Table was dropped.
If we use that synonym the following errors will come
ORA-00980: synonym translation is no longer valid
ORA-00903: invalid table name
ORA-04043: object SCOTT.T1 does not exist
What is the difference between a view and a synonym?
Synonym is just a second name of table used for multiple link of database. Synonym can be created
based on one table and we cannot use any conditions.
View can be created with many tables, and with virtual columns and with conditions.
Can database trigger written on synonym of a table and if it can be then what would be the
effect if original table is accessed.
Yes, database trigger would fire.
What is the difference between the snapshot and synonym?
=> A snapshot refers to read-only copies of a master table or tables located on a remote node. A
snapshot can be queried, but not updated; only the master table can be updated. A snapshot is
periodically refreshed to reflect changes made to the master table. In this sense, a snapshot is really a
view with periodicity.
=> A synonym is an alias for table, view, sequence or program unit. They are of two types private and
public.

What is the difference between data types char and varchar?


Char reserves the number of memory locations mentioned in the variable declarations, even though
not used (it can store a maximum of 255 bytes). Where as Varchar does not reserve any memory
locations when the variable is declared, it stores the values only after they are assigned (it can store a
maximum of 32767 bytes).
How can we place index to a second column in the table i.e. there is already one index and I want
to place another index for the column on the table?
How can the duplicate records be from the table?
create table table_name2 as select distinct * from table_name1;
drop table_name1;
rename table_name2 to table_name1;

Contents
[hide]
1 What is SQL and where does it come from?
2 What are the difference between DDL, DML and DCL commands?
3 Difference between TRUNCATE, DELETE and DROP commands?
4 How does one escape special characters when writing SQL queries?
5 Can one select a random collection of rows from a table?
6 How does one eliminate duplicates rows from a table?
7 How does one get the time difference between two date columns?
8 How does one add a day/hour/minute/second to a date value?
9 How does one code a matrix/crosstab/pivot report in SQL?
10 Can one retrieve only rows X to Y from a table?
11 Can one retrieve only the Nth row from a table?
12 How can one dump/ examine the exact content of a database column?
13 How does one add a column to the middle of a table?
14 How does one code a hierarchical tree-structured query?
15 How does one count/sum data values in a column?
16 How does one drop/ rename a column in a table?
17 How does one implement IF-THEN-ELSE logic in a SELECT statement?
18 How does one prevent Oracle from using an Index?
19 How does one select EVERY Nth row from a table?
20 How does one select the LAST N rows from a table?
21 How does one select the TOP N rows from a table?
22 How to generate a text graphs (histograms) using SQL?

23 Map/ concatenate several rows to a column


24 What is the difference between VARCHAR, VARCHAR2 and CHAR data
types?
[edit] What is SQL and where does it come from?
Structured Query Language (SQL) is a language that provides an interface to relational database
systems. The proper pronunciation of SQL, and the preferred pronunciation within Oracle Corp, is
"sequel" and not "ess cue ell".
SQL was developed by IBM in the 1970s for use in System R, and is a de facto standard, as well as an
ISO and ANSI standard.
In common usage SQL also encompasses DML (Data Manipulation Language), for INSERTs,
UPDATEs, DELETEs and DDL (Data Definition Language), used for creating and modifying tables
and other database structures.
The development of SQL is governed by standards. A major revision to the SQL standard was
completed in 1992, called SQL2. SQL3 support object extensions and are (partially?) implemented in
Oracle8 and 9i.
Example SQL statements:
CREATE TABLE table1 (column1 NUMBER, column2 VARCHAR2(30));
INSERT INTO table1 VALUES (1, 'XYZ');
SELECT * FROM table1 WHERE column2 = 'XYZ';
[edit] What are the difference between DDL, DML and DCL commands?
DDL - Data Definition Language: statements used to define the database structure or schema. Some
examples:

CREATE - to create objects in the database

ALTER - alters the structure of the database


DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces

allocated for the records are removed


COMMENT - add comments to the data dictionary
RENAME - rename an object
DML - Data Manipulation Language: statements used for managing data within schema objects. Some
examples:

SELECT - retrieve data from the a database

INSERT - insert data into a table


UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records

remain
MERGE - UPSERT operation (insert or update)
CALL - call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to the data
LOCK TABLE - controls concurrency

DCL - Data Control Language. Some examples:

GRANT - gives user's access privileges to database

REVOKE - withdraw access privileges given with the GRANT


command

TCL - Transaction Control: statements used to manage the changes made by DML statements. It
allows statements to be grouped together into logical transactions.

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can

later roll back


ROLLBACK - restore database to original since the last COMMIT
SET TRANSACTION - Change transaction options like isolation
level and what rollback segment to use
DML are not auto-commit. i.e. you can roll-back the operations, but DDL are auto-commit
[edit] Difference between TRUNCATE, DELETE and DROP commands?
The DELETE command is used to remove some or all rows from a table. A WHERE clause can be
used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After
performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the
change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to
fire.
SQL> SELECT COUNT(*) FROM emp;
COUNT(*)
---------14
SQL> DELETE FROM emp WHERE job = 'CLERK';
4 rows deleted.

SQL> COMMIT;
Commit complete.
SQL> SELECT COUNT(*) FROM emp;
COUNT(*)
---------10
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will
be fired. As such, TRUNCATE is faster and doesn't use as much undo space as a DELETE.
SQL> TRUNCATE TABLE emp;
Table truncated.
SQL> SELECT COUNT(*) FROM emp;
COUNT(*)
---------0
The DROP command removes a table from the database. All the tables' rows, indexes and privileges
will also be removed. No DML triggers will be fired. The operation cannot be rolled back.
SQL> DROP TABLE emp;
Table dropped.
SQL> SELECT * FROM emp;
SELECT * FROM emp
*
ERROR at line 1:
ORA-00942: table or view does not exist
DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore
DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be
rolled back.
From Oracle 10g a table can be "undropped". Example:
SQL> FLASHBACK TABLE emp TO BEFORE DROP;
Flashback complete.
PS: DELETE will not free up used space within a table. This means that repeated DELETE commands
will severely fragment the table and queries will have to navigate this "free space" in order to retrieve
rows.
[edit] How does one escape special characters when writing SQL queries?

Escape quotes
Use two quotes for every one displayed. Examples:
SQL> SELECT 'Frank''s Oracle site' AS text FROM DUAL;
TEXT
-------------------Franks's Oracle site
SQL> SELECT 'A ''quoted'' word.' AS text FROM DUAL;
TEXT
---------------A 'quoted' word.
SQL> SELECT 'A ''''double quoted'''' word.' AS text FROM DUAL;
TEXT
------------------------A ''double quoted'' word.
Escape wildcard characters
The LIKE keyword allows for string searches. The '_' wild card character is used to match exactly one
character, while '%' is used to match zero or more occurrences of any characters. These characters can
be escaped in SQL. Examples:
SELECT name FROM emp
WHERE id LIKE '%/_%' ESCAPE '/';
SELECT name FROM emp
WHERE id LIKE '%\%%' ESCAPE '\';
Escape ampersand (&) characters in SQL*Plus
When using SQL*Plus, the DEFINE setting can be changed to allow &'s (ampersands) to be used in
text:
SET DEFINE ~
SELECT 'Laurel & Hardy' FROM dual;
Other methods:
Define an escape character:
SET ESCAPE '\'
SELECT '\&abc' FROM dual;
Don't scan for substitution variables:

SET SCAN OFF


SELECT '&ABC' x FROM dual;
Another way to escape the & would be to use concatenation, which would not require any SET
commands SELECT 'Laurel ' || '&' || ' Hardy' FROM dual;
Use the 10g Quoting mechanism:
Syntax
q'[QUOTE_CHAR]Text[QUOTE_CHAR]'
Make sure that the QUOTE_CHAR doesnt exist in the text.
SELECT q'{This is Orafaq's 'quoted' text field}' FROM DUAL;
[edit] Can one select a random collection of rows from a table?
The following methods can be used to select a random collection of rows from a table:
The SAMPLE Clause
From Oracle 8i, the easiest way to randomly select rows from a table is to use the SAMPLE clause
with a SELECT statement. Examples:
SELECT * FROM emp SAMPLE(10);
In the above example, Oracle is instructed to randomly return 10% of the rows in the table.
SELECT * FROM emp SAMPLE(5) BLOCKS;
This example will sample 5% of all formatted database blocks instead of rows.
This clause only works for single table queries on local tables. If you include the SAMPLE clause
within a multi-table or remote query, you will get a parse error or "ORA-30561: SAMPLE option not
allowed in statement with multiple table references". One way around this is to create an inline view
on the driving table of the query with the SAMPLE clause. Example:
SELECT t1.dept, t2.emp
FROM (SELECT * FROM dept SAMPLE(5)) t1,
emp t2
WHERE t1.dep_id = t2.dep_id;
If you examine the execution plan of a "Sample Table Scan", you should see a step like this:

TABLE ACCESS (SAMPLE) OF 'EMP' (TABLE)


ORDER BY dbms_random.value()
This method orders the data by a random column number. Example:
SQL> SELECT * FROM (SELECT ename
2
FROM emp
3
ORDER BY dbms_random.value())
4 WHERE rownum <= 3;
ENAME
---------WARD
MILLER
TURNER
The ORA_HASH() function
The following example retrieves a subset of the data in the emp table by specifying 3 buckets (0 to 2)
and then returning the data from bucket 1:
SELECT * FROM emp WHERE ORA_HASH(empno, 2) = 1;
[edit] How does one eliminate duplicates rows from a table?
Choose one of the following queries to identify or remove duplicate rows from a table leaving only
unique records in the table:
Method 1:
Delete all rowids that is BIGGER than the SMALLEST rowid value (for a given key):
SQL> DELETE FROM table_name A
2 WHERE ROWID > ( SELECT min(rowid)
3
FROM table_name B
4
WHERE A.key_values = B.key_values );
Method 2:
This method is usually faster. However, remember to recreate all indexes, constraints, triggers, etc. on
the table when done.
SQL> create table table_name2 as select distinct * from table_name1;
SQL> drop table table_name1;
SQL> rename table_name2 to table_name1;
Method 3:

SQL> DELETE FROM my_table t1


2 WHERE EXISTS ( SELECT 'x' FROM my_table t2
3
WHERE t2.key_value1 = t1.key_value1
4
AND t2.key_value2 = t1.key_value2
4
AND t2.rowid
> t1.rowid );
Note: One can eliminate N^2 unnecessary operations by creating an index on the joined fields in the
inner loop (no need to loop through the entire table on each pass by a record). This will speed-up the
deletion process.
Note 2: If you are comparing NULL columns, use the NVL function. Remember that NULL is not
equal to NULL. This should not be a problem as all key columns should be NOT NULL by definition.
Method 4:
This method collects the first row (order by rowid) for each key values and delete the rows that are not
in this set:
SQL> DELETE FROM my_table t1
1 WHERE rowid NOT IN ( SELECT min(rowid)
2
FROM my_table t2
3
GROUP BY key_value1, key_value2 );
Note: IF key_value1 is null or key_value2 is null, this still works correctly.
[edit] How does one get the time difference between two date columns?
Oracle allows two date values to be subtracted from each other returning a numeric value indicating
the number of days between the two dates (may be a fraction). This example will show how to relate it
back to a time value.
Let's investigate some solutions. Test data:
SQL> CREATE TABLE dates (date1 DATE, date2 DATE);
Table created.
SQL>
SQL> INSERT INTO dates VALUES (SYSDATE, SYSDATE-1);
1 row created.
SQL> INSERT INTO dates VALUES (SYSDATE, SYSDATE-1/24);
1 row created.
SQL> INSERT INTO dates VALUES (SYSDATE, SYSDATE-1/60/24);
1 row created.
SQL> SELECT (date1 - date2) FROM dates;
DATE1-DATE2
----------1
.041666667

.000694444
Solution 1
SQL> SELECT floor(((date1-date2)*24*60*60)/3600)
2
|| ' HOURS ' ||
3
floor((((date1-date2)*24*60*60) 4
floor(((date1-date2)*24*60*60)/3600)*3600)/60)
5
|| ' MINUTES ' ||
6
round((((date1-date2)*24*60*60) 7
floor(((date1-date2)*24*60*60)/3600)*3600 8
(floor((((date1-date2)*24*60*60) 9
floor(((date1-date2)*24*60*60)/3600)*3600)/60)*60) ))
10
|| ' SECS ' time_difference
11 FROM dates;
TIME_DIFFERENCE
-------------------------------------------------------------------------------24 HOURS 0 MINUTES 0 SECS
1 HOURS 0 MINUTES 0 SECS
0 HOURS 1 MINUTES 0 SECS
Solution 2
If you don't want to go through the floor and ceiling maths, try this method:
SQL> SELECT to_number( to_char(to_date('1','J') +
2
(date1 - date2), 'J') - 1) days,
3
to_char(to_date('00:00:00','HH24:MI:SS') +
4
(date1 - date2), 'HH24:MI:SS') time
5 FROM dates;
DAYS TIME
---------- -------1 00:00:00
0 01:00:00
0 00:01:00
Solution 3
Here is a simpler method:
SQL> SELECT trunc(date1-date2) days,
2 to_char(trunc(sysdate) + (date1 - date2), 'HH24 "Hours" MI "Minutes" SS "Seconds"') time
3 FROM dates;
DAYS TIME
---------- -----------------------------1 00 Hours 00 Minutes 00 Seconds
0 01 Hours 00 Minutes 00 Seconds
0 00 Hours 01 Minutes 00 Seconds

[edit] How does one add a day/hour/minute/second to a date value?


The SYSDATE pseudo-column shows the current system date and time. Adding 1 to SYSDATE will
advance the date by 1 day. Use fractions to add hours, minutes or seconds to the date. Look at these
examples:
SQL> select sysdate, sysdate+1/24, sysdate +1/1440, sysdate + 1/86400 from dual;
SYSDATE
SYSDATE+1/24
SYSDATE+1/1440
SYSDATE+1/86400
-------------------- -------------------- -------------------- -------------------03-Jul-2002 08:32:12 03-Jul-2002 09:32:12 03-Jul-2002 08:33:12 03-Jul-2002 08:32:13
The following format is frequently used with Oracle Replication:
select sysdate NOW, sysdate+30/(24*60*60) NOW_PLUS_30_SECS from dual;
NOW
NOW_PLUS_30_SECS
-------------------- -------------------03-JUL-2005 16:47:23 03-JUL-2005 16:47:53
Here are a couple of examples:
Description

Date Expression

Now

SYSDATE

Tomorow/ next day

SYSDATE + 1

Seven days from now

SYSDATE + 7

One hour from now

SYSDATE + 1/24

Three hours from now

SYSDATE + 3/24

A half hour from now

SYSDATE + 1/48

10 minutes from now

SYSDATE + 10/1440

30 seconds from now

SYSDATE + 30/86400

Tomorrow at 12 midnight TRUNC(SYSDATE + 1)


Tomorrow at 8 AM

TRUNC(SYSDATE + 1) + 8/24

Next Monday at 12:00


NEXT_DAY(TRUNC(SYSDATE), 'MONDAY') + 12/24
noon
First day of the month at
TRUNC(LAST_DAY(SYSDATE ) + 1)
12 midnight
The
next
Monday,
TRUNC(LEAST(NEXT_DAY(sysdate, 'MONDAY'), NEXT_DAY(sysdate,
Wednesday or Friday at 9
'WEDNESDAY'), NEXT_DAY(sysdate, 'FRIDAY'))) + 9/24
a.m
[edit] How does one code a matrix/crosstab/pivot report in SQL?
Newbies frequently ask how one can display "rows as columns" or "columns as rows". Look at these
example crosstab queries (also sometimes called transposed, matrix or pivot queries):

SELECT *
FROM (SELECT job,
sum(decode(deptno,10,sal)) DEPT10,
sum(decode(deptno,20,sal)) DEPT20,
sum(decode(deptno,30,sal)) DEPT30,
sum(decode(deptno,40,sal)) DEPT40
FROM scott.emp
GROUP BY job)
ORDER BY 1;
JOB
DEPT10 DEPT20 DEPT30 DEPT40
--------- ---------- ---------- ---------- ---------ANALYST
6000
CLERK
1300
1900
950
MANAGER
2450
2975
2850
PRESIDENT
5000
SALESMAN
5600
Here is the same query with some fancy headers and totals:
SQL> ttitle "Crosstab Report"
SQL> break on report;
SQL> compute sum of dept10 dept20 dept30 dept40 total on report;
SQL>
SQL> SELECT *
2 FROM (SELECT job,
3
sum(decode(deptno,10,sal)) DEPT10,
4
sum(decode(deptno,20,sal)) DEPT20,
5
sum(decode(deptno,30,sal)) DEPT30,
6
sum(decode(deptno,40,sal)) DEPT40,
7
sum(sal)
TOTAL
8
FROM emp
9
GROUP BY job)
10 ORDER BY 1;
Mon Aug 23

page 1
Crosstab Report

JOB
DEPT10 DEPT20 DEPT30 DEPT40 TOTAL
--------- ---------- ---------- ---------- ---------- ---------ANALYST
6000
6000
CLERK
1300
1900
950
4150
MANAGER
2450
2975
2850
8275
PRESIDENT
5000
5000
SALESMAN
5600
5600
---------- ---------- ---------- ---------- ---------sum
8750
10875
9400
29025
Here's another variation on the theme:

SQL> SELECT DECODE(MOD(v.row#,3)


2
,1, 'Number: ' ||deptno
3
,2, 'Name: ' ||dname
4
,0, 'Location: '||loc
5
) AS "DATA"
6 FROM dept,
7
(SELECT rownum AS row# FROM user_objects WHERE rownum < 4) v
8 WHERE deptno = 30
9 /
DATA
--------------------------------------- --------Number: 30
Name: SALES
Location: CHICAGO
From Oracle 11g, we can use pivot option
[edit] Can one retrieve only rows X to Y from a table?
SELECT * FROM (
SELECT ename, rownum rn
FROM emp WHERE rownum < 101
) WHERE RN between 91 and 100 ;
Note: the 101 is just one greater than the maximum row of the required rows (means x= 90, y=100, so
the inner values is y+1).
SELECT rownum, f1 FROM t1
GROUP BY rownum, f1 HAVING rownum BETWEEN 2 AND 4;
Another solution is to use the MINUS operation. For example, to display rows 5 to 7, construct a
query like this:
SELECT *
FROM tableX
WHERE rowid in (
SELECT rowid FROM tableX
WHERE rownum <= 7
MINUS
SELECT rowid FROM tableX
WHERE rownum < 5);
"this one was faster for me and allowed for sorting before filtering by rownum. The inner query (table
A) can be a series of tables joined together with any operation before the filtering by rownum is
applied."

SELECT *
FROM (SELECT a.*, rownum RN
FROM (SELECT *
FROM t1 ORDER BY key_column) a
WHERE rownum <=7)
WHERE rn >=5;
Please note, there is no explicit row order in a relational database. However, this query is quite fun and
may even help in the odd situation.
The generic solution to get full information of rows between x and y

SELECT * FROM emp WHERE empno in (SELECT empno FROM emp GROUP BY
rownum,empno HAVING rownum BETWEEN &x AND &y);

"select particular rows from a table : select for rownum = 4, 15 and 17."
select * from (
select rownum myrownum, emp.* from employees emp
) mytable
where myrownum in (4,15,17);

"selecting row between range of rownum: select for rownum between (12, 20)."
select * from (
select rownum myrownum, emp.* from employees emp
) mytable
where myrownum between 12 and 20;

"Replace 12 and 20 with &x and &y respectively to assign range dynamically."
select * from (
select rownum myrownum, emp.* from employees emp
) mytable
where myrownum between &x and &y;

"Combined query to give complete flexibility to pick particular rows and also a given range."
select * from (

select rownum myrownum, emp.* from employees emp


) mytable
where myrownum between 12 and 17
or myrownum in ( 3, 18, 25);
[edit] Can one retrieve only the Nth row from a table?
SELECT * FROM t1 a
WHERE n = (SELECT COUNT(rowid)
FROM t1 b
WHERE a.rowid >= b.rowid);
SELECT * FROM (
SELECT ENAME,ROWNUM RN FROM EMP WHERE ROWNUM < 101 )
WHERE RN = 100;
Note: In this first query we select one more than the required row number, then we select the required
one. Its far better than using a MINUS operation.
SELECT f1 FROM t1
WHERE rowid = (
SELECT rowid FROM t1
WHERE rownum <= 10
MINUS
SELECT rowid FROM t1
WHERE rownum < 10);
SELECT rownum,empno FROM scott.emp a
GROUP BY rownum,empno HAVING rownum = 4;
Alternatively...
SELECT * FROM emp WHERE rownum=1 AND rowid NOT IN
(SELECT rowid FROM emp WHERE rownum < 10);
Please note, there is no explicit row order in a relational database. However, this query is quite fun and
may even help in the odd situation.
[edit] How can one dump/ examine the exact content of a database column?
Table data can be extracted from the database as octal, decimal or hex values:
SELECT DUMP(col1, 10)
FROM tab1
WHERE cond1 = val1;
DUMP(COL1)
------------------------------------Typ=96 Len=4: 65,66,67,32

For this example, type=96 is indicating a CHAR column. The last byte in the column is 32, which is
the ASCII code for a space. This tells us that this column is blank-padded.
[edit] How does one add a column to the middle of a table?
Oracle only allows columns to be added to the end of an existing table. Example:
SQL> CREATE TABLE tab1 ( col1 NUMBER );
Table created.
SQL> ALTER TABLE tab1 ADD (col2 DATE);
Table altered.
SQL> DESC tab1
Name
Null? Type
----------------------------------------- -------- ---------------------------COL1
NUMBER
COL2
DATE
Nevertheless, some databases also allow columns to be added to an existing table after a particular
column (i.e. in the middle of the table). For example, in MySQL the following syntax is valid:
ALTER TABLE tablename ADD columnname AFTER columnname;
Oracle does not support this syntax. However, it doesn't mean that it cannot be done.
Workarounds:
1. Create a new table and copy the data across.
SQL> RENAME tab1 TO tab1_old;
Table renamed.
SQL> CREATE TABLE tab1 AS SELECT 0 AS col1, col1 AS col2 FROM tab1_old;
Table created.
2. Use the DBMS_REDEFINITION package to change the structure on-line while users are working.
[edit] How does one code a hierarchical tree-structured query?
The SCOTT/TIGER database schema contains a table EMP with a self-referencing relation (EMPNO
and MGR columns). This table is perfect for testing and demonstrating tree-structured queries as the
MGR column contains the employee number of the "current" employee's boss.
The LEVEL pseudo-column is an indication of how deep in the tree one is. Oracle can handle queries
with a depth of up to 255 levels. Look at this example:

SQL> SELECT level, empno, ename, mgr


2 FROM emp
3 CONNECT BY PRIOR empno = mgr
4 START WITH mgr IS NULL
5 /
LEVEL EMPNO ENAME
MGR
---------- ---------- ---------- ---------1
7839 KING
2
7566 JONES
7839
3
7788 SCOTT
7566
...
One can produce an indented report by using the level number to substring or lpad() a series of spaces,
and concatenate that to the string. Look at this example:
SQL> SELECT LPAD(' ', LEVEL * 2) || ename
2 FROM emp
3 CONNECT BY PRIOR empno = mgr
4 START WITH mgr IS NULL;
LPAD(,LEVEL*2)||ENAME
-----------------------------------------------------KING
JONES
SCOTT
...
Use the "start with" clause to specify the start of the tree. More than one record can match the starting
condition. One disadvantage of having a "connect by prior" clause is that you cannot perform a join to
other tables. The "connect by prior" clause is rarely implemented in the other database offerings.
Trying to do this programmatically is difficult as one has to do the top level query first, then, for each
of the records open a cursor to look for child nodes.
One way of working around this is to use PL/SQL, open the driving cursor with the "connect by prior"
statement, and the select matching records from other tables on a row-by-row basis, inserting the
results into a temporary table for later retrieval.
NOTE: Tree-structured queries are definitely non-relational (enough to kill Codd and make him roll in
his grave). Also, this feature is not often found in other database offerings.
[edit] How does one count/sum data values in a column?
Count/sum FIX values:
Use this simple query to count the number of data values in a column:
select my_table_column, count(*)
from my_table

group by my_table_column;
A more sophisticated example...
select dept, sum( decode(sex,'M',1,0)) MALE,
sum( decode(sex,'F',1,0)) FEMALE,
count(decode(sex,'M',1,'F',1)) TOTAL
from my_emp_table
group by dept;
Count/sum RANGES of data values in a column:
A value x will be between values y and z if GREATEST(x, y) = LEAST(x, z). Look at this example:
select f2,
sum(decode(greatest(f1,59), least(f1,100), 1, 0)) "Range 60-100",
sum(decode(greatest(f1,30), least(f1, 59), 1, 0)) "Range 30-59",
sum(decode(greatest(f1, 0), least(f1, 29), 1, 0)) "Range 00-29"
from my_table
group by f2;
For equal size ranges it might be easier to calculate it with DECODE(TRUNC(value/range), 0, rate_0,
1, rate_1, ...). Eg.
select ename "Name", sal "Salary",
decode( trunc(f2/1000, 0), 0, 0.0,
1, 0.1,
2, 0.2,
3, 0.31) "Tax rate"
from my_table;
[edit] How does one drop/ rename a column in a table?
Drop a column
From Oracle 8i one can DROP a column from a table. Look at this sample script, demonstrating the
ALTER TABLE table_name DROP COLUMN column_name; command.
Workarounds for older releases:
SQL> update t1 set column_to_drop = NULL;
SQL> rename t1 to t1_base;
SQL> create view t1 as select >specific columns> from t1_base;
SQL> create table t2 as select >specific columns> from t1;
SQL> drop table t1;
SQL> rename t2 to t1;

Rename a column
From Oracle 9i one can RENAME a column from a table. Look at this example:
ALTER TABLE tablename RENAME COLUMN oldcolumn TO newcolumn;
Workarounds for older releases:
Use a view with correct column names:
rename t1 to t1_base;
create view t1 >column list with new name> as select * from t1_base;
Recreate the table with correct column names:
create table t2 >column list with new name> as select * from t1;
drop table t1;
rename t2 to t1;
Add a column with a new name and drop an old column:
alter table t1 add ( newcolame datatype );
update t1 set newcolname=oldcolname;
alter table t1 drop column oldcolname;
[edit] How does one implement IF-THEN-ELSE logic in a SELECT statement?
One can use the CASE statement or functions like DECODE, NVL, NVL2, NULLIF, COALESCE,
etc.
Here is the syntax for the CASE-statement:
CASE exp WHEN comparison_exp1 THEN return_exp1
[WHEN comparison_exp2 THEN return_exp2
WHEN comparison_exp3 THEN return_exp3
ELSE else_exp
]
END
And for DECODE:
DECODE( col | exprn, srch1, rslt1 [, srch2, rslt2,...,] [,default] )
[edit] How does one prevent Oracle from using an Index?
In certain cases, one may want to disable the use of a specific, or all indexes for a given query. Here
are some examples:

Adding an expression to the indexed column


SQL>select count(*) from t where empno+0=1000;
COUNT(*)
---------1
Execution Plan
--------------------------------------------- ----- -------0
SELECT STATEMENT Optimizer=CHOOSE (Cost=2 Card=1 Bytes=3)
1 0 SORT (AGGREGATE)
2 1 TABLE ACCESS (FULL) OF 'T' (Cost=2 Card=1 Bytes=3)
Specifying the FULL hint to force full table scan
SQL>select /*+ FULL(t) */ * from t where empno=1000;
EMPNO ENAME JOB
MGR HIREDATE
SAL
COMM DEPTNO GRADE
---------- ---------- --------- ---------- --------- ---------- ---------- ---------- ---------1000 Victor DBA
7839 20-MAY-03
11000
0
10 JUNIOR
Execution Plan
--------------------------------------------- ----- -------0
SELECT STATEMENT Optimizer=CHOOSE (Cost=2 Card=1 Bytes=41)
1 0 TABLE ACCESS (FULL) OF 'T' (Cost=2 Card=1 Bytes=41)
Specifying NO_INDEX hint
SQL>select /*+ NO_INDEX(T) */ count(*) from t where empno=1000;
COUNT(*)
---------1
Execution Plan
--------------------------------------------- ----- -------0
SELECT STATEMENT Optimizer=CHOOSE (Cost=2 Card=1 Bytes=3)
1 0 SORT (AGGREGATE)
2 1 TABLE ACCESS (FULL) OF 'T' (Cost=2 Card=1 Bytes=3)
Using a function over the indexed column
SQL>select count(*) from t where to_number(empno)=1000;
COUNT(*)
---------1
Execution Plan
--------------------------------------------- ----- --------

0
1
2

SELECT STATEMENT Optimizer=CHOOSE (Cost=2 Card=1 Bytes=3)


0 SORT (AGGREGATE)
1 TABLE ACCESS (FULL) OF 'T' (Cost=2 Card=1 Bytes=3)

[edit] How does one select EVERY Nth row from a table?
One can easily select all even, odd, or Nth rows from a table using SQL queries like this:
Method 1: Using a subquery
SELECT *
FROM emp
WHERE (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,4)
FROM emp);
Method 2: Use dynamic views (available from Oracle7.2):
SELECT *
FROM ( SELECT rownum rn, empno, ename
FROM emp
) temp
WHERE MOD(temp.ROWNUM,4) = 0;
Method 3: Using GROUP BY and HAVING
SELECT rownum, f1 FROM t1
GROUP BY rownum, f1 HAVING MOD(rownum,n) = 0 OR rownum = 2-n;
Please note, there is no explicit row order in a relational database. However, these queries are quite fun
and may even help in the odd situation.
[edit] How does one select the LAST N rows from a table?
From Oracle 9i onwards, the RANK() and DENSE_RANK() functions can be used to determine the
LAST N or BOTTOM N rows. Examples:
Get the bottom 10 employees based on their salary
SELECT ename, sal
FROM ( SELECT ename, sal, RANK() OVER (ORDER BY sal ASC) sal_rank
FROM emp )
WHERE sal_rank <= 10;
Select the employees getting the lowest 10 salaries
SELECT ename, sal

FROM ( SELECT ename, sal, DENSE_RANK() OVER (ORDER BY sal) sal_dense_rank


FROM emp )
WHERE sal_dense_rank <= 10;
For Oracle 8i and above, one can get the bottom N rows using an inner-query with an ORDER BY
clause:
SELECT *
FROM (SELECT * FROM my_table ORDER BY col_name_1)
WHERE ROWNUM < 10;
Use this workaround for older (8.0 and prior) releases:
SELECT *
FROM my_table a
WHERE 10 >= (SELECT COUNT(DISTINCT maxcol)
FROM my_table b
WHERE b.maxcol <= a.maxcol)
ORDER BY maxcol;
[edit] How does one select the TOP N rows from a table?
From Oracle 9i onwards, the RANK() and DENSE_RANK() functions can be used to determine the
TOP N rows. Examples:
Get the top 10 employees based on their salary
SELECT ename, sal
FROM ( SELECT ename, sal, RANK() OVER (ORDER BY sal DESC) sal_rank
FROM emp )
WHERE sal_rank <= 10;
Select the employees making the top 10 salaries
SELECT ename, sal
FROM ( SELECT ename, sal, DENSE_RANK() OVER (ORDER BY sal DESC) sal_dense_rank
FROM emp )
WHERE sal_dense_rank <= 10;
For Oracle 8i and above, one can get the Top N rows using an inner-query with an ORDER BY clause:
SELECT *
FROM (SELECT * FROM my_table ORDER BY col_name_1 DESC)
WHERE ROWNUM < 10;

Use this workaround for older (8.0 and prior) releases:


SELECT *
FROM my_table a
WHERE 10 >= (SELECT COUNT(DISTINCT maxcol)
FROM my_table b
WHERE b.maxcol >= a.maxcol)
ORDER BY maxcol DESC;
[edit] How to generate a text graphs (histograms) using SQL?
SELECT d.dname AS "Department",
LPAD('+', COUNT(*), '+') as "Graph"
FROM emp e, dept d
WHERE e.deptno = d.deptno
GROUP BY d.dname;
Sample output:
Department Graph
-------------- -------------------------------------------------ACCOUNTING +++
RESEARCH
+++++
SALES
++++++
In the above example, the value returned by COUNT(*) is used to control the number of "*" characters
to return for each department. We simply pass COUNT(*) as an argument to the string function LPAD
(or RPAD) to return the desired number of *'s.
[edit] Map/ concatenate several rows to a column
This FAQ will demonstrate how row values can be concatenated into a single column value (similar to
MySQL's [i]GROUP_CONCAT[/i] function).
Start by creating this function:
SQL> CREATE OR REPLACE FUNCTION rowconcat(q in VARCHAR2) RETURN VARCHAR2 IS
2 ret VARCHAR2(4000);
3 hold VARCHAR2(4000);
4 cur sys_refcursor;
5 BEGIN
6 OPEN cur FOR q;
7 LOOP
8
FETCH cur INTO hold;
9
EXIT WHEN cur%NOTFOUND;
10
IF ret IS NULL THEN
11
ret := hold;

12
ELSE
13
ret := ret || ',' || hold;
14
END IF;
15 END LOOP;
16 RETURN ret;
17 END;
18 /
Function created.
This function returns a string result with the concatenated non-NULL values from a SQL statement. It
returns NULL if there are no non-NULL values.
Here is an example of how to map several rows to a single concatenated column:
SQL> SELECT rowconcat('SELECT dname FROM dept') AS departments
2 FROM dual;
DEPARTMENTS
-------------------------------------------------------------------------------ACCOUNTING,RESEARCH,SALES,OPERATIONS
This example is more interresting, it concatenates a column across several rows based on an
aggregation:
SQL> col employees format a50
SQL> SELECT deptno,
2
rowconcat('SELECT ename FROM emp a WHERE deptno='||deptno) AS Employees
3 FROM emp
4 GROUP BY deptno
5 /
DEPTNO EMPLOYEES
---------- -------------------------------------------------30 ALLEN,WARD,MARTIN,BLAKE,TURNER,JAMES
20 SMITH,JONES,SCOTT,ADAMS,FORD
10 CLARK,KING,MILLER
[edit] What is the difference between VARCHAR, VARCHAR2 and CHAR data types?
Both CHAR and VARCHAR2 types are used to store character string values, however, they behave
very differently. The VARCHAR type should not be used:
CHAR
CHAR should be used for storing fixed length character strings. String values will be space/blank
padded before stored on disk. If this type is used to store variable length strings, it will waste a lot of
disk space.
SQL> CREATE TABLE char_test (col1 CHAR(10));

Table created.
SQL> INSERT INTO char_test VALUES ('qwerty');
1 row created.
SQL> SELECT col1, length(col1), dump(col1) "ASCII Dump" FROM char_test;
COL1
LENGTH(COL1) ASCII Dump
---------- ------------ -----------------------------------------------------------qwerty
10 Typ=96 Len=10: 113,119,101,114,116,121,32,32,32,32
Note: ASCII character 32 is a blank space.
VARCHAR
Currently VARCHAR behaves exactly the same as VARCHAR2. However, this type should not be
used as it is reserved for future usage.
SQL> CREATE TABLE varchar_test (col1 VARCHAR2(10));
Table created.
SQL> INSERT INTO varchar_test VALUES ('qwerty');
1 row created.
SQL> SELECT col1, length(col1), dump(col1) "ASCII Dump" FROM varchar_test;
COL1
LENGTH(COL1) ASCII Dump
---------- ------------ -----------------------------------------------------------qwerty
6 Typ=1 Len=6: 113,119,101,114,116,121
VARCHAR2
VARCHAR2 is used to store variable length character strings. The string value's length will be stored
on disk with the value itself.
SQL> CREATE TABLE varchar2_test (col1 VARCHAR2(10));
Table created.
SQL> INSERT INTO varchar2_test VALUES ('qwerty');
1 row created.
SQL> SELECT col1, length(col1), dump(col1) "ASCII Dump" FROM varchar2_test;
COL1
LENGTH(COL1) ASCII Dump
---------- ------------ -----------------------------------------------------------qwerty
6 Typ=1 Len=6: 113,119,101,114,116,121

I.DATA DEFINITION LANGUAGE


It is used to define the data base objects.
(A) CREATE
(B) ALTER
(C) DROP
1. How to create a table?
A. CREATE table emp(empno number(3),
ename varchar2(10),
job varchar2(10),
salary number(8),
hire_date date
);
2. How to create a table from the existing table?
A. CREATE table t1
AS select empno,
ename,
deptno
FROM
emp;
3. How to create user?
A. CREATE user hari identified by hari;
4. How to view the table structure?
A. DESC emp;
5. How to modify the structure of the table?
A. ALTER table emp MODIFY address varchar2(25);
6. How to add a column in the existing table?
A. ALTER table emp ADD address varchar2(20);
7. How to drop a column in the table?
A. ALTER table emp DROP COLUMN address;
8. How to set the column unused?
A. ALTER table emp SET UNUSED(ename);

[This column is indirectly dropped]

9. How to drop unused columns?


A. ALTER table emp DROP UNUSED columns;
10. How to drop a table?
A. DROP table emp;
11. How to change the table name?
A. RENAME emp to emp1;
12. How to rename column name?
A. ALTER table emp RENAME column deptno to dno;
II.DATA MANIPULATION LANGUAGE
It is used to manipulate the information in the data base objects.
(A) INSERT
(B) UPDATE
(C) DELETE
1. How to insert data into the table?
A. INSERT into emp VALUES(100,'hari','marketing ',8000,sysdate);
2. How to insert data into a particular column?
A. INSERT into emp(ename,salary) values('raju',7000);
3. How to insert null values into the table?
A. INSERT into emp VALUES(100, 'hari','marketing ',8000,default);
4. How to update or insert row using single condition?
A. MERGE into dept d USING emp e ON(d.deptno=e.deptno)
WHEN MATCHED FOUND then update set d.name=e.ename d.job=e.job d.salary=e.salary
d.deptno=e.deptno
WHEN NOT MATCHED then insert values(e.ename,e.job,e.salary,e.deptno);
5. How to insert multiple rows in to the table?
A. insert all into emp2 values(empno,ename,job,sal,deptno,comm,hire_date) select * from emp;
6. How to update the columns in the existing table?
A. update emp set hire_date=to_date('02/06/05','dd/mm/yyyy') where empno=102;
7. How to update columns more than one?
A. update emp set ename= 'manoj',salary=7000 where empno=108;
8. How to 'delete' or 'truncate' a rows in the table?
A. delete from emp;
[If we use this condition total rows will be deleted]
truncate table emp;
9 How to delete a particular row in the table?
A. delete from emp where empno=100;
10. How to copy rows from one table to other table?
A. insert into emp1(no,name,job,salary) select empno,ename,job,salary from emp;
insert into emp1 select * from emp;

III.DATA CONTROL LANGUAGE


It is used to share information between users
(A) GRANT - It is used to give permission
(B) REVOKE - It is used to cancel the permission
1. How to give permission to another user?
A. grant all on emp to scott1;

[all - means select,insert,update,delete]

2. How to give permission only on delete to another user?


A. grant delete on emp to scott1;
3. How to give permission for insert, update and select to another user?
A. grant insert,update,select on emp to scott1;
4. How to give permission to two users?
A. grant all on emp to scott1,scott2;
5. How to give permission to all users?
A. grant insert on emp to public;
6. How to give permission to scott1 to give grant option to other user?
A. grant all on emp to scott1 with grant option;
7. How to give permission on columns?
A. grant insert(empno,ename,hire_date) on emp to scott1;
8. How to cancel permission from the user?
A. revoke all on emp from scott1;
9. How to cancel permission on particular columns from the user?
A. revoke insert,delete on emp from scott1;
10. How to cancel the permission from all the users?
A. revoke all on emp from public;
11. How to cancel permission on columns?
A. revoke insert on emp from scott1;
12. How to see the permission list given by user to others?
A. desc all_privs_made
13. How to see the permission list received by user from others?
A. desc all_privs_recd
IV.TRANSACTION CONTROL LANGUAGE
It is used to control the DML operation.
(A) COMMIT
- It is used to save the data dynamically.
(B) ROLL BACK - It is used to cancel the changes.
(C) SAVEPOINT - It is used to mark the transactions.
1. How to save the changes permanently?

A. commit;
2. How to cancel changes which we made?
A. rollback;

[if we use DROP condition it will delete permanently]

3. If we made delete,insert,update how to cancel only update statements?


A. savepoint s1;
[ use after deletion]
savepoint s2;
[use after insertion]
rollback to savepoint s2;
[It will cancel only the updates]
commit;
[It will save the changes only for delete & insert]
V.DATA QUERYING LANGUAGE
It is used to get the data from data base objects for read only purpose
(A) SELECT
1. How to see the data in the table?
A. select * from emp;
2. How to retrieve specific columns from the table?
A. select empno,ename,salary from emp;
3. How to do arithmetic operations in the select statement?
A. select empno,ename,salary,salary+3000 from emp;
4. How to use alias in the select statement?
A. select empno,ename,salary,salary*12 "annual salary" from emp;
5. How to eliminate the duplicate rows in the select statement?
A. select distinct deptno from emp;
WHERE CLAUSE & SPECIAL OPERATORS
1. How to retrieve a particular column from the table?
A. select * from emp where empno=100;
select * from emp where salary>4000;
2. How to retrieve the data from the table using between condition?
A. select * from emp where salary between 3000 and 7000;
select * from emp where salary not between 3000 and 7000;
3. How to retrieve data from the table using relation condition?
A. select * from emp where job_id='marketing' and salary>5000;
4. How to retrieve selected row more than one from the table?
A. select * from emp where empno in(100,105,110);
select * from emp where empno not in(100,105,110);
5. How to retrieve names which is starting with 'S' from the table?
A. select * from emp where ename like 's%';
select * from emp where ename not like 's%';
6. How to retrieve upper case characters?
A. select * from emp where upper(ename) like 'A%';

7. How to retrieve lower case characters?


A. select * from emp where lower(ename) like 'a%';
8. How to retrieve names which is ending with S from the table?
A. select * from emp where ename like '%s';
select * from emp where ename not like '%s';
9. How to retrieve names which is the second letter 'S' from the table?
A. select * from emp where ename like '_s%';
select * from emp where ename not like '_s%';
10. How to retrieve null values from the table?
A. select * from emp where comm is null;
select * from emp where comm is not null;
11. How to retrieve data belonging two column conditions from the table?
A. select * from emp where job_id='marketing' or salary>5000;
ARITHEMATIC OPERATIONS
1. How to see the absolute value in the select statement?
A. select empno,ename,abs(comm-salary) from emp;
2. How to see the square root of the given number?
A. select sqrt(5) from dual;
3. How to see the power of the given number?
A. select power(4,2) from dual;
4. How to see the modulus of the given number?
A. select mod(6,3) from dual;

[It gives the remainder value as output]

5. How to see the exponential value for the given number?


A. select exp(5) from dual;
6. How to see the 'log' value?
A. select log(4,3) from dual;
7. How to see the 'sine', 'cosine', 'tan' values?
A. select sin(30),cos(45),tan(60) from dual;
ARITHEMATIC FUNCTIONS
1. How to see the whole number for the output value?
A. select round(sin(30)) from dual;
Select round(19.7876) ,round(19.4634),round(19.7872,2) from dual;

[Ans: 20 19 19.78]

2. How to use trunc function?


A. select trunc(19.7876),trunc(19.4536),trunc(19.7342,2) from dual;

[Ans: 19 19 19.73]

CHARACTER FUNCTIONS
1. How to display the first char as capital?
A. select empno,initcap(ename),job,salary from emp;

2. How to display the string in capital letter?


A. select empno,upper(ename),salary from emp;
3. How to display the string in small letters?
A. select empno,lower(ename),job,deptno from emp;
4. How to display the length of the string in the table?
A. select empno,ename,length(ename) from the emp;
5. How to display the string in reverse?
A. select empno,ename,reverse(ename) from emp;
6. How to display the ascii value of the character in number?
A. select ascii('A'),ascii('a') from dual;
7. How to display the number in ascii value?
A. select chr(43),chr(50) from the dual;
8. How to display the left space with * in the select statement?
A. select empno,ename,lpad(sal,6,'*') from emp;
9. How to display the right space with & in the select statement?
A. select empno,ename,rpad(sal,6,'*') from emp;
10. How to remove the first char in the string?
A. select ename,trim('s' from ename) from emp;
11. How to concatenate ename with a job in the select statement?
A. select ename ||'is a'|| job from emp;
12. How to replace string in the table?
A. select ename,replace(ename,'s',2) from emp;
13. How to translate the characters in the select statement?
A. select empno,ename,translate(ename,'aeiou','12345') from emp;
14. How to display the first five letter of the string in the table?
A. select empno,ename,substr(ename,1,5) from emp;
15. How to see the position of the char?
A. select ename,instr(ename,'a',1,1) from emp;
DATE FUNCTIONS
1. How to display the sysdate date?
A. select sysdate from dual;
2. How to see how many months happen up to now from joining?
A. select ename,job,months_between(sysdate,hire_date) from emp;
3. How to add months to the hire_date in the select statement?
A. select ename,hire_date,add_months(hire_date,6) from emp;

['is a' it is a literal string]

4. How to display the next day using hire_date?


A. select hire_date,next_day(hire_date,'Friday') from emp;
5. How to display the last day of the month?
A. select hire_date,last_day(hire_date) from emp;
TIME FUNCTIONS
1. How to see the fractional seconds with date & time of server?
A. select systimestamp from dual;
2. How to see the fractional seconds with date & time of client system?
A. select current_timestamp from dual;
3. How to see the date of client system?
A. select current_date from dual;
4. How to converts the date into timestamp?
A. select to_timestamp(sysdate) from dual;
CHARACTER FORMATS
1. How we can display the date format in another model?
A. select hire_date,to_char(hire_date,'ddth/mm/yyyy') from emp;
select hire_date,to_char(hire_date,'dy mon yyyy') from emp;
select hire_date,to_char(hire_date,'day month year') from emp;

[special characters are th,nd,st]

GENERAL FUNCTIONS
1. How to select the least value from the given values?
A. select least(12,09,4,20,6,46) from dual;
2. How to select greatest value from the given values?
A. select greatest(12,09,4,20,6,46) from dual;
3. How to select minimum & maximum salary from the table?
A. select min(salary),max(salary) from emp;
SPECIAL OPERATORS
1. How to converts a null value in to actual value?
A. select empno,ename,nvl(comm,10) from emp;
select count(nvl(comm,0)) from emp;

[if the comm is null then it takes the value as 10]

2. How to use NVL2 in the select statement?


A. select empno,ename,nvl2(comm,salary+comm,salary) from emp;
[if exp1 is true it displays exp2, if exp1 is false then it displays exp3]
3. How to use NULLIF in the select statement?
A. select length(ename),length(job_id),nullif(length(ename),length(job_id)) "result" from emp;
[if the exp1 & exp2 lengths are equal then it displays value as null]

4. How to use COALESCE in the select statement?


A. select empno,ename,coalesce(comm,salary,10) from emp;
[if exp1 is not null it shows comm, if
exp1 is null it shows sal, if two exps are null it shows the value as 10]
5. How to use CASE expression in the select statement?
A. select ename,salary,case job_id when 'marketing' then .10*sal when 'clerk' then .5*sal
else salary end "revised salary" from emp;
6. How to use DECODE expression in the select statement?
A. select ename,salary decode(job_id,'marketing',0.10*sal,'clerk',0.5*sal,sal) "salary" from emp;
OREDER BY CLAUSE
1. How to retrieve the data in the ascending order from the table?
A. select * from emp order by deptno;
2. How to retrieve data in the descending order from the table?
A. select * from emp order by empno desc;
GROUP FUNCTIONS
Group functions operate on sets of rows to give one result per group
1. How to select average & sum salary from the table?
A. select avg(salary),sum(salary) from emp;
2. How to select maximum & minimum salary in the table?
A. select max(salary),min(salary) from emp;
3. How to select total no.of row in the table?
A. select count(*) from emp;
select count(empno) from emp;
4. How to display the salary according to deptno?
A. select deptno,avg(salary) from emp group by deptno;
5. How to use HAVING clause in group function?
A. select deptno,avg(salary) from emp group by deptno having avg(salary)>5000;
HIERARCHICAL DATA ACCESS
1. Display all the employees name in their relational hierarchy?
A. select ename from emp start with mgr is null connect by prior empno=mgr;
2. Display all the employees name in their relation hierarchy output should be formatted?
A. select lpad(ename,length(ename)+level) from emp start with mgr is null connect by prior
empno=mgr;
3. Display those employees whose level is odd number?
A. select ename from emp where mod(level,2)!=0 start with mgr is null connect by prior
empno=mgr;

4. Display total salary paid by Jones to his employees?


A. select sum(sal) from emp where level>1 start with ename='JONES' connect by prior empno=mgr;
JOINS
1. How to display data from two tables using 'cross join' or 'cartesian join'?
A. select * from emp,dept;
2. How to display data from two tables using 'equi join' or 'natural join' condition?
A. select e.empno,e.ename,e.deptno,d.dname from emp e,dept d where e.deptno=d.deptno;
select e.empno,e.deptno,d.dname from emp e,dept d where e.deptno=d.deptno and ename='hari';
3. How to join more than two tables?
A. select e.ename,e.deptno,d.dname,d.loc_id,l.address from emp e,dept d,loc l where
e.deptno =d.deptno and d.loc_id=l.loc_id;
4. How to use 'outer join' in the select statement?
A. select e.empno,e.ename,e.deptno,d.dname from emp e,dept d where e.deptno(+)=d.deptno;
select e.empno,e.ename,e.deptno,d.dname from emp e,dept d where e.deptno=d.deptno(+);
5. How to retrieve two tables using 'USING' clause?
A. select e.empno,e.ename,e.deptno,d.dname from emp e,dept d using(deptno);
6. How to retrieve two tables using outer joins?
A. select e.empno,e.ename,d.dname from emp e full outer join dept d on(e.deptno=d.deptno);
select e.empno,e.ename,d.dname from emp e left outer join dept d on(e.deptno=d.deptno);
select e.empno,e.ename,d.dname from emp e right outer join dept d on(e.deptno=d.deptno);
7. How to use set operators in joins?
A. select distinct job from emp where deptno=10 union all select distinct job from emp where
deptno=20;
select distinct job from emp where deptno=10 union select distinct job from emp where
deptno=20;
select distinct job from emp where deptno=10 intersect select distinct job from emp where
deptno=20;
select distinct job from emp where deptno=10 minus select distinct job from emp where
deptno=20;
SUB QUERY
Simple Subquery
Correlated Subquery
1. How to display the data who is having more than average salary?
A. select empno,ename,job,salary from emp where salary>(select avg(salary) from emp);
select * from emp where deptno=(select deptno from emp where ename='krishna');
2. How to display the employees who joined the company before their employees?
A. select * from emp e where e.hiredate>(select m.hiredate from emp m where e.mgr=m.empno);
LOCKS
1. How to lock a row for update or insert?
A. select * from emp where empno=100 for update;[commit or rollback will release any type of lock]

2. How to lock the table for manipulations?


A. lock table emp in share mode;
lock table emp in share update mode;
lock table emp in exclusive mode;
CONSTRAINTS
1. How to create primary constraint?
A. create table emp(empno number(2),ename varchar2(10),job varchar2(10),deptno number(3),
constraint emp_deptno_pk primary key(deptno));
2. How to create foreign constraint?
A. create table dept(deptno number(3),dname varchar2(10),loc number(6),constraint
dept_deptno_fk foreign key(deptno) references emp(deptno);
3. How to delete child table from parent table?
A. create table dept(deptno number(3),dname varchar2(10),loc number(6),constraint
dept_deptno_fk foreign key(deptno) references emp(deptno) on delete cascade;
4. How to add a 'not null' in the existing table?
A. alter table emp modify empno not null;
5. How to add a 'unique' constraint in the existing table?
A. alter table emp add constraint emp_ename_uk unique(ename);
6. How to add a check salary constraint in the existing table?
A. alter table emp add constraint emp_salary_min check(salary>5000);
7. How to drop constraint?
A. alter table emp drop constraint emp_deptno_pk;
8. How to disable constraint?
A. alter table emp disable constraint emp_salary_min cascade;
9. How to enable constraint?
A. alter table emp enable constraint emp_salary_min cascade;
10. How to view constraint?
A. select owner,constraint_name,constraint_type from user_constraints where table_name='emp';
[To see the user constraints the query is : desc user_constraints]
SQL REPORTING COMMANDS
1. How to set the title in the top of the table?
A. ttitle on;
ttitle 'employee reports';
2. How to off the ttitle?
A. ttitle off;
3. How to set the title in the left side?
A. ttitle left 'employee reports' skip left;

4. How to set the title in the center?


A. ttitle center 'employee reports' skip center;
5. How to set the title in the right side?
A. ttitle right 'employee reports' skip right;
6. How to set the title in the bottom of the table?
A. btitle on;
btitle 'End of the report'
7. How to off the btitle?
A. btitle off;
8. How to change the column name?
A. column empno heading 'no';
9. How to change the salary format?
A. column sal heading 'salary' format $9,999.99;
10. How to clear column heading?
A. column empno clear;
11. How to break the deptno?
A. break on deptno;
12. How to clear the break command?
A. clear breaks;
clear breaks on deptno;

[it clears all the break command]

VIEWS
* It is a stored select statement.
* It will not hold any data.
* Desc, DML, Select allowed in views.
* Any manipulations in view will be reflected in table.
* Providing high security while sharing view with other users.
1. How to create view?
A. create view v1 as select * from emp;
2. How to display the view structure?
A. desc view
3. How to insert values in view?
A. insert into view v1 values(108,'prasad','clerk',7000,40,sysdate);
[these values will be automatically inserted into emp also]
4. How to update values in to view?
A. update v1 set salary=8000 where empno=102;
5. How to delete rows in view?
A. delete from v1 where empno=102;

6. How to drop column in view?


A. no alter option in views;
7. How to drop view?
A. drop view v1;
8. How to create view based on view?
A. create view v3 as select * from v1 where salary>5000;
9. How to create view for read purpose?
A. create view v2 as select * from emp with read only; [we cannot do any changes in Read Only]
10. How to create view with out table?
A. create force view v1 as select * from emp1;
create table emp1 as select * from emp;
11. How to create materialized view?
A. create materialized view mv1 as select * from emp;
[OR]
create snapshot s1 as select * from emp;
[this view will exit if u drop the emp table also, we cannot use DML option]
[we have to create a table with primary key
]
12. How to effect manipulation of emp in materialized view?
A. create materialized view mv1 refresh on commit as select * from emp;
[After manipulation in emp we have to give commit to occur in the view]
13. How to drop materialized view?
A. drop materialized view mv1;
drop snapshot s1;
14. How to create view from more than one table?
A. create view v1 as select empno,ename,e.deptno,dname,loc from emp e,dept d where
e.deptno=d.deptno;
[in join view, no DML option]
15. How to create view using with check option?
A. create view v1 as select * from emp where deptno=30 with check option;
[we cannot insert rows & update the deptno because it violates with check option]
16. How to create a complex view?
A. create view v1(name,max(sal),min(sal),avg(sal)) as select d.dname,max(e.sal),min(e.sal),
avg(e.sal) from emp e,dept d where e.deptno=d.deptno group by d.dname;
[we cannot do any manipulations in a complex view]
ROWNUM
* It is automatically generated when select is performed.
* It is a unique value but not stored permanently.
1. How to retrieve the top 5 salaried employees?
A. select rownum,empno,ename,sal from (select rownum,empno,ename,sal from emp order by
sal desc) where rownum<=5;
2. How to retrieve the Nth salaried employee?

A. select empno,ename,job,sal from (select empno,ename,job,sal from emp order by sal desc)
group by rownum,empno,ename,job,sal having rownum=&n;
3. How to retrieve alternate rows?
A. select rownum,empno,ename,job,sal from emp group by rownum,empno,ename,job,sal having
mod(rownum,2)=0;
4. How to delete the duplicate records which is having the same data,empno & ename?
A. delete from emp where rowid not in(select min(rowid) from emp group by empno);
5. How to retrieve the first five rows from the table?
A. select * from emp where rownum<6;
6. How to retrieve the last five rows from the table?
A. select * from emp minus select * from emp where rownum<=10;
select * from emp minus select * from emp where rownum<=(select max(rownum)-5 from emp);
7. How to retrieve a particular row from the table?
A. select * from emp where rownum<6 minus select * from emp where rownum<5;
8. How to see the no.of rows in the table?
A. select max(rownum) from emp;
9. How to delete a row from the table using rownum?
A. delete from emp where rownum<2;
delete from emp where rownum<5;
10. How to update row using rownum?
A. update emp set sal=2500 where rownum<2;
SEQUENCE
It is used to generate number in order.
It is not related to the tables.
It uses two pseudo columns.
-- nextval (holds the next generated value)
--currval (holds the current available value)
1. How to create sequence?
A. create sequence s1
increment by 1
start with 200
maxvalue 210
nocache
nocycle;
2. How to insert into a table using sequence?
A. insert into emp(empno,ename,job,salary,deptno) values(s1.nextval,'ravi','employee',8000,10);
3. How to see the sequence current value?
A. select s1.currval from dual;

4. How to see the sequence next value?


A. select s1.nextval from dual;
5. How to see the structure of sequence?
A. select sequence_name,min_value,max_value,increment_by,last_number from user_sequences;
[to see the user sequence the query is : desc user_sequences;]
6. How to modify sequence?
A. alter sequence s1
increment by 1
maxvalue 220
nocache
nocycle;
7. How to drop the sequence?
A. drop sequence s1;
INDEX
It is mainly used to improve performance which retrieving (or) manipulating data by using
indexed columns in where clause. It is a pointer to locate the address of data.
1. How to create index on emp?
A. create index i1 on emp(empno);
create index i2 on emp(sal,deptno);
2. How to use index?
A. select * from emp where ename='ram';
select * from emp where sal=3000 and deptno=20;

[the index will be activate in the back ground]

3. How to drop index?


A. drop index idx1;
4. How to see the structure of index?
A. select index_name,index_type,table_owner,table_name,table_type from user_indexes;
[to see the user indexes, query is : desc user_indexes]
SYNONYM
Synonym is nothing but an Alias name to the table.
1. How to create synonym?
A. create synonym s1 for emp;
[it is a copy of emp & it is related to emp table]
2. How to drop synonym?
A. drop synonym s1;
SPOOL
1. How to save the statements which we done in SQL in to a folder?
A. spool d:\hari
select * from emp;
spool off
DATABASE UTILITIES

Export the file


Import the file
1. How to export the data into the file?
A. conn system/manager
create user hari identified by hari;
grant connect,resource,dba to hari;
conn scott/tiger
host
D:\oracle\ora90\bin> EXP
Username : scott
(enter)
Password : tiger
(enter)
Enter array fetch buffersize:4096>
(enter)
Export file:EXP.DMP.DMP> D:\hari.dmp
(file name)
(2)U(sers),or (3)T(ables): (2)U>
(enter)
export grants (yes/no): yes>
(enter)
export table data (yes/no): yes>
(enter)
compress extents (yes/no): yes>
(enter)
User to be exported: <return to quit> > scott (enter)
User to be exported: <return to quit> >
(enter)
D:\oracle\ora90\bin>exit
2. How to import data from file into database?
A. conn hari/hari
Host
D:\oracle\ora90\bin> IMP
Username : hari
Password : hari
Import file:EXP.DMP.DMP> D:\hari.DMP
Enter insert buffer size(minimum is 8192)) 30720>
List contents of import file only(yes/no) no>
Ignore create error due to object existence (yes/no) no>
Import grants(yes/no) yes>
Import table data (yes/no): yes>
Import entire export file (yes/no): no>
Username: scott
Enter table(T) or partition(T:P)name or . If done:
D:\oracle\ora90\bin>exit

(enter)
(enter)
(enter)
(enter)
(enter)
(enter)

You might also like