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.
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:
DML - Data Manipulation Language: statements used for managing data within
schema objects. Some examples:
DML are not auto-commit. i.e. you can roll-back the operations, but DDL are auto-
commit
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> COMMIT;
Commit complete.
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.
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.
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.
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?
From Oracle 8i, the easiest way to randomly select rows from a table is to use the
SAMPLE clause with a SELECT statement. Examples:
In the above example, Oracle is instructed to randomly return 10% of the rows in
the table.
ORDER BY dbms_random.value()
Method 1:
Delete all rowids that is BIGGER than the SMALLEST rowid value (for a given key):
Method 2:
How does one get the time difference between two date columns?
Solution 1
Solution 2
If you don't want to go through the floor and ceiling maths, try this method:
Solution 3
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).
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.
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);
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...
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.
SELECT *
FROM (SELECT * FROM my_table ORDER BY col_name_1 DESC)
WHERE ROWNUM < 10;
SELECT *
FROM (SELECT * FROM my_table ORDER BY col_name_1)
WHERE ROWNUM < 10;
SELECT *
FROM emp
WHERE (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,4)
FROM emp);
SELECT *
FROM ( SELECT rownum rn, empno, ename
FROM emp
) temp
WHERE MOD(temp.ROWNUM,4) = 0;
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.
One can use the CASE statement or functions like DECODE, NVL, NVL2, NULLIF,
COALESCE, etc.
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.
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
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
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
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..
BY USING DISTINCT
LIKE
DEPTNO
------
10
20
30
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
Session 1
session 2
No rows found.
Session 1
Rollback;
Session 2
12 rows selected.
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:
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.
Disadvatages:
2. When table is dropped view becomes inactive.. it depends on the table objects.
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.
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.
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
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...
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......
There is no difference. Cartesian Products and Cross Joins are the same.
FROM user_constraints
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
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.
or
NAME SALARY
---------- ----------
MANI 10000
SELVAM 10000
SURAJ 10000
KAMAL 20000
RAMESH 20000
SARA 20000
6 rows selected.
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.
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.
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
Translate:
Ex:
result: ashok
Replace:
Ex:
select replace('tech world' 'Tech' 'technology')
from dual;
EMP
Emp_Id varchar(10)
Location varchar(12)
you can remove the duplicates using 'union'
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
select sal from (select distinct(sal) from emp where sal is NOT NULL order by sal dsc) where
rownum n
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.
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
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
Ref Cursor is object name of the cursor type. Its mainly used for dynamic purpose
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.
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
Rowtype means associating a single variable to a entire row.(It is one way of Declaring a
composite plsql datatype RECORD )
both Rowtype and type declarations are known as Anchored Declarations in plsql .