Vous êtes sur la page 1sur 18

what is the internal structure of database and how sql is related with it?

Databse data is stored in data_file's of the databse. For every table's data some
space from the data_files would be allocated. This space is known as data segment.
Say you have a table named EMP. There could be a data segment 'EMP_DATA_SEG'
for this table. So when you query the table using the the query 'SELECT ENO FROM
EMP' Oracle server would parse the query ( check for syntax table availability your
authentication on that table etc) and then would go to the data segment to get you
the the data based on the condition that your query has specified.

What is difference between UNIQUE and PRIMARY KEY constraints?

A table can have only one PRIMARY KEY whereas there can be any number of
UNIQUE keys. The columns that compose PK are automatically define NOT NULL,
whereas a column that compose a UNIQUE is not automatically defined to be
mandatory must also specify the column is NOT NULL

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

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.

How does one escape special characters when writing SQL queries?

Use two quotes for every one displayed

Can one select a random collection of rows from a table?

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.

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

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;

How does one get the time difference between two date columns?

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

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);

Can one retrieve only the Nth row from a table?

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.

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.

How does one select the TOP N rows from a table?

SELECT *
FROM (SELECT * FROM my_table ORDER BY col_name_1 DESC)
WHERE ROWNUM < 10;

How does one select the LAST N rows from a table?

SELECT *
FROM (SELECT * FROM my_table ORDER BY col_name_1)
WHERE ROWNUM < 10;

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.

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] )

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.

VARCHAR

Currently VARCHAR behaves exactly the same as VARCHAR2. However, this type
should not be used as it is reserved for future usage.

VARCHAR2

VARCHAR2 is used to store variable length character strings. The string value's length
will be stored on disk with the value itself.

What is a pseudo column. Give some examples?

pseudocolumn behaves like an column of a table but actually it is not a column of the table.
User can not insert/update/delete this column

Which is more faster - IN or EXISTS?

it is always better to use exists when u go correlated sub queries in for ordinary sub queries

When do you use WHERE clause and when do you use HAVING clause?

The WHERE clause is a conditional construct used to restrict or limit rows based on some
condition.

If the condition is satisfied then the filtered rows are returned as output. Consider this
example

SELECT ename job_id


FROM emp
WHERE deptno 10
ORDER BY ename desc;

The above example returns the employee name and job id of employees who are working in
department number 10.

The rows are filtered here based on the condition mentioned in the WHERE clause
HAVING clause is also a conditional clause similar to WHERE
The HAVING clause was introduced by oracle coz you can't use group functions like
SUM MIN MAX COUNT AVG STDDEV VARIANCE in the WHERE clause

Consider this example

SELECT ename avg(salary)


FROM emp
WHERE avg(sal)>1000

This example gives you an error stating "group function is not allowed here" which means one
can't use group functions in WHERE clause. We can rewrite the above example as
SELECT ename avg(sal)
FROM emp
HAVING avg(sal)>1000
GROUP BY ename;

This displays the employee name and average salary of employees whose average salary is
more than 1000

NOTE: Group function must always be used when you are using having clause
Because you have used a group function in the having clause to filter the records..

How you will avoid duplicating records in a query?

BY USING DISTINCT

LIKE

WE HAVE COLUMN DEPTNO


10
10
20
20
10

WHEN YOU USE


SELECT DISTINCT DEpTNO FROM EMP;

DEPTNO
------
10
20
30

Which datatype is used for storing graphics and images?

Blob datatype for storing images....

What is difference between SUBSTR and INSTR?

substr:
sub(string n m): It returns the characters from nth position m
characters long
Ex:-substr(abcdefgh 3 3) it returns cde

instr:

instr(string n m):It returns the position of the nth character of the mth
occurrence.
Ex:-instr(abcadea 1 3) it returns 7

Can a primary key contain more than one columns?

Yes we can choose more than one column as primarykey


This is also known as composite primary key

SESSION 1 DELETE FROM EMP;


SESSION 2 SELECT * FROM EMP; What will be the result?

Delete is a DML statement so there is no auto commit for delete.

TO answer the question.

Session 1

DELETE FROM EMP;

session 2

SELECT * FROM EMP;

No rows found.

Session 1

Rollback;

Session 2

SELECT * FROM EMP;

12 rows selected.

What is the difference between ROWNUM and ROWID

Rowid: Hexadecimal string representing the unique address of a row in its table. This datatype
is primarily for values returned by the ROWID pseudocolumn.

Rownum: For each row returned by a query the ROWNUM pseudocolumn returns a number
indicating the order in which Oracle selects the row from a table or set of joined rows. The first
row selected has a ROWNUM of 1 the second has 2 and so on. You can use ROWNUM to limit
the number of rows returned by a query as in this example:

SELECT * FROM employees WHERE ROWNUM < 10;

What are the advantages and disadvantages of View?

Advantages of views:

1. View the data without storing the data into the object.

2. Restict the view of a table i.e. can hide some of columns in the tables.

3. Join two or more tables and show it as one object to user.


4. Restict the access of a table so that nobody can insert the rows into the table.

Disadvatages:

1. Can not use DML operations on this.

2. When table is dropped view becomes inactive.. it depends on the table objects.

3. It is an object so it occupies space.

What is Complex View? Where we can use?

we go for complex views when we want to display from two or more tables using group cluase
or grouping aggregate functions

In Oracle10g sqlplus, how do you find the tables that have been dropped?

When you drop a table normally the database does not immediately release the space
associated with the table. Rather the database renames the table and places it in a recycle bin
where it can later be recovered with the FLASHBACK TABLE statement if you find that you
dropped the table in error.

FLASHBACK TABLE RECYCLETEST TO BEFORE DROP;

what is an inline view?

An inline view is created by placing a subquery in the FROM clause and giving that subquery an
alias. The subquery defines a data source that can be referenced in the main query.

how many number of tables we can join in join concepts?


is there any limitation?

No limit

since joins and subqueries are used for same purpose , why we have two things.is
there any need

In some times we may nt retrive the data from Joins in such scenario we must depend up on
sub-queries like Correlation of tables .. to do so we must use Subqueris only...

what is difference between sub query and correlated sub query, Give the example
for this.

Corelated sub query will fire for each row and sub query will fire only once like that easy to
remember

How to find Nth largest or Nth smallest data from oracle table, for ex..5th highest
salary from employees

To find the nth higest salary:


select min(sal) from (select distinct sal from emp order by sal desc) where rownum< &n;

To find the nth smallest salary:

select max(sal) from (select distinct sal from emp order by sal) where rownum< &n;

Dont get confused... its min(sal) for highest and max(sal) for lowest. Becos:

Ex: Top 3 salaries - 5000 3000 2975 for 3rd higest min(sal) i.e 2975...

What is Cartesian product in the SQL?

when a join condition is omited when getting result from two tables then that kind of query
gives us Cartesian product in which all combination of rows displayed. All rows in the first table
is joined to all rows of second table......

What is difference between Cartesian Join & Cross Join?

There is no difference. Cartesian Products and Cross Joins are the same.

How to see the existing constraints in a table?

SELECT constraint_name constraint_type

FROM user_constraints

WHERE table_name 'EMPLOYEES';

Is it possible to update Views? If yes, How, If Not, Why?

There are two types of views namely Simple and complex views.

U can perform DML operation on simple views which is based on single table and that view
doesn't contain any single row function and any group by clause and it has to satiesfy integrity
constraint also.

U can't perform DML operation on complex views becuase they are based on multiple table. U
can achive this task by using Triggers(Instade of...).

There are 10 rows in Table A and 0 Rows in table B. Select * from A,B How many
rows will be retrieved.

no rows selected

How do you view the last record added to a table?

select * from test where rowid ( select max(rowid) from test);

test is table name. Replace test with appropriate table name


We have two type of constraints - Table Level and Column Level. Which is better
and why..?

constraints are maiainly five


1.not null
2.unique
3primarykey
4.foreignkey
5.check
all colun level constarins only applited to table

Performance wise there will not be any difference between table level and column level
constraints.

Generally we use table level constraint to define composit keys( Constraint on combination of
columns). Except not null constraint remaining constraints cane be defined at table table or
column level. Not null constraint must be declared as column level constraint only.

Write a query to display employee records having same salary?

select * from emp where sal in(


select sal from emp where rowid not in(
select max(rowid) from emp group by sal))

or

select a.empno a.ename a.sal from scott.emp a where a.sal in

(select sal from scott.emp group by sal having count(*)>1)

SQL> select distinct e.name e.salary from employe e employe a


2 where e.salary a.salary and e.name ! a.name;

NAME SALARY
---------- ----------
MANI 10000
SELVAM 10000
SURAJ 10000
KAMAL 20000
RAMESH 20000
SARA 20000

6 rows selected.

Difference between nested query,sub query and nested query?

query inside the query is nested query.

it is also called as sub query.

Correlated subquery runs once for each row selected by the outer query. It contains a
reference to a value from the row selected by the outer query.

Nested subquery runs only once for the entire nesting (outer) query. It does not contain any
reference to the outer query row.

can we insert a record in dual?

Dual is a table owned by sys user and public synonym for the same is created.
So it is available to all the users of the database.

To get the details use following query :

select * from all_synonyms a


where a.synonym_name 'DUAL';

By using create table to create dual table we can insert into dual .

But without creating dual we cannot insert into dual.As we didn't have insert object privilege
on sys.dual table or public synonym dual

How and in what way REPLACE is different from TRANSLATE?

Translate:

It is used to replace charecter by charecter

Ex:

Select translate('ashok' 'xp' 'sk')


from dual;

result: ashok

Replace:

It is used to replace word by word

Ex:
select replace('tech world' 'Tech' 'technology')
from dual;

result: technology world

how we can eliminate duplicates without using distinct command?

Assume 'location' is the column in 'Emp' table has several duplicates

EMP

Emp_Id varchar(10)
Location varchar(12)
you can remove the duplicates using 'union'

select location from emp union select location from emp ;

this will strip the duplicates .

Where clause restricts rows, what does having clause restricts ?


1. only group results.
2. rows results.
3. both rows and groups result.

1) HAVING clause can only be used to filter out the aggegate functions whereas
WHERE clause cannot filter out the aggegate functions.
2) HAVING clause can be used with GROUP BY function where as WHERE clause
cannot be used with group by function

Find out nth highest salary from emp table

select sal from (select distinct(sal) from emp where sal is NOT NULL order by sal dsc) where
rownum n

Display Odd/ Even number of records

For odd:
SELECT MAX(ROWNUM) EMPNO ENAME FROM EMP
GROUP BY ROWNUM EMPNO ENAME
HAVING MOD(ROWNUM 2)<>0

For even:
SELECT MAX(ROWNUM) EMPNO ENAME FROM EMP
GROUP BY ROWNUM EMPNO ENAME
HAVING MOD(ROWNUM 2) 0

What is the need of primary key as opposed to using not null and unique ?

1) Primary key creates clustered index by default which actually reorders the row in a table
based on index while unique key creates non-clustered index.

2) Replication of table possible only if it contains primary key.

Is the order in which the conditions are given in the 'WHERE' clause are
important?

Yes the order is important. But it is important for the performance of the query and not for the
final result. The output of the query will be the same irrespective of the order in which the
join conditions are applied. Ideally the condition that filters maximum number of records
should be placed last. Reason Oracle follows a bottom up approach.
What is nested table in Oracle and and difference between table and nested table

A nested table can be stored as a database column. This means that the entire nested table is
contained in one row of a table and each row of the table can contain different nested table

1. Can be stored in database

2. can be manipulated using SQL

3. can be automatically null

4. individual elements can be accessed using subscript

What are the types of cursors apart from explicit and implicit cursors ? Explain
when and where they are used ?

1. Implicit Cursor
2. Explicit Cursor
3. Ref Cursor

Implicit Cursor like SQL rowcount SQL rowtype...

Explicit cursors are user defined cursor

Ref Cursor is object name of the cursor type. Its mainly used for dynamic purpose

The difference between these two is


1. A cursor is once define its contents are fixed and can't be changed.
Using ref cursor we can create a dynamic cursor. In dynamic cursors the contents of cursor can
be changed dynamically depending upon the sitution.
2. A cursor can't be passed as parameter from subroutine to subroutine. Where as ref cursor
can be passed as paramer to subprograms.
3. A ref cursor can be returned to the client machine. A cursor can't.
4. A cusor can be defined globally. A ref cursor can't

Generally we use ref cursor when we need to return result set. In other cases it is advisable to
use static cursor because they give better performace.

Why DUAL table is not visible?

DUAL is a part data dictionary and owned by SYS. You should not make modifications to this
table.
It contains only one row and one column of VARCHAR2 datatype.
Used to refer an object which does not have any pysical reference in database table.
Ex:- Select sysdate from dual

What are mutating tables?

Mutating tables are the tables which is currently modifying by itself.

What is materialized view?


A materialized view is a database object that contains the results of a query. They are local
copies of data located remotely or are used to create summary tables based on aggregations of
a table's data. Materialized views which store data based on remote tables are also know as
snapshots.A materialized view can query tables views and other materialized views.
Collectively these are called master tables (a replication term) or detail tables (a data
warehouse term).

what is the diff between %Rowtype and %type?

Rowtype means associating a single variable to a entire row.(It is one way of Declaring a
composite plsql datatype RECORD )

type means associating a single variable to a particular column in table.

both Rowtype and type declarations are known as Anchored Declarations in plsql .