Write SQL Query to display current date.
Ans: SQL has built in function called GetDate () which returns current timestamp.
Mention the difference between clustered and a non-clustered index?
1. A clustered index is a special type of index that reorders the way records in the table are
physically stored. Therefore table can have only one clustered index.
2. A non clustered index is a special type of index in which the logical order of the index does
not match the physical stored order of the rows on disk. The leaf node of a non clustered
index does not consist of the data pages. Instead, the leaf nodes contain index rows.
Write an SQL Query to find names of employee start with ‘S’.
Ans: SELECT * FROM Employees WHERE EmpName like ‘S%’.
When do you use UPDATE_STATISTICS command?
Ans: This command is used when a large processing of data has occurred. If any large amount of
deletions, any modifications, or Bulk Copy into the tables has occurred, it has to update the
indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these
tables accordingly.
What type of Joins have you used?
Ans: Most SQL programmers have used inner join and (left/right) outer join; but the catch point
here is to also mention cross join and self-join.
How will you find the 3rd max salary in the employment table?
Ans: Select distinct salary from employment e1 where 3= (select count (distinct salary) from
employment e2 where [Link]<=[Link])
How would apply date range filter?
Ans: One can use simple conditions like >= and <=, or use between/and but the trick here is to
know your exact data type.
o Sometimes date fields contain time and that is where the query can go wrong so it is
recommended to use some date related functions to remove the time issue. In SQL Server
common function for accomplishing the task datediff () function.
o Interviewees also have to be aware of different time zones and server time zone.
o To increase query performance you may still want to use between however you should be
aware of proper format you should use if not it might misbehave during filtering.
How will I retrieve all records of employment 1 those should not be present n employment 2?
Ans: (Select * from employment 2)-(Select * from employment 1).
Define Trigger.
Ans: Trigger allows us to execute a batch of SQL code when an insert, update or delete command
is executed against a specific table.
Triggers are special types of stored procedures that are defined to execute automatically in place
of or after data modifications. They can be executed automatically on the insert, delete and update
operation.
Define a temp table.
Ans: In a nutshell, a temp table is a temporary storage structure. It means you can use a temp
table to store data temporarily so you can manipulate and change it before it reaches its
destination format.
In table_user.gender column change ‘male to female’ and ‘female to male’ in one SQL statement.
Ans: UPDATE table_user
SET gender =
CASE gender
WHEN ‘male’ THEN ‘female’
WHEN ‘female’ THEN ‘male’
ELSE gender
END
How will you find out 7th highest salary in a table?
Ans: SELECT * FROM(SELECT ROW_NUMBER()OVER(ORDER BY sal DESC)
row_number,empno,sal FROM emp) a WHERE row_number = 7
State one similarity and difference between WHERE Clause and HAVING Clause?
Similarity: Both WHERE and HAVING Clause filters out records based on one or more conditions.
Difference: WHERE Clause can only be applied to a static non-aggregated column whereas HAVING
is needed for aggregated columns.
What is the difference between a primary key and a unique key?
By default, primary key creates a clustered index on the column, whereas a unique key creates a
non clustered index by default.
What are defaults? Is there a column to which a default can’t be bound?
A default is a value which will be used by a column, if no value is supplied to that column while
inserting data.
What are constraints? Mention the different types of constraints?
Constraints enable the RDBMS to enforce the integrity of the database automatically, without the
need to create triggers, rule or defaults.
Types of Constraints: NOT NULL, CHEQUE, UNIQUE, PRIMARY KEY, FOREIGN KEY.
What is the difference between JOIN and UNION?
SQL JOIN allows access to records of other table based on the given conditions between two tables.
Ex: If we are provided with the department ID of each employee, then we can use the department
ID of the employee table to merge with the department ID of the department table to access
department names.
UNION operation allows addition of 2 similar data sets to create a resulting set that contains all the
data from the source data sets.
Ex: If we are provided with 2 employee tables of the same structure, we can UNION them to create
a singular result that will contain all employee from both the table.
What are dimension tables and definition of Fact tables?
Fact tables are mainly central tables that are an integral part of data warehousing and dimension
tables are used for describing the attributes of the fact tables. Both of these tables are important
and play an important role in maintaining the database management system.
What exactly the ETL process means in database system?
ETL process is defined as Extraction, Transformation and loading of data during different stages in
the database management system. ETL also involves data mining, which is mainly process of
analyzing of the present data and the summary of the information. All these steps are very
important in a database management system and helps in faster execution of things in a smooth
and easy manner.
To fetch ALTERNATE records from a table. (EVEN NUMBERED)
select * from emp where rowid in (select decode(mod(rownum,2),0,rowid, null) from emp);
To select ALTERNATE records from a table. (ODD NUMBERED)
select * from emp where rowid in (select decode(mod(rownum,2),0,null ,rowid) from emp);
Find the 3rd MAX salary in the emp table.
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where [Link] <=
[Link]);
Find the 3rd MIN salary in the emp table.
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2where [Link] >=
[Link]);
Select FIRST n records from a table.
select * from emp where rownum <= &n;
Select LAST n records from a table
select * from emp minus select * from emp where rownum <= (select count(*) - &n from emp);
List dept no., Dept name for all the departments in which there are no employees in the
department.
select * from dept where deptno not in (select deptno from emp);
alternate solution: select * from dept a where not exists (select * from emp b where [Link] =
[Link]);
altertnate solution: select empno,ename,[Link],dname from emp a, dept b where [Link](+)
= [Link] and empno is null;
How to get 3 Max salaries ?
select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where [Link] <=
[Link]) order by [Link] desc;
How to get 3 Min salaries ?
select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where [Link] >=
[Link]);
How to get nth max salaries ?
select distinct hiredate from emp a where &n = (select count(distinct sal) from emp b where [Link]
>= [Link]);
Select DISTINCT RECORDS from emp table.
select * from emp a where rowid = (select max(rowid) from emp b where [Link]=[Link]);
How to delete duplicate rows in a table?
delete from emp a where rowid != (select max(rowid) from emp b where [Link]=[Link]);
Count of number of employees in department wise.
select count(EMPNO), [Link], dname from emp a, dept b where [Link](+)=[Link] group
by [Link],dname;
Suppose there is annual salary information provided by emp table. How to fetch monthly salary of
each and every employee?
select ename,sal/12 as monthlysal from emp;
Select all record from emp table where deptno =10 or 40.
select * from emp where deptno=30 or deptno=10;
Select all record from emp table where deptno=30 and sal>1500.
select * from emp where deptno=30 and sal>1500;
Select all record from emp where job not in SALESMAN or CLERK.
select * from emp where job not in ('SALESMAN','CLERK');
Select all record from emp where ename in 'BLAKE','SCOTT','KING'and'FORD'.
select * from emp where ename in('JONES','BLAKE','SCOTT','KING','FORD');
Select all records where ename starts with ‘S’ and its lenth is 6 char.
select * from emp where ename like'S____';
Select all records where ename may be any no of character but it should end with ‘R’.
select * from emp where ename like'%R';
Count MGR and their salary in emp table.
select count(MGR),count(sal) from emp;
In emp table add comm+sal as total sal .
select ename,(sal+nvl(comm,0)) as totalsal from emp;
Select any salary <3000 from emp table.
select * from emp where sal> any(select sal from emp where sal<3000);
Select all salary <3000 from emp table.
select * from emp where sal> all(select sal from emp where sal<3000);
Select all the employee group by deptno and sal in descending order.
select ename,deptno,sal from emp order by deptno,sal desc;
How can I create an empty table emp1 with same structure as emp?
Create table emp1 as select * from emp where 1=2;
How to retrive record where sal between 1000 to 2000?
Select * from emp where sal>=1000 And sal<2000
Select all records where dept no of both emp and dept table matches.
select * from emp where exists(select * from dept where [Link]=[Link])
If there are two tables emp1 and emp2, and both have common record. How can I fetch all the
recods but common records only once?
(Select * from emp) Union (Select * from emp1)
How to fetch only common records from two tables emp and emp1?
(Select * from emp) Intersect (Select * from emp1)
How can I retrive all records of emp1 those should not present in emp2?
(Select * from emp) Minus (Select * from emp1)
Count the totalsa deptno wise where more than 2 employees exist.
SELECT deptno,sum(sal)As totalsal FROM emp GROUP BY deptno HAVING COUNT(empno) > 2
Set Operators
Set operators basically combine the result of two queries into one
These queries are known as compound queries.
These are the set operater.
UNION: Returns all rows from either queries; no duplicate rows.
UNION ALL: Returns all rows from either query, including duplicates.
INTERSETCT: Returns distinct rows that are returned by both queries.
MINUS: Returns distinct rows that are returned by the first query but not returned by the second.
Joins
SQL joins are used to fetch data from two or more tables, based on conditions between tables.
There are various type of joins. Like
Equi-Joins
Self-Join
Outer-Join
Semi-Join
Anti-Join
Cross-Join
Equi-join
It is a sql join where we use the equal sign as the comparison operator i.e "=" between two
[Link] default this join is inner-equi-join.
Example1: Suppose we want to fetch records from two tables emp, dept where deptno of
employee is equal to dept no of dept.
The query is:
SELECT * FROM EMP E,DEPT D WHERE [Link]=[Link];
Another way to write it,like
SELECT * FROM EMP E INNER JOIN DEPT ON D WHERE [Link]=[Link];
Non-Equi Join:
A Non- Equi Join is a SQL Join where condition is established between table using all comparison
operators (>=, <=, <, >) can used except the equal (=) .
Example1: Suppose there are two tables Employee and Salary_Grade.Salary_Grade contains
lowsal,[Link] want to fetch all records where sal of employees less than lowsal.
SELECT * FROM EMPLOYEE E, SALARY_GRADE SD WHERE [Link]<=[Link].
Example2: There are two table emp and dept. We want to fetch records of emp where deptno
between 10 and 20.
SELECT * FROM EMP E, DEPT D WHERE [Link] BETWEEN 10 AND 20;
Self Joins:
A self means joining columns of a table to itself. It fetches record from same table only and for
that we have to mention table alias name twice times.
Example1: In Emp table there are two columns empno and mgr. Fetch the records where empno
and mgr are same.
SELECT * FROM EMP E1, EMP E2 WHERE [Link]=[Link]
Retrieve the records from Emp table whose jobs are sam
SELECT * FROM EMP E1,EMP E2 WHERE [Link]=[Link];
Outer-Join
Outer join returns all records from one table and those records from another table where meets joining condition.
There are three types of outer joins
=>Left Outer-join
=>Right outer-join
=>Full outer-join
Left Outer-join
In Left Outer-Join retrieves the unmatched rows and matched from the left (1st)table and only matched rows from
right(2nd) table.
The result of a left outer join for table A and B always contains all records of the Left table (A), even if the condition
does not match with record in the Right table (B). This means
that a left outer join returns all the values from the left table, plus matched values from the Right table or returns
NULL in case of no matching join condition satisfied.
Example Select an employee's department where they have not been assigned to a department
SELECT * FROM EMP LEFT OUTER JOIN DEPT ON [Link]=[Link];
or
SELECT * FROM EMP,DEPT WHERE [Link]=[Link](+);
Right Outer-join
In Right Outer-Join retrieves the unmatched rows and matched from the Right table and only matched rows from
Left table.
The result of a Right outer join for table A and B always contains all records of the
Right table (B), even if the condition does not match with record in the Left table (A).
This means that a Right outer join returns all the values from the Right table, plus matched values from the Left
table or returns NULL in case of no matching join condition satisfied.
Example List dept no., Dept name for all the departments in which there are no
employees in the department.
SELECT * FROM EMP RIGHT OUTER JOIN DEPT ON [Link]=[Link]
OR
SELECT * FROM EMP,DEPT [Link](+)=[Link]
Full Outer-join
Full Outer-join is combination of left and right outer [Link] returns both match and unmatched row from both tables.
Example Retrieve each employee who is in a department and each department that has an employee and also
each employee who is not part of a department and each department which doesn't have an employee.
SELECT * FROM EMP FULL OUTER JOIN DEPT ON [Link]=[Link]
OR
SELECT * FROM EMP,DEPT [Link](+)=[Link](+)
Anti Join
Suppose there are two tables A and B Anti-join between two tables A AND B returns rows from the
table A, for which there are no corresponding rows in the Table B. Anti-join is also a sub-query in
which parent query doesn't depend upon child query. Example1:List deptno. Dept name for all the
departments in which there are no employees in the department.
?
SELECT * FROM DEPT D WHERE NOT EXIST (SELECT * FROM EMP E WHERE [Link] = [Link])
Example2:There are two tables Emp1 and Emp2. Fetch the record those are present in Emp1 not in
Emp2
?
SELECT * FROM EMP1 MINUS SELECT * FROM EMP2
Semi Join
Semi-join between two tables returns rows from table A ,where one or more matches are found in
table [Link] is kown as Co-Related-Sub-query, Where parent query depents upon Child query.
Example1:There are two tables Emp1 and Emp2. Fetch the record common in Emp1 and emp2.
SELECT * FROM EMP1 INTERSECT SELECT * FROM EMP2
Example2:Select records from emp and Dept where Deptno of Emp matches Deptno in Dept
SELECT * FROM EMP WHERE [Link] IN(SELECT DEPTNO FROM DEPT)
Cross Join
Cross join jenerally generate cross product between two table. Each row of Table1 ,combined with
each rows of Table2.
Example Generate cross join between Emp and Dept
SELECT * FROM EMP CROSS JOIN DEPT;
or
SELECT * FROM EMP,DEPT;
Sql Functions
Aggregate functions
Aggregate functions return a single result row based on groups of rows, rather than on
single rows.
Aggregate functions can appear in select lists and in ORDER BY and HAVING clauses.
They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle divides
the rows of a queried table or view into groups.
All aggregate functions except COUNT(*)and GROUPING ignore nulls.
These are Aggregate functions
SUM()
SELECT SUM(salary) as Sum_Sal FROM emp;
AVG()
SELECT AVG(salary) as Avg_Sal FROM emp;
Max()
MAX returns maximum value of expression.
SELECT Max(salary) as Max_Sal FROM emp;
Min()
Min returns minimum value of expression.
SELECT Min(salary) as Min_Sal FROM emp;
Count()
Count returns the number of rows in the query.
SELECT COUNT(*) as total_rec FROM emp;
Example of Aggregate Function using GROUP BY:
To return the minimum and maximum salaries for each department in the emp table,we can
use:group by clause
SELECT department_id,MIN(salary),MAX(salary)
FROM emp
GROUP BY dept_id;
To return the minimum and maximum salaries for each department in the emp table where
minimum salary should be more than 5000
SELECT department_id, MIN(salary), MAX (salary)
FROM emp
WHERE MIN(salary) > 5000
GROUP BY dept_id;
Character Functions
It calculates the ASCII equivalent of the first character of the given input string.
ASCII(<Character>)
ascii('A') would return 65
ascii('a') would return 97
ascii('a8') would return 97
CHR(<Character>)
Returns the character equivalent of the given integer.
Example
SELECT CHR(65), CHR(97) FROM dual;
O/P A a
CONCAT(<string1>,<string2>)
This function returns String2 appended to String1.
Example:
SELECT CONCAT('Fname', 'Lname') Emp_name FROM emp;
INITCAP(<String>)
This function returns String with the first character of each word in upper case and rest of all in
lower case.
Example:
SELECT INITCAP('oracle tutorial') FROM Dual;
O/p Oracle Tutorial
instr( string1, string2 [, start_position [, nth_Appearance ] ] ):
string1 is the string to search.
string2 is the substring to search for in string1.
start_position is the position in string1 from where the search will start. This argument is optional.
If not mentioned, it defaults to 1.
The first position in the string is 1. If the start_position is negative, the function counts backward
direction
nth_appearance is the nth appearance of string2. This is optional. If not defined, it defaults to 1.
Example
SELECT INSTR('Character','r',1,1) POS1
, INSTR('Character','r',1,2) POS2
, INSTR('Character','a',-1,2) POS3
,INSTR('character','c',) POS4
FROM Dual;
pos1 pos2 pos3 pos4
4 9 3 6
LENGTH(<Str>)
Returns length of a string
secect length('Sql Tutorial') as len from dual;
O/p len
12
LOWER(<Str>)
This function returns a character string with all characters in lower case.
UPPER(<Str>)
This function returns a character string with all characters in upper case.
LPAD(<Str1>,<i>[,<Str2>])
This function returns the character string Str1 expanded in length to i characters, using Str2 to fill
in space as needed on the left side of Str1.
Example
SELECT LPAD('Oracle',10,'.') lapd_doted from Dual, would return ....Oracle
SELECT LPAD('RAM', 7) lapd_exa from Dual would return ' RAM'
RPAD(<Str1>,<i>[,<Str2>])
RPAD is same as LPAD but Str2 is padded at the right side
LTRIM(<Str1>[,<Str2>])
The LTRIM function removes characters from the left side of the character Srting, with all the
leftmost characters that appear in another text expression removed.
This function returns Str1 without any leading character that appears in [Link] Str2 characters are
leading character in Str1, then Str1 is returned unchanged.
Str2 defaults to a single space.
Example
Select LTRIM('datawarehousing','ing') trim1
, LTRIM('datawarehousing ') trim2
, LTRIM(' datawarehousing') trim3
, LTRIM('datawarehousing','data') trim4 from dual
O/P trim1 trim2 trim3 trim4
datawarehousing datawarehousing datawarehousing warehousing
RTRIM(<Str1>[,<Str2>])
Same as LTRIM but the characters are trimmed from the right side
TRIM([[<Str1>]<Str2> FROM]<Str3>)
If present Str1 can be one of the following literal: LEADING, TRAILING, BOTH.
This function returns Str3 with all C1(leading trailing or both) occurrences of characters in
Str2 removed.
If any of Str1,Str2 or Str3 is Null, this function returns a Null.
Str1 defaults to BOTH, and Str2 defaults to a space character.
Example
SELECT TRIM(' Oracle ') trim1, TRIM('Oracle ') trim2 FROM Dual;
Ans trim1 trim2
Oracle Oracle
It'll remove the space from both string.
REPLACE(<Str1>,<Str2>[,<Str3>]
This function returns Str1 with all occurrence of Str2 replaced with Str3
Example
SELECT REPLACE (‘Oracle’, ’Ora’, ’Arti’) replace_exa FROM Dual;
O/p replace_exa
Atricle
Essential Numeric Functions
ABS()
Select Absolute value
SELECT ABS(-25) "Abs" FROM DUAL;
Abs
-------
15
ACOS ()
Select cos value
SELECT ACOS(.28)"Arc_Cosine" FROM DUAL;
ASIN ()
Select sin value
SELECT ASIN(.6)"Arc_Cosine" FROM DUAL;
ATAN()
Select tan value
SELECT ATAN(.6)"Arc_Cosine" FROM DUAL;
CEIL()
Returns the smallest integer greater than or equal to the order total of a specified orde
SELECT CEIL(239.8) FROM Dual would return 240
FLOOR()
Returns the largest integer equal to or less than value.
SELECT FLOOR(15.65) "Floor" FROM DUAL;
Floor
------
15
MOD()
Return modulus value
SELECT MOD(11,3) "Mod" FROM DUAL;
Modulus
-------
2
POWER()
SELECT POWER(3,2) "Power" FROM DUAL;
power
-------
9
ROUND (number)
SELECT ROUND(43.698,1) "Round" FROM DUAL;
Round
----------
43.7
TRUNC (number)
The TRUNC (number) function returns n1 truncated to n2 decimal places. If n2 is omitted, then n1
is truncated to 0 places. n2 can be negative to truncate (make zero) n2 digits left of the decimal
point.
SELECT TRUNC(12.75,1) "Trunc" FROM DUAL;
Trunc
----------
12.75
SELECT TRUNC(12.75,-1) "Trunc" FROM DUAL;
Trunc
------
10
Date And Time Function
ADD_MONTHS(date,number_of_month)
SELECT SYSDATE, ADD_MONTHS(SYSDATE,2), ADD_MONTHS(SYSDATE,-2) FROM DUAL;
Result:
SYSDATE ADD_MONTH ADD_MONTH
------------- ------------------------------------------
10-Feb-13 10-Apr-13 10-Dec-13
EXTRACT(<type> FROM <date>)
'Type' can be YEAR, MONTH, DAY, HOUR, MIN, SECOND, TIME_ZONE_HOUR, TIME_ZONE_MINUTE,
TIME_ZONE_REGION
SELECT SYSDATE, EXTRACT(YEAR FROM SYSDATE)YEAR, EXTRACT(DAY FROM SYSDATE)DAY ,
EXTRACT(TIMEZONE_HOUR FROM SYSTIMESTAMP) TZH FROM DUAL;
LAST_DAY(<date>)
Extract last day of month
Example:
SELECT SYSDATE, LAST_DAY(SYSDATE) END_OF_MONTH FROM DUAL;
Result: SYSDATE END_OF_MO
---------- ---------------
10-Feb-13 28-Feb-13
NEXT_DAY(<date>,<day>)
SELECT NEXT_DAY('28-Feb-13','SUN') "FIRST MONDAY OF MARCH” FROM DUAL;
O/P FIRST MONDAY OF MARCH
03-Mar-13
ROUND (date[,<fmt>])
SELECT SYSDATE, ROUND(SYSDATE,'MM'), ROUND(SYSDATE,'YYYY') FROM DUAL;
Result:SYSDATE ROUND(SYS ROUND(SYS
----------- ---------------
10-FEB-13 01-MAR-13 01-JAN-13
TRUNC(date[,<fmt>])
SELECT SYSDATE, TRUNC(SYSDATE,'MM'), TRUNC(SYSDATE,'YYYY') FROM DUAL;
Result: SYSDATE TRUNC(SYS TRUNC(SYS
------- - ------------ --------
10-FEB-13 01-FEB-13 01-JAN-13
difference between Where and Having clause: Top most are pointed below:
1. Where clause can not be used with Aggregate Functions where as Having clause has been
introduced in SQL for this purpose only.
2. Where clause can be used with other than Select Statement where as Having clause can only be
used with Select Statement.
3. Where clause can be used before group by clause where as Having clause can be used after
group by clause.
Inner Join
SELECT [Link] DEPARTMENT, [Link] EMPLOYEE
FROM DEPT dept, EMPLOYEE emp
WHERE emp.dept_id = [Link]
Outer Join
SELECT [Link] DEPARTMENT, [Link] EMPLOYEE
FROM DEPT dept, EMPLOYEE emp
WHERE [Link] = emp.dept_id (+)
The above SQL can be alternatively written as below (will yield the same result as above):
SELECT [Link] DEPARTMENT, [Link] EMPLOYEE
FROM DEPT dept LEFT OUTER JOIN EMPLOYEE emp
ON [Link] = emp.dept_id
What is the difference between JOIN and UNION?
SQL JOIN allows us to “lookup” records on other table based on the given conditions between two
tables. For example, if we have the department ID of each employee, then we can use this
department ID of the employee table to join with the department ID of department table to lookup
department names.
UNION operation allows us to add 2 similar data sets to create resulting data set that contains all
the data from the source data sets. Union does not require any condition for joining. For example, if
you have 2 employee tables with same structure, you can UNION them to create one result set that
will contain all the employees from both of the tables.
SELECT * FROM EMP1
UNION
SELECT * FROM EMP2;
What is the difference between UNION and UNION ALL?
UNION and UNION ALL both unify for add two structurally similar data sets, but UNION operation
returns only the unique records from the resulting data set whereas UNION ALL will return all the
rows, even if one or more rows are duplicated to each other.
In the following example, I am choosing exactly the same employee from the emp table and
performing UNION and UNION ALL. Check the difference in the result.
SELECT * FROM EMPLOYEE WHERE ID = 5
UNION ALL
SELECT * FROM EMPLOYEE WHERE ID = 5
ID MGR_ID DEPT_ID NAME SAL DOJ
5.0 2.0 2.0 Anno 80.0 01-Feb-2012
5.0 2.0 2.0 Anno 80.0 01-Feb-2012
SELECT * FROM EMPLOYEE WHERE ID = 5
UNION
SELECT * FROM EMPLOYEE WHERE ID = 5
ID MGR_ID DEPT_ID NAME SAL DOJ
5.0 2.0 2.0 Anno 80.0 01-Feb-2012
What is the difference between WHERE clause and HAVING clause?
WHERE and HAVING both filters out records based on one or more conditions. The difference is,
WHERE clause can only be applied on a static non-aggregated column whereas we will need to use
HAVING for aggregated columns.
To understand this, consider this example.
Suppose we want to see only those departments where department ID is greater than 3. There is
no aggregation operation and the condition needs to be applied on a static field. We will use
WHERE clause here:
SELECT * FROM DEPT WHERE ID > 3
ID NAME
4 Sales
5 Logistics
Next, suppose we want to see only those Departments where Average salary is greater than 80.
Here the condition is associated with a non-static aggregated information which is “average of
salary”. We will need to use HAVING clause here:
SELECT [Link] DEPARTMENT, avg([Link]) AVG_SAL FROM DEPT dept, EMPLOYEE emp
WHERE [Link] = emp.dept_id (+) GROUP BY [Link] HAVING AVG([Link]) > 80
DEPARTMENT AVG_SAL
Engineering 90
As you see above, there is only one department (Engineering) where average salary of employees
is greater than 80.
What is the difference among UNION, MINUS and INTERSECT?
UNION combines the results from 2 tables and eliminates duplicate records from the result set.
MINUS operator when used between 2 tables, gives us all the rows from the first table except the
rows which are present in the second table.
INTERSECT operator returns us only the matching or common rows between 2 result sets.
To understand these operators, let’s see some examples. We will use two different queries to
extract data from our emp table and then we will perform UNION, MINUS and INTERSECT
operations on these two sets of data.
UNION
SELECT * FROM EMPLOYEE WHERE ID = 5 UNION SELECT * FROM EMPLOYEE WHERE ID = 6
ID MGR_ID DEPT_ID NAME SAL DOJ
5 2 2.0 Anno 80.0 01-Feb-2012
6 2 2.0 Darl 80.0 11-Feb-2012
MINUS
SELECT * FROM EMPLOYEE MINUS SELECT * FROM EMPLOYEE WHERE ID > 2
ID MGR_ID DEPT_ID NAME SAL DOJ
1 2 Hash 100.0 01-Jan-2012
2 1 2 Robo 100.0 01-Jan-2012
INTERSECT
SELECT * FROM EMPLOYEE WHERE ID IN (2, 3, 5)
INTERSECT
SELECT * FROM EMPLOYEE WHERE ID IN (1, 2, 4, 5)
ID MGR_ID DEPT_ID NAME SAL DOJ
5 2 2 Anno 80.0 01-Feb-2012
2 1 2 Robo 100.0 01-Jan-2012
What is Self Join and why is it required?
Self Join is the act of joining one table with itself.
Self Join is often very useful to convert a hierarchical structure into a flat structure In our employee
table example above, we have kept the manager ID of each employee in the same row as that of
the employee. This is an example of how a hierarchy (in this case employee-manager hierarchy) is
stored in the RDBMS table. Now, suppose if we need to print out the names of the manager of each
employee right beside the employee, we can use self join. See the example below:
SELECT [Link] EMPLOYEE, [Link] MANAGER FROM EMPLOYEE e, EMPLOYEE m
WHERE e.mgr_id = [Link] (+)
How can we transpose a table using SQL (changing rows to column or vice-versa) ?
The usual way to do it in SQL is to use CASE statement or DECODE statement.
How to generate row number in SQL Without ROWNUM
Generating a row number – that is a running sequence of numbers for each row is not easy using
plain SQL. In fact, the method I am going to show below is not very generic either. This method
only works if there is at least one unique column in the table. This method will also work if there is
no single unique column, but collection of columns that is unique. Anyway, here is the query:
SELECT name, sal, (SELECT COUNT(*) FROM EMPLOYEE i WHERE [Link] >= [Link])
row_numFROM EMPLOYEE oorder by row_num
How to select first 5 records from a table?
In Oracle,
SELECT * FROM EMP WHERE ROWNUM <= 5;
In SQL Server,
SELECT TOP 5 * FROM EMP;
What is the difference between ROWNUM pseudo column and ROW_NUMBER() function?
ROWNUM is a pseudo column present in Oracle database returned result set prior to ORDER BY
being evaluated. So ORDER BY ROWNUM does not work.
ROW_NUMBER() is an analytical function which is used in conjunction to OVER() clause wherein we
can specify ORDER BY and also PARTITION BY columns.
Suppose if you want to generate the row numbers in the order of ascending employee salaries for
example, ROWNUM will not work. But you may use ROW_NUMBER() OVER() like shown below:
SELECT name, sal, row_number() over(order by sal desc) rownum_by_sal
FROM EMPLOYEE o
What are the differences among ROWNUM, RANK and DENSE_RANK?
ROW_NUMBER assigns contiguous, unique numbers from 1.. N to a result set.
RANK does not assign unique numbers—nor does it assign contiguous numbers. If two records tie
for second place, no record will be assigned the 3rd rank as no one came in third, according to
RANK. See below:
SELECT name, sal, rank() over(order by sal desc) rank_by_sal
FROM EMPLOYEE o
DENSE_RANK, like RANK, does not assign unique numbers, but it does assign contiguous numbers.
Even though two records tied for second place, there is a third-place record. See below:
SELECT name, sal, dense_rank() over(order by sal desc) dense_rank_by_sal
FROM EMPLOYEE o
What is the difference between “Stored Procedure” and “Function”?
1. A procedure can have both input and output parameters, but a function can only have
input parameters.
2. Inside a procedure we can use DML (INSERT/UPDATE/DELETE) statements. But inside a
function we can't use DML statements.
3. We can't utilize a Stored Procedure in a Select statement. But we can use a function in a
Select statement.
4. We can use a Try-Catch Block in a Stored Procedure but inside a function we can't use a
Try-Catch block.
5. We can use transaction management in a procedure but we can't in a function.
6. We can't join a Stored Procedure but we can join functions.
7. Stored Procedures cannot be used in the SQL statements anywhere in the
WHERE/HAVING/SELECT section. But we can use a function anywhere.
8. A procedure can return 0 or n values (max 1024). But a function can return only 1 value
that is mandatory.
9. A procedure can't be called from a function but we can call a function from a procedure.
What is difference between “Clustered Index” and “Non Clustered Index”?
1. A Clustered Index physically stores the data of the table in the order of the keys values and
the data is resorted every time whenever a new value is inserted or a value is updated in
the column on which it is defined, whereas a non-clustered index creates a separate list of
key values (or creates a table of pointers) that points towards the location of the data in
the data pages.
2. A Clustered Index requires no separate storage than the table storage. It forces the rows to
be stored sorted on the index key whereas a non-clustered index requires separate storage
than the table storage to store the index information.
3. A table with a Clustered Index is called a Clustered Table. Its rows are stored in a B-Tree
structure sorted whereas a table without any clustered indexes is called a non-clustered
table. Its rows are stored in a heap structure unsorted.
4. The default index is created as part of the primary key column as a Clustered Index.
5. In a Clustered Index, the leaf node contains the actual data whereas in a non-clustered
index, the leaf node contains the pointer to the data rows of the table.
6. A Clustered Index always has an Index Id of 1 whereas non-clustered indexes have Index
Ids > 1.
7. A Table can have only 1 Clustered Index whereas prior to SQL Server 2008 only 249 non-
clustered indexes can be created. With SQL Server 2008 and above 999 non-clustered
indexes can be created.
8. A Primary Key constraint creates a Clustered Index by default whereas A Unique Key
constraint creates a non-clustered index by default.
What is the difference between the “DELETE” and “TRUNCATE” commands?
1. The DELETE command is used to remove rows from a table based on a WHERE condition
whereas TRUNCATE removes all rows from a table.
2. So we can use a where clause with DELETE to filter and delete specific records whereas we
cannot use a Where clause with TRUNCATE.
3. DELETE is executed using a row lock, each row in the table is locked for deletion whereas
TRUNCATE is executed using a table lock and the entire table is locked for removal of all
records.
4. DELETE is a DML command whereas TRUNCATE is a DDL command.
5. DELETE retains the identity of the column value whereas in TRUNCATE, the Identify column
is reset to its seed value if the table contains any identity column.
6. To use Delete you need DELETE permission on the table whereas to use Truncate on a
table you need at least ALTER permission on the table.
7. DELETE uses more transaction space than the TRUNCATE statement whereas Truncate
uses less transaction space than DELETE statement.
8. DELETE can be used with indexed views whereas TRUNCATE cannot be used with indexed
views.
9. The DELETE statement removes rows one at a time and records an entry in the transaction
log for each deleted row whereas TRUNCATE TABLE removes the data by deallocating the
data pages used to store the table data and records only the page deallocations in the
transaction log.
10. Delete activates a trigger because the operation is logged individually whereas TRUNCATE
TABLE can't activate a trigger because the operation does not log individual row deletions.
What is the difference between the “WHERE” clause and the “HAVING” clause?
1. WHERE clause can be used with a Select, Update and Delete Statement Clause but the
HAVING clause can be used only with a Select statement.
2. We can't use an aggregate functions in the WHERE clause unless it is in a sub-query
contained in a HAVING clause whereas we can use an aggregate function in the HAVING
clause. We can use a column name in the HAVING clause but the column must be
contained in the group by clause.
3. WHERE is used before the GROUP BY clause whereas a HAVING clause is used to impose a
condition on the GROUP Function and is used after the GROUP BY clause in the query.
4. A WHERE clause applies to each and every row whereas a HAVING clause applies to
summarized rows (summarized with GROUP BY).
5. In the WHERE clause the data that is fetched from memory depending on a condition
whereas in HAVING the completed data is first fetched and then separated depending on
the condition.
What is the difference between “Primary Key” and “Unique Key”?
1. We can have only one Primary Key in a table whereas we can have more than one Unique
Key in a table.
2. The Primary Key cannot have a NULL value whereas a Unique Key may have only one null
value.
3. By default, a Primary Key is a Clustered Index whereas by default, a Unique Key is a unique
non-clustered index.
4. A Primary Key supports an Auto Increment value whereas a Unique Key doesn't support an
Auto Increment value.
Oracle Age calculation from Date of birth and Today
select trunc(months_between(sysdate,dob)/12) year,
trunc(mod(months_between(sysdate,dob),12)) month,
trunc(sysdate-add_months(dob,trunc(months_between(sysdate,dob)/12)*12+trunc(mod(months_b
etween(sysdate,dob),12)))) day
from (Select to_date('28052013','DDMMYYYY') dob from dual);
YEAR MONTH DAY
---------- ---------- ----------
1 1 0
2) select trunc(sysdate) as today,
floor(months_between(trunc(sysdate),hiredate)/12)
as age from emp;
select trunc(months_between(sysdate,hiredate)/12) as age from emp
SQL Query to fetch data from the last 30 days?
SELECT productid FROM product WHERE purchase_date > sysdate-30
24. Get employee details from employee table whose first name ends with 'n' and name contains 4
letters
Select * from EMPLOYEE where FIRST_NAME like '___n' (Underscores)
25. Get employee details from employee table whose first name starts with 'J' and name contains 4
letters
Select * from EMPLOYEE where FIRST_NAME like 'J___' (Underscores)
Get employee details from employee table whose joining year is “2013”
Select * from EMPLOYEE where to_char(joining_date,'YYYY') = '2013'
Get employee details from employee table whose joining month is “January”
SQL Queries in Oracle, Select * from EMPLOYEE where to_char(joining_date,'MM') = '01' or Select *
from EMPLOYEE where to_char(joining_date,'Mon') = 'Jan'
Get employee details from employee table who joined before January 1st 2013
SQL Queries in Oracle, Select * from EMPLOYEE where JOINING_DATE <
to_date('01/01/2013','dd/mm/yyyy')
Get employee details from employee table who joined after January 31st
SQL Queries in Oracle, Select * from EMPLOYEE where JOINING_DATE >
to_date('31/01/2013','dd/mm/yyyy')
Get Joining Date and Time from employee table
SQL Queries in Oracle, select to_char(JOINING_DATE,'dd/mm/yyyy hh:mi:ss') from EMPLOYEE
72. Write syntax to delete table employee
DROP table employee;
73. Write syntax to set EMPLOYEE_ID as primary key in employee table
ALTER TABLE EMPLOYEE add CONSTRAINT EMPLOYEE_PK PRIMARY KEY(EMPLOYEE_ID)
74. Write syntax to set 2 fields(EMPLOYEE_ID,FIRST_NAME) as primary key in employee
table
ALTER TABLE EMPLOYEE add CONSTRAINT EMPLOYEE_PK PRIMARY
KEY(EMPLOYEE_ID,FIRST_NAME)
75. Write syntax to drop primary key on employee table
Alter TABLE EMPLOYEE drop CONSTRAINT EMPLOYEE_PK;
76. Write Sql Syntax to create EMPLOYEE_REF_ID in INCENTIVES table as foreign key
with respect to EMPLOYEE_ID in employee table
ALTER TABLE INCENTIVES ADD CONSTRAINT INCENTIVES_FK FOREIGN KEY (EMPLOYEE_REF_ID)
REFERENCES EMPLOYEE(EMPLOYEE_ID)
77. Write SQL to drop foreign key on employee table
ALTER TABLE INCENTIVES drop CONSTRAINT INCENTIVES_FK;
78. Write SQL to create Orcale Sequence
CREATE SEQUENCE EMPLOYEE_ID_SEQ START WITH 0 NOMAXVALUE MINVALUE 0 NOCYCLE
NOCACHE NOORDER;
83. Oracle materialized view - Fast Refresh on Commit
Create materialized view log for fast refresh. Following materialized view script wont get executed
if materialized view log doesn't exists
84. What is SQL Injection ?
SQL Injection is one of the the techniques uses by hackers to hack a website by injecting SQL
commands in data fields.
Select employee details from employee table if data exists in incentive table ?
select * from EMPLOYEE where exists (select * from INCENTIVES)
Explanation : Here exists statement helps us to do the job of If statement. Main query will get
executed if the sub query returns at least one row. So we can consider the sub query as "If
condition" and the main query as "code block" inside the If condition. We can use any SQL
commands (Joins, Group By , having etc) in sub query. This command will be useful in queries
which need to detect an event and do some activity.
How to fetch data that are common in two query results ?
select * from EMPLOYEE where EMPLOYEE_ID INTERSECT select * from EMPLOYEE where
EMPLOYEE_ID < 4
Get Employee ID's of those employees who didn't receive incentives without using sub
query ?
select EMPLOYEE_ID from EMPLOYEE
MINUS
select EMPLOYEE_REF_ID from INCENTIVES
Select Banking as 'Bank Dept', Insurance as 'Insurance Dept' and Services as 'Services
Dept' from employee table
SQL Queries in Oracle, SELECT distinct DECODE (DEPARTMENT, 'Banking', 'Bank Dept', 'Insurance',
'Insurance Dept', 'Services', 'Services Dept') FROM EMPLOYEE
Write a query to rank employees based on their incentives for a month
select FIRST_NAME,INCENTIVE_AMOUNT,DENSE_RANK() OVER (PARTITION BY INCENTIVE_DATE
ORDER BY INCENTIVE_AMOUNT DESC) AS Rank from EMPLOYEE a, INCENTIVES b where
a.EMPLOYEE_ID = b.EMPLOYEE_REF_ID
Explanation : Here in order to rank employees based on their rank for a month, DENSE_RANK
keyword is used. Here partition by keyword helps us to sort the column with which filtering is done.
Rank is provided to the column specified in the order by statement. The above query ranks
employees with respect to their incentives for a given month.
Select no of employees joined with respect to year and month from employee table
SQL Queries in Oracle, select to_char (JOINING_DATE,'YYYY') Join_Year,to_char
(JOINING_DATE,'MM') Join_Month,count(*) Total_Emp from employee group by to_char
(JOINING_DATE,'YYYY'),to_char(JOINING_DATE,'MM')
Get department wise minimum salary from employee table order by salary ascending
select DEPARTMENT,min(SALARY) MinSalary from employee group by DEPARTMENT order by
MinSalary asc
Get department,no of employees in a department,total salary with respect to a
department from employee table order by total salary descending
Select DEPARTMENT,count(FIRST_NAME),sum(SALARY) Total_Salary from employee group by
DEPARTMENT order by Total_Salary descending
Get Last Name from employee table after replacing special character with white space
SQL Queries in Oracle, Select translate(LAST_NAME,'%',' ') from employee
Get department,no of employees in a department,total salary with respect to a
department from employee table order by total salary descending
Select DEPARTMENT,count(FIRST_NAME),sum(SALARY) Total_Salary from employee group by
DEPARTMENT order by Total_Salary descending
Select Nth Highest salary from employee table
SQL Queries in Oracle, select min(salary) from (select * from (select * from employee order by
SALARY desc) where rownum < N + 1)
Select 2nd Highest salary from employee table
SQL Queries in Oracle, select min(salary) from (select * from (select * from employee order by
SALARY desc) where rownum < 3)
Select TOP N salary from employee table
SQL Queries in Oracle, select * from (select * from employee order by SALARY desc) where
rownum < N + 1
Select TOP 2 salary from employee table
SQL Queries in Oracle, select * from (select * from employee order by SALARY desc) where
rownum < 3
2. How to search for strings containing ‘%’ in Oracle? Search for columns containing ‘%’
in Oracle.
In ORACLE , you can use the ESCAPE keyword to search for strings containing ‘%’. Otherwise it
would be considered as a META CHARACTER .
Using the escape character ( to search for strings containing like ‘ABC %%TRF’, ‘TR%FF’ or ‘%GH’)
Answer :
SELECT col_name FROM tbl_name
WHERE col_name LIKE '%?%%' ESCAPE '?';
Here ‘?’ can be replaced with any other character.
Another solution:
SELECT col_name FROM tbl_name
WHERE instr(col_name,'%') > 0
****************************************************
3. How does one remove special characters in ORACLE?
To replace special characters in a string with null use translate :
translate(‘string’,'to_replace’,'replace_with’)
for eg:
SELECT translate
('asdfsd@#@$#$%$sdfg&;','!@#$%^&;*()_+=-`~?><:/.,',' ') FROM dual;
will return—asdfsdsdfg
To remove quotes, use two quotes for every single quote as shown below:
CREATE TABLE test_quote(quote VARCHAR2(5));
INSERT INTO test_quote VALUES ('L''uck');
SELECT * FROM test_quote;
SELECT REPLACE(quote,'''','') from test_quote;
1. How can you compare a part of the name rather than the entire name?
Answer: SELECT * FROM people WHERE empname LIKE '%ab%'Would return a recordset
with records consisting empname the sequence 'ab' in empname.
1. What is GROUP BY?
Answer: The GROUP BY keywords have been added to SQL because aggregate functions
(like SUM) return the aggregate of all column values every time they are [Link] the
GROUP BY functionality, finding the sum for each individual group of column values was
not possible.
2. What is the difference among "dropping a table", "truncating a table" and
"deleting all records" from a table.
Answer: Dropping : (Table structure + Data are deleted), Invalidates the dependent objects
,Drops the indexes Truncating: (Data alone deleted), Performs an automatic commit, Faster
than deleteDelete : (Data alone deleted), Doesn't perform automatic commit
11. What are the Large object types suported by Oracle?
Answer: Blob and Clob.
12. Difference between a "where" clause and a "having" clause.
Answer: Having clause is used only with group functions whereas Where is not used with.
13. What's the difference between a primary key and a unique key?
Answer: Both primary key and unique enforce uniqueness of the column on which they are
[Link] by default primary key creates a clustered index on the column, where are
unique creates a nonclustered index by [Link] major difference is that, primary
key doesn't allow NULLs, but unique key allows one NULL only.
14. What are cursors? Explain different types of [Link] are the disadvantages
of cursors? How can you avoid cursors?
Answer: Cursors allow row-by-row prcessing of the [Link] of cursors: Static,
Dynamic, Forward-only, [Link] books online for more
[Link] of cursors: Each time you fetch a row from the cursor, it results
in a network roundtrip, where as a normal SELECT query makes only one rowundtrip,
however large the resultset [Link] are also costly because they require more resources
and temporary storage (results in more IO operations).Furthere, there are restrictions on
the SELECT statements that can be used with some types of [Link] of the times, set
based operations can be used instead of cursors.
15. What are triggers? How to invoke a trigger on demand?
Answer: Triggers are special kind of stored procedures that get executed automatically
when an INSERT, UPDATE or DELETE operation takes place on a [Link] can't be
invoked on [Link] get triggered only when an associated action (INSERT, UPDATE,
DELETE) happens on the table on which they are [Link] are generally used to
implement business rules, [Link] can also be used to extend the referential
integrity checks, but wherever possible, use constraints for this purpose, instead of
triggers, as constraints are much faster.
16. What is a join and explain different types of joins.
Answer: Joins are used in queries to explain how different tables are [Link] also let
you select data from a table depending upon data from another [Link] of joins: INNER
JOINs, OUTER JOINs, CROSS [Link] JOINs are further classified as LEFT OUTER JOINS,
RIGHT OUTER JOINS and FULL OUTER JOINS.
17. What is a self join?
Answer: Self join is just like any other join, except that two instances of the same table will
be joined in the query.
18. How can I eliminate duplicates values in a table?
Answer: SQL> DELETE FROM table_name A WHERE ROWID > (SELECT min(rowid) FROM
table_name B WHERE A.key_values = B.key_values);
19. How can I change my Oracle password?
Answer: From SQL*Plus type: ALTER USER username IDENTIFIED BY new_password
21. What are the most important DDL statements in SQL?
Answer: The most important DDL statements in SQL are:
create table-creates a new database table
alter table-alters (changes) a database table
drop table-deletes a database table
create index-creates an index (search key)
drop index-deletes an index
22. What are the different SELECT statements?
Answer: The SELECT statements are:
SELECT column_name(s) FROM table_nameSELECT DISTINCT column_name(s)
FROM table_name
SELECT column FROM table WHERE column operator value
SELECT column FROM table WHERE column LIKE pattern
SELECT column,SUM(column) FROM table GROUP BY column
SELECT column,SUM(column) FROM table GROUP BY column HAVING SUM(column)
condition value
23. What are the INSERT INTO Statements?
Answer: The INSERT INTO statements are:
INSERT INTO table_name VALUES (value1, value2,....)
INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)
24. Write theUpdate Statement?
Answer: UPDATE table_name SET column_name = new_value WHERE column_name =
some_value
25. What are the Delete Statements?
Answer: These are:
DELETE FROM table_name WHERE column_name = some_value
Delete All Rows:
DELETE FROM table_name
DELETE * FROM table_name
26. how we can sort the Rows?
Answer: There are mainly three types:
SELECT column1, column2,...FROM table_name ORDER BY columnX, columnY,..
SELECT column1, column2,...FROM table_name ORDER BY columnX DESC
SELECT column1, column2,...FROM table_name ORDER BY columnX DESC, columnY
ASC
27. Explain IN operator.
Answer: The IN operator may be used if you know the exact value you want to return for at
least one of the columns.
SELECT column_name FROM table_name WHERE column_name IN (value1,value2,..)
28. Explain BETWEEN...AND
Answer: SELECT column_name FROM table_name WHERE column_name BETWEEN value1
AND value2 The values can be numbers, text, or dates.
Table Name : Employee
EMPLOYEE_ID FIRST_NAME LAST_NAME SALARY JOINING_DATE DEPARTMENT
1 John Abraham 1000000 01-JAN-13 12.00.00 AM Banking
2 Michael Clarke 800000 01-JAN-13 12.00.00 AM Insurance
3 Roy Thomas 700000 01-FEB-13 12.00.00 AM Banking
4 Tom Jose 600000 01-FEB-13 12.00.00 AM Insurance
5 Jerry Pinto 650000 01-FEB-13 12.00.00 AM Insurance
6 Philip Mathew 750000 01-JAN-13 12.00.00 AM Services
7 TestName1 123 650000 01-JAN-13 12.00.00 AM Services
8 TestName2 Lname% 600000 01-FEB-13 12.00.00 AM Insurance
Table Name : Incentives
EMPLOYEE_REF_ID INCENTIVE_DATE INCENTIVE_AMOUNT
1 01-FEB-13 5000
2 01-FEB-13 3000
3 01-FEB-13 4000
1 01-JAN-13 4500
2 01-JAN-13 3500
SQL QUERIES INTERVIEW QUESTIONS AND ANSWERS ON "SQL SELECT" - EXAMPLES
1. Get all employee details from the employee table
Select * from employee
2. Get First_Name,Last_Name from employee table
Select first_name, Last_Name from employee
3. Get First_Name from employee table using alias name “Employee Name”
Select first_name Employee Name from employee
4. Get First_Name from employee table in upper case
Select upper(FIRST_NAME) from EMPLOYEE
5. Get First_Name from employee table in lower case
Select lower(FIRST_NAME) from EMPLOYEE
6. Get unique DEPARTMENT from employee table
select distinct DEPARTMENT from EMPLOYEE
7. Select first 3 characters of FIRST_NAME from EMPLOYEE
Oracle Equivalent of SQL Server SUBSTRING is SUBSTR, Query : select
substr(FIRST_NAME,0,3) from employee
8. Get position of 'o' in name 'John' from employee table
Oracle Equivalent of SQL Server CHARINDEX is INSTR, Query : Select instr(FIRST_NAME,'o')
from employee where first_name = 'John'
9. Get FIRST_NAME from employee table after removing white spaces from right side
select RTRIM(FIRST_NAME) from employee
10. Get FIRST_NAME from employee table after removing white spaces from left side
select LTRIM(FIRST_NAME) from employee
11. Get length of FIRST_NAME from employee table
Query :select length(FIRST_NAME) from employee
12. Get First_Name from employee table after replacing 'o' with '$'
select REPLACE(FIRST_NAME,'o','$') from employee
13. Get First_Name and Last_Name as single column from employee table separated by a
'_'
Oracle Equivalent of MySQL concat is '||', Query : Select FIRST_NAME|| '_' ||LAST_NAME from
EMPLOYEE
14. Get FIRST_NAME ,Joining year,Joining Month and Joining Date from employee table
SQL Queries in Oracle, Select FIRST_NAME, to_char(joining_date,'YYYY') JoinYear ,
to_char(joining_date,'Mon'), to_char(joining_date,'dd') from EMPLOYEE
15. Get all employee details from the employee table order by First_Name Ascending
Select * from employee order by FIRST_NAME asc
16. Get all employee details from the employee table order by First_Name descending
Select * from employee order by FIRST_NAME desc
17. Get all employee details from the employee table order by First_Name Ascending
and Salary descending
Select * from employee order by FIRST_NAME asc,SALARY desc
18. Get employee details from employee table whose employee name is “John”
Select * from EMPLOYEE where FIRST_NAME = 'John'
19. Get employee details from employee table whose employee name are “John” and
“Roy”
Select * from EMPLOYEE where FIRST_NAME in ('John','Roy')
20. Get employee details from employee table whose employee name are not “John”
and “Roy”
Select * from EMPLOYEE where FIRST_NAME not in ('John','Roy')
21. Get employee details from employee table whose first name starts with 'J'
Select * from EMPLOYEE where FIRST_NAME like 'J%'
22. Get employee details from employee table whose first name contains 'o'
Select * from EMPLOYEE where FIRST_NAME like '%o%'
23. Get employee details from employee table whose first name ends with 'n'
Select * from EMPLOYEE where FIRST_NAME like '%n'
24. Get employee details from employee table whose first name ends with 'n' and name
contains 4 letters
Select * from EMPLOYEE where FIRST_NAME like '___n' (Underscores)
25. Get employee details from employee table whose first name starts with 'J' and name
contains 4 letters
Select * from EMPLOYEE where FIRST_NAME like 'J___' (Underscores)
26. Get employee details from employee table whose Salary greater than 600000
Select * from EMPLOYEE where Salary > 600000
27. Get employee details from employee table whose Salary less than 800000
Select * from EMPLOYEE where Salary < 800000
28. Get employee details from employee table whose Salary between 500000 and
800000
Select * from EMPLOYEE where Salary between 500000 and 800000
29. Get employee details from employee table whose name is 'John' and 'Michael'
Select * from EMPLOYEE where FIRST_NAME in ('John','Michael')
30. Get employee details from employee table whose joining year is “2013”
Select * from EMPLOYEE where to_char(joining_date,'YYYY') = '2013'
31. Get employee details from employee table whose joining month is “January”
Select * from EMPLOYEE where to_char(joining_date,'MM') = '01'
or
Select * from EMPLOYEE where to_char(joining_date,'Mon') = 'Jan'
32. Get employee details from employee table who joined before January 1st 2013
Select * from EMPLOYEE where JOINING_DATE < to_date('01/01/2013','dd/mm/yyyy')
33. Get employee details from employee table who joined after January 31st
Select * from EMPLOYEE where JOINING_DATE > to_date('31/01/2013','dd/mm/yyyy')
35. Get Joining Date and Time from employee table
select to_char(JOINING_DATE,'dd/mm/yyyy hh:mi:ss') from EMPLOYEE
36. Get Joining Date,Time including milliseconds from employee table
select to_char(JOINING_DATE,'dd/mm/yyyy HH:mi:[Link]') from EMPLOYEE . Column Data Type
should be “TimeStamp”
37. Get difference between JOINING_DATE and INCENTIVE_DATE from employee and
incentives table
Select FIRST_NAME,INCENTIVE_DATE - JOINING_DATE from employee a inner join incentives B on
A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID
38. Get database date
SQL Queries in Oracle, select sysdate from dual
Get names of employees from employee table who has '%' in Last_Name. Tip : Escape
character for special characters in a query.
SQL Queries in Oracle, Select FIRST_NAME from employee where Last_Name like '%?%%'
SQL Queries in SQL Server, Select FIRST_NAME from employee where Last_Name like '%[%]%'
SQL Queries in MySQL,Select FIRST_NAME from employee where Last_Name like '%\%%'
40. Get Last Name from employee table after replacing special character with white
space
SQL Queries in Oracle, Select translate(LAST_NAME,'%',' ') from employee
41. Get department,total salary with respect to a department from employee table.
Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by department
42. Get department,total salary with respect to a department from employee table
order by total salary descending
Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by DEPARTMENT order by
Total_Salary descending
43. Get department,no of employees in a department,total salary with respect to a
department from employee table order by total salary descending
Select DEPARTMENT,count(FIRST_NAME),sum(SALARY) Total_Salary from employee group by
DEPARTMENT order by Total_Salary descending
44. Get department wise average salary from employee table order by salary ascending
select DEPARTMENT,avg(SALARY) AvgSalary from employee group by DEPARTMENT order by
AvgSalary asc
45. Get department wise maximum salary from employee table order by
salary ascending
select DEPARTMENT,max(SALARY) MaxSalary from employee group by DEPARTMENT order by
MaxSalary asc
46. Get department wise minimum salary from employee table order by salary
ascending
select DEPARTMENT,min(SALARY) MinSalary from employee group by DEPARTMENT order by
MinSalary asc
47. Select no of employees joined with respect to year and month from employee table
SQL Queries in Oracle, select to_char (JOINING_DATE,'YYYY') Join_Year,to_char
(JOINING_DATE,'MM') Join_Month,count(*) Total_Emp from employee group by to_char
(JOINING_DATE,'YYYY'),to_char(JOINING_DATE,'MM')
48. Select department,total salary with respect to a department from employee table
where total salary greater than 800000 order by Total_Salary descending
Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by DEPARTMENT having
sum(SALARY) > 800000 order by Total_Salary desc
49. Select first_name, incentive amount from employee and incentives table for those
employees who have incentives
Select FIRST_NAME,INCENTIVE_AMOUNT from employee a inner join incentives B on
A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID
50. Select first_name, incentive amount from employee and incentives table for those
employees who have incentives and incentive amount greater than 3000
Select FIRST_NAME,INCENTIVE_AMOUNT from employee a inner join incentives B on
A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID and INCENTIVE_AMOUNT > 3000
51. Select first_name, incentive amount from employee and incentives table for all
employes even if they didn't get incentives
Select FIRST_NAME,INCENTIVE_AMOUNT from employee a left join incentives B on A.EMPLOYEE_ID
= B.EMPLOYEE_REF_ID
52. Select first_name, incentive amount from employee and incentives table for all
employees even if they didn't get incentives and set incentive amount as 0 for those
employees who didn't get incentives.
Select FIRST_NAME,nvl(INCENTIVE_AMOUNT,0) from employee a left join incentives B on
A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID
53. Select first_name, incentive amount from employee and incentives table for all
employees who got incentives using left join
Select FIRST_NAME,nvl(INCENTIVE_AMOUNT,0) from employee a right join incentives B on
A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID
54. Select max incentive with respect to employee from employee and incentives table
using sub query
select DEPARTMENT,(select nvl(max(INCENTIVE_AMOUNT),0) from INCENTIVES where
EMPLOYEE_REF_ID = EMPLOYEE_ID) Max_incentive from EMPLOYEE
55. Select TOP 2 salary from employee table
select * from (select * from employee order by SALARY desc) where rownum < 3
56. Select TOP N salary from employee table
select * from (select * from employee order by SALARY desc) where rownum < N + 1
57. Select 2nd Highest salary from employee table
select min(salary) from (select * from (select * from employee order by SALARY desc) where
rownum < 3)
58. Select Nth Highest salary from employee table
select min(salary) from (select * from (select * from employee order by SALARY desc) where
rownum < N + 1)
59. Select First_Name,LAST_NAME from employee table as separate rows
select FIRST_NAME from EMPLOYEE union select LAST_NAME from EMPLOYEE
60. What is the difference between UNION and UNION ALL ?
Both UNION and UNION ALL is used to select information from structurally similar tables. That
means corresponding columns specified in the union should have same data type. For example, in
the above query, if FIRST_NAME is DOUBLE and LAST_NAME is STRING above query wont work.
Since the data type of both the columns are VARCHAR, union is made possible. Difference
between UNION and UNION ALL is that , UNION query return only distinct values.
61. Select employee details from employee table if data exists in incentive table ?
select * from EMPLOYEE where exists (select * from INCENTIVES)
Explanation : Here exists statement helps us to do the job of If statement. Main query will get
executed if the sub query returns at least one row. So we can consider the sub query as "If
condition" and the main query as "code block" inside the If condition. We can use any SQL
commands (Joins, Group By , having etc) in sub query. This command will be useful in queries
which need to detect an event and do some activity.
62. How to fetch data that are common in two query results ?
select * from EMPLOYEE where EMPLOYEE_ID INTERSECT select * from EMPLOYEE where
EMPLOYEE_ID < 4
Explanation : Here INTERSECT command is used to fetch data that are common in 2 queries. In
this example, we had taken EMPLOYEE table in both the [Link] can apply INTERSECT
command on different tables. The result of the above query will return employee details of "ROY"
because, employee id of ROY is 3, and both query results have the information about ROY.
63. Get Employee ID's of those employees who didn't receive incentives without using
sub query ?
select EMPLOYEE_ID from EMPLOYEE
MINUS
select EMPLOYEE_REF_ID from INCENTIVES
Explanation : To filter out certain information we use MINUS command. What MINUS Command
odes is that, it returns all the results from the first query, that are not part of the second query. In
our example, first three employees received the incentives. So query will return employee id's 4 to
8.
64. Select 20 % of salary from John , 10% of Salary for Roy and for other 15 % of salary
from employee table
SELECT FIRST_NAME, CASE FIRST_NAME WHEN 'John' THEN SALARY * .2 WHEN 'Roy' THEN SALARY
* .10 ELSE SALARY * .15 END "Deduced_Amount" FROM EMPLOYEE
Explanation : Here we are using SQL CASE statement to achieve the desired results. After case
statement, we had to specify the column on which filtering is applied. In our case it is
"FIRST_NAME". And in then condition, specify the name of filter like John, Roy etc. To handle
conditions outside our filter, use else block where every one other than John and Roy enters.
65. Select Banking as 'Bank Dept', Insurance as 'Insurance Dept' and Services as
'Services Dept' from employee table
SQL Queries in Oracle, SELECT distinct DECODE (DEPARTMENT, 'Banking', 'Bank Dept', 'Insurance',
'Insurance Dept', 'Services', 'Services Dept') FROM EMPLOYEE
66. Delete employee data from employee table who got incentives in incentive table
delete from EMPLOYEE where EMPLOYEE_ID in (select EMPLOYEE_REF_ID from INCENTIVES)
Explanation : Trick about this question is that we can't delete data from a table based on some
condition in another table by joining them. Here to delete multiple entries from EMPLOYEE table,
we need to use Subquery. Entries will get deleted based on the result of Subquery.
67. Insert into employee table Last Name with " ' " (Single Quote - Special Character)
Tip - Use another single quote before special character
Insert into employee (LAST_NAME) values ('Test''')
68. Select Last Name from employee table which contain only numbers
Select * from EMPLOYEE where lower(LAST_NAME) = upper(LAST_NAME)
Explanation : Here in order to achieve the desired result, we use ASCII property of the database.
If we get results for a column using Lower and Upper commands, ASCII of both results will be same
for numbers. If there is any alphabets in the column, results will differ.
69. Write a query to rank employees based on their incentives for a month
select FIRST_NAME,INCENTIVE_AMOUNT,DENSE_RANK() OVER (PARTITION BY INCENTIVE_DATE
ORDER BY INCENTIVE_AMOUNT DESC) AS Rank from EMPLOYEE a, INCENTIVES b where
a.EMPLOYEE_ID = b.EMPLOYEE_REF_ID
Explanation : Here in order to rank employees based on their rank for a month, DENSE_RANK
keyword is used. Here partition by keyword helps us to sort the column with which filtering is
done. Rank is provided to the column specified in the order by statement. The above query ranks
employees with respect to their incentives for a given month.
70. Update incentive table where employee name is 'John'
Explanation : Here we need to join Employee and Incentive Table for updating the incentive
amount. But for update statement joining query wont work. We need to use sub query to update
the data in the incentive table. SQL Query is as shown below.
update INCENTIVES set INCENTIVE_AMOUNT = '9000' where EMPLOYEE_REF_ID =(select
EMPLOYEE_ID from EMPLOYEE where FIRST_NAME = 'John' )
71. Write create table syntax for employee table
Oracle -
CREATE TABLE EMPLOYEE (
EMPLOYEE_ID NUMBER,
FIRST_NAME VARCHAR2(20 BYTE),
LAST_NAME VARCHAR2(20 BYTE),
SALARY FLOAT(126),
JOINING_DATE TIMESTAMP (6) DEFAULT sysdate,DEPARTMENT VARCHAR2(30 BYTE) )
72. Write syntax to delete table employee
DROP table employee;
73. Write syntax to set EMPLOYEE_ID as primary key in employee table
ALTER TABLE EMPLOYEE add CONSTRAINT EMPLOYEE_PK PRIMARY KEY(EMPLOYEE_ID)
74. Write syntax to set 2 fields(EMPLOYEE_ID,FIRST_NAME) as primary key in employee
table
ALTER TABLE EMPLOYEE add CONSTRAINT EMPLOYEE_PK PRIMARY
KEY(EMPLOYEE_ID,FIRST_NAME)
75. Write syntax to drop primary key on employee table
Alter TABLE EMPLOYEE drop CONSTRAINT EMPLOYEE_PK;
76. Write Sql Syntax to create EMPLOYEE_REF_ID in INCENTIVES table as foreign key
with respect to EMPLOYEE_ID in employee table
ALTER TABLE INCENTIVES ADD CONSTRAINT INCENTIVES_FK FOREIGN KEY (EMPLOYEE_REF_ID)
REFERENCES EMPLOYEE(EMPLOYEE_ID)
77. Write SQL to drop foreign key on employee table
ALTER TABLE INCENTIVES drop CONSTRAINT INCENTIVES_FK;
78. Write SQL to create Orcale Sequence
CREATE SEQUENCE EMPLOYEE_ID_SEQ START WITH 0 NOMAXVALUE MINVALUE 0 NOCYCLE
NOCACHE NOORDER;
79. Write Sql syntax to create Oracle Trigger before insert of each row in employee
table
CREATE OR REPLACE TRIGGER EMPLOYEE_ROW_ID_TRIGGER
BEFORE INSERT ON EMPLOYEE FOR EACH ROW
DECLARE
seq_no number(12);
BEGIN
select EMPLOYEE_ID_SEQ.nextval into seq_no from dual ;
:new EMPLOYEE_ID := seq_no;
END;
SHOW ERRORS;
80. Oracle Procedure 81. Oracle View
An example oracle view script is given below
create view Employee_Incentive as select FIRST_NAME,max(INCENTIVE_AMOUNT)
INCENTIVE_AMOUNT from EMPLOYEE a, INCENTIVES b where a.EMPLOYEE_ID =
b.EMPLOYEE_REF_ID group by FIRST_NAME
82. Oracle materialized view - Daily Auto Refresh
CREATE MATERIALIZED VIEW Employee_Incentive
REFRESH COMPLETE
START WITH SYSDATE
NEXT SYSDATE + 1 AS
select FIRST_NAME,INCENTIVE_DATE,INCENTIVE_AMOUNT from EMPLOYEE a, INCENTIVES b
where a.EMPLOYEE_ID = b.EMPLOYEE_REF_ID
83. Oracle materialized view - Fast Refresh on Commit
Create materialized view log for fast refresh. Following materialized view script wont get executed
if materialized view log doesn't exists
CREATE MATERIALIZED VIEW MAT_Employee_Incentive_Refresh
BUILD IMMEDIATE
REFRESH FAST ON COMMIT AS
select FIRST_NAME,max(INCENTIVE_AMOUNT) from EMPLOYEE a, INCENTIVES b
where a.EMPLOYEE_ID = b.EMPLOYEE_REF_ID group by FIRST_NAME
84. What is SQL Injection ?
SQL Injection is one of the the techniques uses by hackers to hack a website by injecting SQL
commands in data fields.
Difference between Correlated Subquery and Subquery?
A correlated subquery is a SELECT statement nested inside another T-SQL statement, which
contains a reference to one or more columns in the outer query. Therefore, the correlated
subquery can be said to be dependent on the outer query. This is the main difference between a
correlated subquery and just a plain subquery. A plain subquery is not dependent on the outer
query, can be run independently of the outer query, and will return a result set. A correlated
subquery, since it is dependent on the outer query will return a syntax errors if it is run by itself.
A correlated subquery will be executed many times while processing the SQL statement that
contains the correlated subquery. The correlated subquery will be run once for each candidate row
selected by the outer query. The outer query columns, referenced in the correlated subquery, are
replaced with values from the candidate row prior to each execution. Depending on the results of
the execution of the correlated subquery, it will determine if the row of the outer query is returned
in the final result set.
Correlated Subquery is a sub-query that uses values from the outer query. In this case the inner
query has to be executed for every row of outer query.
Simple subquery doesn't use values from the outer query and is being calculated only once.
Views:- View can be described as virtual table which derived its data from one or more than one
table [Link] is stored in the database. It is used to implements the security mechanism .For
example, suppose there is table called Employeeinfo whose structure is given below:
Create table EmployeeInfo(EmpId int, EmpName nvarchar(200),EmpLogin nvarchar(20),
Emppassword nvarchar(20) , EmploymentDate datetime )
Now suppose that the Administrator do not want that the users have excess to the table
EmployeeInfo which contains the some critical information (Emplogin, EmpPassword etc) of the
Employees. So he can create a view which gives the empid, empname, employmentdate as the
output and give the permission for the view to the user. In this way the administrator do not need
to bother about giving the access permission for the table to the user.
The syntax for creating a View is given below:-
Create View Viewname As
Select Column1, Column2 From Tablename
Where (Condition)
Group by (Grouping Condition) having (having Condition)
Difference between Primary key and Unique key
1)There can be only one Primary key possible in a table but there can be many unique keys
possible in a table.
2)Primary key do not allow NULL values but a Unique key allow one NULL [Link] we try to insert
NULL value into the primary key, we get an error message.
Difference between Subquery, Nested Subquery and Correlated Subquery
Suppose we have a two tables Student and courses whose structure is given below:-
create table Student (Studentid int identity(1,1), Firstname nvarchar(200),Lastname nvarchar(200),
Email nvarchar(100))
create table Course (Courseid int identity(1,1), Coursename nvarchar(250),CourseAdmin int)
Select * from student
Select * from Course
Subquery:-If a sql statement contains another sql statement then the sql statement which is
inside another sql statement is called Subquery. It is also known as nested query. The Sql
Statement which contains the other sql statement is called Parent Statement.
For example, if we want to find the name of the course Admin of the course “Oracle”, then the
following subquery will be used:-
select Firstname+''+Lastname from student where studentid in (selectcourseadminid from course
where coursename ='Oracle')
Result:-
In this example, the sql
statement “select courseadminid from course wherecoursename ='Oracle'” is a subquery.
Nested Subquery:-If a Subquery contains another subquery, then the subquery inside another
subquery is called nested subquery.
Let us suppose we have another table called “StudentCourse” which contains the information,
which student is connected to which Course. The structure of the table is:-
create table StudentCourse( StudentCourseid int identity(1,1), Studentid int,Courseid int)
The Query to insert data into the table “Studentcourse” is
Insert into StudentCourse values(1,3)
Insert into StudentCourse values(2,1)
Insert into StudentCourse values(3,2)
Insert into StudentCourse values(4,4)
Note: - We don’t need to insert data for the column StudentCourseid since it is an identity column.
Now, if we want to get the list of all the student which belong to the course “Oracle”, then the
query will be,
select Firstname, lastname from student where studentid in (select studentidfrom studentcourse w
here courseid in (select courseid from course wherecoursename='Oracle'))
Result:-
In this example we use the nested subquery since the subquery
“select courseidfrom course where coursename='Oracle'” is itself contained in the another
subquery(Parent Subquery)
“select studentid from studentcourse where courseidin (select courseid from course where coursen
ame='Oracle')”.
Correlated Subquery:-If the outcome of a subquery is depends on the value of a column of its
parent query table then the Sub query is called Correlated Subquery.
Suppose we want to get the details of the Courses (including the name of their course admin) from
the Course table, we can use the following query:-
select Coursename ,Courseadminid,(select Firstname+'
'+Lastname from studentwhere studentid=[Link])as CourseAdminName from cour
se
Result:-
Here in this example the “select Firstname+'
'+Lastname from student wherestudentid=[Link]” is called the correlated
subquery since the outcome of this subquery is depends on the column courseadminid of the
parent query. This means that the correlated subquery will be executed for each row selected by
the parent query.
It is not necessary that the column on which the correlated query is depended is included in the
selected columns list of the parent query. For example the below query will also works even the
column courseadminid on which the correlated query is depends , is not included in the selected
columns list of the parent query.
select Coursename ,(select Firstname+'
'+Lastname from student wherestudentid=[Link])as CourseAdminName from cour
se
Results:-
ORACLE SUBQUERY/CORRELATED QUERY EXAMPLES
A subquery is a SELECT statement which is used in another SELECT statement. Subqueries are very
useful when you need to select rows from a table with a condition that depends on the data of the
table itself. You can use the subquery in the SQL clauses including WHERE clause, HAVING clause,
FROM clause etc.
The subquery can also be referred as nested SELECT, sub SELECT or inner SELECT. In general, the
subquery executes first and its output is used in the main query or outer query.
Types of Sub queries:
There are two types of subqueries in oracle:
Single Row Subqueries: The subquery returns only one row. Use single row comparison
operators like =, > etc while doing comparisions.
Multiple Row Subqueries: The subquery returns more than one row. Use multiple row
comparison operators like IN, ANY, ALL in the comparisons.
SINGLE ROW SUBQUERY EXAMPLES
1. Write a query to find the salary of employees whose salary is greater than the salary of
employee whose id is 100?
SELECT EMPLOYEE_ID,SALARY FROM EMPLOYEES WHERE SALARY >
(SELECT SALARY FROM EMPLOYEES WHERE EMPLOYEED_ID = 100 )
CORRELATED SUBQUERIES EXAMPLES
Correlated sub query is used for row by row processing. The sub query is executed for each row of
the main query.
2. Write a query to list the department names which have at lease one employee?
SELECT DEPARTMENT_ID,DEPARTMENT_NAME FROM DEPARTMENTS D
WHERE EXISTS(SELECT 1 FROM EMPLOYEES E WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID)
Date Functions
Date Functions are ADD_MONTHS, LAST_DAY, NEXT_DAY, MONTHS_BETWEEN & SYSDATE.
Character Functions
Character Functions are INITCAP, UPPER, LOWER, SUBSTR & LENGTH. Additional functions are
GREATEST & LEAST.
Group Functions returns results based upon groups of rows rather than one result per row, use
group functions. They are AVG, COUNT, MAX, MIN & SUM.
Correlated Subquery
Correlated Subquery is a subquery that is evaluated once for each row processed by the parent
statement. Parent statement can be Select, Update or Delete. Use CRSQ to answer multipart
questions whose answer depends on the value in each row processed by parent statement
Sequences
Sequences are used for generating sequence numbers without any overhead of locking. Drawback
is that after generating a sequence number if the transaction is rolled back, then that sequence
number is lost.
Synonyms
Synonyms is the alias name for table, views, sequences & procedures and are created for reasons
of Security and Convenience.
Two levels are Public - created by DBA & accessible to all the users. Private - Accessible to creator
only. Advantages are referencing without specifying the owner and Flexibility to customize a more
meaningful naming convention.
Indexes
Indexes are optional structures associated with tables used to speed query execution and/or
guarantee uniqueness. Create an index if there are frequent retrieval of fewer than 10-15% of the
rows in a large table and columns are referenced frequently in the WHERE clause. Implied tradeoff
is query speed vs. update speed. Oracle automatically update indexes. Concatenated index max. is
16 columns.
Rollback
Rollback causes work in the current transaction to be undone.
Savepoint
Savepoint is a point within a particular transaction to which you may rollback without rolling back
the entire transaction.
SQL*Plus
SQL*Plus is an application that recognizes & executes SQL commands & specialized SQL*Plus
commands that can customize reports, provide help & edit facility & maintain system variables.
SQL*Loader
SQL*Loader is a product for moving data in external files into tables in an Oracle database. To load
data from external files into an Oracle database, two types of input must be provided to
SQL*Loader : the data itself and the control file. The control file describes the data to be loaded. It
describes the Names and format of the data files, Specifications for loading data and the Data to
be loaded (optional). Invoking the loader sqlload username/password controlfilename <options>.
SELECT SAL + NVL(COMM,0) FROM EMP;?
This displays the total salary of all employees. The null values in the commission column will be
replaced by 0 and added to salary.
What command is used to get back the privileges offered by the GRANT command?
REVOKE.
What will be the output of the following query?
SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );?
NO.
Which date function is used to find the difference between two dates?
MONTHS_BETWEEN.
What operator performs pattern matching?
LIKE operator.
What command is used to create a table by copying the structure of another table?
CREATE TABLE .. AS SELECT command
Explanation:
To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE
statement as in the following.
CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;
If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to
the new table.
TRUNCATE TABLE EMP; DELETE FROM EMP; Will the outputs of the above two commands differ?
Both will result in deleting all the rows in the table EMP..
What is correlated sub-query?
Correlated sub-query is a sub-query, which has reference to the main query.
Difference between SUBSTR and INSTR?
INSTR (String1, String2 (n, (m)),
INSTR returns the position of the m-th occurrence of the string 2 in string1. The search begins from
nth position of string1.
SUBSTR (String1 n, m)
SUBSTR returns a character string of size m in string1, starting from n-th position of string1.
Explain UNION, MINUS, UNION ALL and INTERSECT?
INTERSECT - returns all distinct rows selected by both queries.
MINUS - returns all distinct rows selected by the first query but not by the second.
UNION - returns all distinct rows selected by either query
UNION ALL - returns all rows selected by either query, including all duplicates.
What is ROWID?
ROWID is a pseudo column attached to each row of a table. It is 18 characters long, blockno,
rownumber are the components of ROWID.
What is the fastest way of accessing a row in a table?
Using ROWID.
CONSTRAINTS
What is an integrity constraint?
Integrity constraint is a rule that restricts values to a column in a table.
What is referential integrity constraint?
Maintaining data integrity through a set of rules that restrict the values of one or more columns of
the tables based on the values of primary key or unique key of the referenced table.
What is the usage of SAVEPOINTS?
SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back part of a
transaction. Maximum of five save points are allowed.
What are the advantages of VIEW?
- To protect some of the columns of a table from other users.
- To hide complexity of a query.
- To hide complexity of calculations.
1. Get the first day of the month
SELECT TRUNC (SYSDATE, 'MONTH') "First day of current month"
FROM DUAL;
2. Get the last day of the month
SELECT TRUNC (LAST_DAY (SYSDATE)) "Last day of current month"
FROM DUAL;
3. Get the first day of the Year
SELECT TRUNC (SYSDATE, 'YEAR') "Year First Day" FROM DUAL;
4. Get the last day of the year
SELECT ADD_MONTHS (TRUNC (SYSDATE, 'YEAR'), 12) - 1 "Year Last Day" FROM DUAL
5. Get number of days in current month
SELECT CAST (TO_CHAR (LAST_DAY (SYSDATE), 'dd') AS INT) number_of_days
FROM DUAL;
6. Get number of days left in current month
SELECT SYSDATE,
LAST_DAY (SYSDATE) "Last",
LAST_DAY (SYSDATE) - SYSDATE "Days left"
FROM DUAL;
7. Get number of days between two dates
SELECT ROUND ( (MONTHS_BETWEEN ('01-Feb-2014', '01-Mar-2012') * 30), 0)
num_of_days
FROM DUAL;
OR
SELECT TRUNC(sysdate) - TRUNC(e.hire_date) FROM employees;
8. Get number of seconds passed since today (since 00:00 hr)
SELECT (SYSDATE - TRUNC (SYSDATE)) * 24 * 60 * 60 num_of_sec_since_morning
FROM DUAL;
9. Get number of seconds left today (till [Link] hr)
SELECT (TRUNC (SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_left
FROM DUAL;
10. Check if a table exists in the current database schema
SELECT table_name
FROM user_tables
WHERE table_name = 'TABLE_NAME';
11. Check if a column exists in a table
SELECT column_name AS FOUND
FROM user_tab_cols
WHERE table_name = 'TABLE_NAME' AND column_name = 'COLUMN_NAME';
12. Showing the table structure
SELECT DBMS_METADATA.get_ddl ('TABLE', 'TABLE_NAME', 'USER_NAME') FROM DUAL;
13. Getting current schema
Yet another query to get current schema name.
SELECT SYS_CONTEXT ('userenv', 'current_schema') FROM DUAL;
14. Changing current schema
ALTER SESSION SET CURRENT_SCHEMA = new_schema;
15. Database version information
SELECT * FROM v$version;
16. Database default information
Some system default information.
SELECT username,
profile,
default_tablespace,
temporary_tablespace
FROM dba_users;
17. Database Character Set information
Display the character set information of database.
SELECT * FROM nls_database_parameters;
18. Get Oracle version
SELECT VALUE
FROM v$system_parameter
WHERE name = 'compatible';
19. Adding datafile to a tablespace
Query to add datafile in a tablespace.
ALTER TABLESPACE data01 ADD DATAFILE '/work/oradata/STARTST/[Link]'
SIZE 1000M AUTOEXTEND OFF;
20. Find the Actual size of a Database
SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_data_files;
21. Find the size occupied by Data in a Database or Database usage details
Gives the size occupied by data in this database.
SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_segments;
22. Find the size of the SCHEMA/USER
Give the size of user in MBs.
SELECT SUM (bytes / 1024 / 1024) "size"
FROM dba_segments
WHERE owner = '&owner';
23. Last SQL Fired from particular Schema or Table:
SELECT CREATED, TIMESTAMP, last_ddl_time
FROM all_objects
WHERE OWNER = 'MYSCHEMA'
AND OBJECT_TYPE = 'TABLE'
AND OBJECT_NAME = 'EMPLOYEE_TABLE';
24. Oracle SQL query over the view that shows actual Oracle connections.
SELECT osuser,
username,
machine,
program
FROM v$session
ORDER BY osuser;
25. Oracle SQL query that show the opened connections group by the
program that opens the connection.
SELECT program application, COUNT (program) Numero_Sesiones
FROM v$session
GROUP BY program
ORDER BY Numero_Sesiones DESC;
26. Oracle SQL query that shows Oracle users connected and the sessions
number for user
SELECT username Usuario_Oracle, COUNT (username) Numero_Sesiones
FROM v$session
GROUP BY username
ORDER BY Numero_Sesiones DESC;
27. Get number of objects per owner
SELECT owner, COUNT (owner) number_of_objects
FROM dba_objects
GROUP BY owner
ORDER BY number_of_objects DESC;
28. Utility / Math related queries
29. Convert number to words
SELECT TO_CHAR (TO_DATE (1526, 'j'), 'jsp') FROM DUAL;
Output:
one thousand five hundred twenty-six
30. Find the last record from a table
This ones straight forward. Use this when your table does not have primary key or you
cannot be sure if record having max primary key is the latest one.
SELECT *
FROM employees
WHERE ROWID IN (SELECT MAX (ROWID) FROM employees);
(OR)
SELECT * FROM employees
MINUS
SELECT *
FROM employees
WHERE ROWNUM < (SELECT COUNT (*) FROM employees);
31. Random number generator in Oracle
--generate random number between 0 and 100
SELECT ROUND (DBMS_RANDOM.VALUE () * 100) + 1 AS random_num FROM DUAL;
32. Check if table contains any data
This one can be written in multiple ways. You can create count(*) on a table to know
number of rows. But this query is more efficient given the fact that we are only interested
in knowing if table has any data.
SELECT 1
FROM TABLE_NAME
WHERE ROWNUM = 1;
Deleting Duplicate Rows In Oracle
1. Using MIN(rowid) : The most common method of removing duplicate rows.
DELETE FROM tbl_test
WHERE ROWID NOT IN (SELECT MIN (ROWID)
FROM tbl_test
GROUP BY ser_no, fst_nm, deptid, cmnt);
1 Which is more faster - IN or EXISTS?
EXISTS is more faster than IN because EXISTS returns a Boolean value whereas IN returns a value.
2 Which datatype is used for storing graphics and images?
LONG RAW data type is used for storing BLOB's (binary large objects).
3 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.
4 What WHERE CURRENT OF clause does in a cursor?
LOOPSELECT num_credits INTO v_numcredits FROM classesWHERE dept=123 and
course=101;UPDATE studentsSET current_credits=current_credits+v_numcreditsWHERE CURRENT
OF X;END LOOPCOMMIT;END;
5 What should be the return type for a cursor [Link] we use a scalar data type as return
type?
The return type for a cursor must be a record [Link] can be declared explicitly as a user-defined or
%ROWTYPE can be used. eg TYPE t_studentsref IS REF CURSOR RETURN students%ROWTYPE
6 What is use of a cursor variable? How it is defined?
A cursor variable is associated with different statements at run time, which can hold different
values at run time. Static cursors can only be associated with one run time query. A cursor variable
is reference type (like a pointer in C).Declaring a cursor variable:TYPE type_name IS REF CURSOR
RETURN return_type type_name is the name of the reference type,return_type is a record type
indicating the types of the select list that will eventually be returned by the cursor variable.
7 What is the purpose of a cluster?
Oracle does not allow a user to specifically locate tables, since that is a part of the function of the
RDBMS. However, for the purpose of increasing performance, oracle allows a developer to create a
CLUSTER. A CLUSTER provides a means for storing data from different tables together for faster
retrieval than if the table placement were left to the RDBMS.
8 What is the maximum buffer size that can be specified using the DBMS_OUTPUT.ENABLE
function?
1,000,00
9 What is syntax for dropping a procedure and a function .Are these operations possible?
Drop Procedure procedure_nameDrop Function function_name
10 What is OCI. What are its uses?
Oracle Call Interface is a method of accesing database from a 3GL program. Uses--No precompiler
is required,PL/SQL blocks are executed like other DML statements. The OCI library provides· -
functions to parse SQL statemets· -bind input variables· -bind output variables· -execute
statements· -fetch the results
11 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.
12 What is difference between SUBSTR and INSTR?
SUBSTR returns a specified portion of a string eg SUBSTR('BCDEF',4) output BCDEINSTR provides
character position in which a pattern is found in a string. eg INSTR('ABC-DC-F','-',2) output 7 (2nd
occurence of '-')
13 What is 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,DCL,DDL).
SQL*PLUS commands are used to format query result, Set options, Edit SQL commands and
PL/SQL.
14 What is difference between Rename and Alias?
Rename is a permanent name given to a table or column whereas Alias is a temporary name given
to a table or column which do not exist once the SQL statement is executed.
15 What is difference between a formal and an actual parameter?
The variables declared in the procedure and which are passed, as arguments are called actual, the
parameters in the procedure declaration. Actual parameters contain the values that are passed to
a procedure and receive results. Formal parameters are the placeholders for the values of actual
parameters
16 What is an UTL_FILE.What are different procedures and functions associated with it?
UTL_FILE is a package that adds the ability to read and write to operating system files. Procedures
associated with it are FCLOSE, FCLOSE_ALL and 5 procedures to output data to a file PUT,
PUT_LINE, NEW_LINE, PUTF, [Link], FFLUSH.PUT_LINE,FFLUSH.NEW_LINE. Functions
associated with it are FOPEN, ISOPEN.
17 What is a view ?
A view is stored procedure based on one or more tables, it’s a virtual table.
18 What is a pseudo column. Give some examples?
It is a column that is not an actual column in the [Link] USER, UID, SYSDATE, ROWNUM, ROWID,
NULL, AND LEVEL.
19 What is a OUTER JOIN?
Outer Join--Its a join condition used where you can query all the rows of one of the tables in the join
condition even though they don’t satisfy the join condition.
20 What is a cursor?
Oracle uses work area to execute SQL statements and store processing information PL/SQL
construct called a cursor lets you name a work area and access its stored information A cursor is a
mechanism used to fetch more than one row in a Pl/SQl block.
21 What is a cursor for loop?
Cursor For Loop is a loop where oracle implicitly declares a loop variable, the loop index that of the
same record type as the cursor's record.
22 What are various privileges that a user can grant to another user?
· SELECT· CONNECT· RESOURCES
23 What are various constraints used in SQL?
· NULL· NOT NULL· CHECK· DEFAULT
24 What are ORACLE PRECOMPILERS?
Using ORACLE PRECOMPILERS, SQL statements and PL/SQL blocks can be contained inside 3GL
programs written in C,C++,COBOL,PASCAL, FORTRAN,PL/1 AND [Link] Precompilers are known
as Pro*C,Pro*Cobol,...This form of PL/SQL is known as embedded pl/sql,the language in which pl/sql
is embedded is known as the host language. The prcompiler translates the embedded SQL and
pl/sql ststements into calls to the precompiler runtime [Link] output must be compiled and
linked with this library to creater an executable.
25 What are different Oracle database objects?
· TABLES· VIEWS· INDEXES· SYNONYMS· SEQUENCES· TABLESPACES etc
26 What are different modes of parameters used in functions and procedures?
· IN· OUT· INOUT
27 What are cursor attributes?
· %ROWCOUNT· %NOTFOUND· %FOUND· %ISOPEN
28 What a SELECT FOR UPDATE cursor represent.
[ANSWER]SELECT......FROM......FOR......UPDATE[OF column-reference][NOWAIT] The processing
done in a fetch loop modifies the rows that have been retrieved by the cursor. A convenient way of
modifying the rows is done by a method with two parts: the FOR UPDATE clause in the cursor
declaration, WHERE CURRENT OF CLAUSE in an UPDATE or declaration statement.
29 There is a string 120000 12 0 .125 , how you will find the position of the decimal place?
INSTR('120000 12 0 .125',1,'.')output 13
30 There is a % sign in one field of a column. What will be the query to find it?
'' Should be used before '%'.
31 Suppose a customer table is having different columns like customer no, [Link] will be
the query to select top three max payments?
SELECT customer_no, payments from customer C1
WHERE 3<=(SELECT COUNT(*) from customer C2
WHERE [Link] <= [Link])
32 [Link] Select the Nth lowest value from a table
select level, min('col_name') from my_table where level = '&n' connect by prior ('col_name') <
'col_name')
group by level;
Example:
Given a table called emp with the following columns:
-- id number
-- name varchar2(20)
-- sal number
--
-- For the second lowest salary:
-- select level, min(sal) from emp
-- where level=2
-- connect by prior sal < sal
-- group by level
33 [Link] Select the Nth Highest value from a table
select level, max('col_name') from my_table where level = '&n' connect by prior ('col_name') >
'col_name')
group by level;
Example:
Given a table called emp with the following columns:
-- id number
-- name varchar2(20)
-- sal number
--
-- For the second highest salary:
-- select level, max(sal) from emp
-- where level=2
-- connect by prior sal > sal
-- group by level
34 How you will avoid your query from using indexes?
SELECT * FROM emp
Where emp_no+' '=12345;
i.e you have to concatenate the column name with space within codes in the where condition.
SELECT /*+ FULL(a) */ ename, emp_no from emp
where emp_no=1234;
i.e using HINTS
35 How you will avoid duplicating records in a query?
By using DISTINCT
36 How you were passing cursor variables in PL/SQL 2.2?
In PL/SQL 2.2 cursor variables cannot be declared in a [Link] is because the storage for a
cursor variable has to be allocated using Pro*C or OCI with version 2.2, the only means of passing a
cursor variable to a PL/SQL block is via bind variable or a procedure parameter.
37 How you open and close a cursor [Link] it is required?
OPEN cursor variable FOR SELECT...Statement
CLOSE cursor variable In order to associate a cursor variable with a particular SELECT statement
OPEN syntax is used. In order to free the resources used for the query CLOSE statement is used.
38 How will you delete duplicating rows from a base table?
delete from table_name where rowid not in (select max(rowid) from table group by
duplicate_values_field_name); or
delete duplicate_values_field_name dv from table_name ta where rowid <(select min(rowid) from
table_name tb where [Link]=[Link]);
39 How do you find the numbert of rows in a Table ?
A bad answer is count them (SELECT COUNT(*) FROM table_name)
A good answer is :-
'By generating SQL to ANALYZE TABLE table_name COUNT STATISTICS by querying Oracle System
Catalogues (e.g. USER_TABLES or ALL_TABLES).
The best answer is to refer to the utility which Oracle released which makes it unnecessary to do
ANALYZE TABLE for each Table individually.
40 Find out nth highest salary from emp table
SELECT DISTINCT ([Link]) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT ([Link])) FROM EMP B
WHERE [Link]<=[Link]);
For Eg:-
Enter value for n: 2
SAL
---------
3700
41 Display the records between two range?
select rownum, empno, ename from emp where rowid in (select rowid from emp where rownum
<=&upto minus select rowid from emp where rownum<&Start);
42 Display the number value in Words?
SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))
from emp;
the output like,
SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))
--------- -----------------------------------------------------
800 eight hundred
1600 one thousand six hundred
1250 one thousand two hundred fifty
If you want to add some text like, Rs. Three Thousand only.
SQL> select sal "Salary ",
(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))
"Sal in Words" from emp
/
Salary Sal in Words
------- ------------------------------------------------------
800 Rs. Eight Hundred only.
1600 Rs. One Thousand Six Hundred only.
1250 Rs. One Thousand Two Hundred Fifty only.
43 Display Odd/ Even number of records
Odd number of records:
select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
Output:-
1
3
5
Even number of records:
select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
Output:-
2
4
6
44 Difference between procedure and function.
Functions are named PL/SQL blocks that return a value and can be called with arguments
procedure a named block that can be called with parameter. A procedure all is a PL/SQL statement
by itself, while a Function call is called as part of an expression.
45 Difference between NO DATA FOUND and %NOTFOUND
NO DATA FOUND is an exception raised only for the SELECT....INTO statements when the where
clause of the querydoes not match any rows. When the where clause of the explicit cursor does not
match any rows the %NOTFOUND attribute is set to TRUE instead.
46 Difference between database triggers and form triggers?
Data base trigger(DBT) fires when a DML operation is performed on a data base table. Form
trigger(FT) Fires when user presses a key or navigates between fields on the screen
Can be row level or statement level No distinction between row level and statement level.
Can manipulate data stored in Oracle tables via SQL Can manipulate data in Oracle tables as well
as variables in forms.
Can be fired from any session executing the triggering DML statements. Can be fired only from the
form that define the trigger.
Can cause other database triggers to [Link] cause other database triggers to fire, but not other
form triggers.
47 Difference between an implicit & an explicit cursor.
PL/SQL declares a cursor implicitly for all SQL data manipulation statements, including quries that
return only one row. However,queries that return more than one row you must declare an explicit
cursor or use a cursor FOR loop.
Explicit cursor is a cursor in which the cursor name is explicitly assigned to a SELECT statement via
the CURSOR...IS statement. An implicit cursor is used for all SQL statements Declare, Open, Fetch,
Close. An explicit cursors are used to process multirow SELECT statements An implicit cursor is
used to process INSERT, UPDATE, DELETE and single row SELECT. .INTO statements.
48 Can you use a commit statement within a database trigger?
No.
49 Can the default values be assigned to actual parameters?
Yes
50 Can cursor variables be stored in PL/SQL [Link] yes how. If not why?
No, a cursor variable points a row which cannot be stored in a two-dimensional PL/SQL table.
51 Can a primary key contain more than one columns?
Yes
52 Can a function take OUT parameters. If not why?
No. A function has to return a value,an OUT parameter cannot return a value.
53 What are various joins used while writing SUBQUERIES?
Self join-Its a join foreign key of a table references the same table. Outer Join--Its a join condition
used where One can query all the rows of one of the tables in the join condition even though they
don't satisfy the join condition.
Equi-join--Its a join condition that retrieves rows from one or more tables in which one or more
columns in one table are equal to one or more columns in the second table.
54 Differentiate between TRUNCATE and DELETE
TRUNCATE deletes much faster than DELETE
TRUNCATE
DELETE
It is a DDL statement It is a DML statement
It is a one way trip,cannot ROLLBACK One can Rollback
Doesn't have selective features (where clause) Has
Doesn't fire database triggers Does
It requires disabling of referential constraints. Does not require
1 What is PL/SQL ?
PL/SQL is a procedural language that has both interactive SQL and procedural programming
language constructs such as iteration, conditional branching.
2 Write the order of precedence for validation of a column in a table ?
I. done using Database triggers.
ii. done using Integarity Constraints.
I & ii.
Exception :
3 Where the Pre_defined_exceptions are stored ?
In the standard package.
Procedures, Functions & Packages ;
4 What are % TYPE and % ROWTYPE ? What are the advantages of using these over datatypes?
% TYPE provides the data type of a variable or a database column to that variable.
% ROWTYPE provides the record type that represents a entire row of a table or view or columns
selected in the cursor.
The advantages are : I. Need not know about variable's data type
ii. If the database definition of a column in a table changes, the data type of a variable changes
accordingly.
5 What will happen after commit statement ?
Cursor C1 is
Select empno,
ename from emp;
Begin
open C1; loop
Fetch C1 into
[Link];
Exit When
C1 %notfound;-----
commit;
end loop;
end;
The cursor having query as SELECT .... FOR UPDATE gets closed after COMMIT/ROLLBACK.
The cursor having query as SELECT.... does not get closed even after COMMIT/ROLLBACK.
6 What is the basic structure of PL/SQL ?
PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks can be used
in PL/SQL.
7 What is Raise_application_error ?
Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue an
user_defined error messages from stored sub-program or database trigger.
8 What is Pragma EXECPTION_INIT ? Explain the usage ?
The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle error. To
get an error message of a specific oracle error.
e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)
9 What is PL/SQL table ?
Objects of type TABLE are called "PL/SQL tables", which are modeled as (but not the same as)
database tables, PL/SQL tables use a primary PL/SQL tables can have one column and a primary
key.
Cursors
10 What is Overloading of procedures ?
The Same procedure name is repeated with parameters of different datatypes and parameters in
different positions, varying number of parameters is called overloading of procedures.
e.g. DBMS_OUTPUT put_line
What is a package ? What are the advantages of packages ?
11 What is difference between a PROCEDURE & FUNCTION ?
A FUNCTION is always returns a value using the return statement.
A PROCEDURE may return one or more values through parameters or may not return at all.
12 What is difference between a Cursor declared in a procedure and Cursor declared in a package
specification ?
A cursor declared in a package specification is global and can be accessed by other procedures or
procedures in a package.
A cursor declared in a procedure is local to the procedure that can not be accessed by other
procedures.
13 What is difference between % ROWTYPE and TYPE RECORD ?
% ROWTYPE is to be used whenever query returns a entire row of a table or view.
TYPE rec RECORD is to be used whenever query returns columns of different
table or views and variables.
E.g. TYPE r_emp is RECORD (eno [Link]% type,ename emp ename %type
);
e_rec emp% ROWTYPE
cursor c1 is select empno,deptno from emp;
e_rec c1 %ROWTYPE.
14 What is an Exception ? What are types of Exception ?
Exception is the error handling part of PL/SQL block. The types are Predefined and user defined.
Some of Predefined exceptions are.
CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
INVALID_NUMBER
LOGON_DENIED
NOT_LOGGED_ON
PROGRAM-ERROR
STORAGE_ERROR
TIMEOUT_ON_RESOURCE
VALUE_ERROR
ZERO_DIVIDE
OTHERS.
15 What is a stored procedure ?
A stored procedure is a sequence of statements that perform specific function.
16 What is a database trigger ? Name some usages of database trigger ?
Database trigger is stored PL/SQL program unit associated with a specific database table. Usages
are Audit data modifications, Log events transparently, Enforce complex business rules Derive
column values automatically, Implement complex security authorizations. Maintain replicate
tables.
17 What is a cursor for loop ?
Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor, fetches rows of values
from active set into fields in the record and closes
when all the records have been processed.
eg. FOR emp_rec IN C1 LOOP
salary_total := salary_total +emp_rec sal;
END LOOP;
18 What is a cursor ? Why Cursor is required ?
Cursor is a named private SQL area from where information can be accessed. Cursors are required
to process rows individually for queries returning multiple rows.
19 What happens if a procedure that updates a column of table X is called in a database trigger of
the same table ?
Mutation of table occurs.
20 What are two virtual tables available during database trigger execution ?
The table columns are referred as OLD.column_name and NEW.column_name.
For triggers related to INSERT only NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name NEW.column_name values only available.
For triggers related to DELETE only OLD.column_name values only available.
21 What are two parts of package ?
The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY.
Package Specification contains declarations that are global to the packages and local to the
schema.
Package Body contains actual procedures and local declaration of the procedures and cursor
declarations.
22 What are the two parts of a procedure ?
Procedure Specification and Procedure Body.
23 What are the return values of functions SQLCODE and SQLERRM ?
SQLCODE returns the latest code of the error that has occurred.
SQLERRM returns the relevant error message of the SQLCODE.
24 What are the PL/SQL Statements used in cursor processing ?
DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO or Record types,
CLOSE cursor name.
25 What are the modes of parameters that can be passed to a procedure ?
IN,OUT,IN-OUT parameters.
26 What are the datatypes a available in PL/SQL ?
Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN.
Some composite data types such as RECORD & TABLE.
27 What are the cursor attributes used in PL/SQL ?
%ISOPEN - to check whether cursor is open or not
% ROWCOUNT - number of rows fetched/updated/deleted.
% FOUND - to check whether cursor has fetched any row. True if rows are fetched.
% NOT FOUND - to check whether cursor has fetched any row. True if no rows are featched.
These attributes are proceeded with SQL for Implicit Cursors and with Cursor name for Explicit
Cursors.
28 What are the components of a PL/SQL Block ?
Declarative part, Executable part and Exception part.
Datatypes PL/SQL
29 What are the components of a PL/SQL block ?
A set of related declarations and procedural statements is called block.
30 What are advantages fo Stored Procedures /
Extensibility,Modularity, Reusability, Maintainability and one time compilation.
1 What is PL/SQL ?
PL/SQL is a procedural language that has both interactive SQL and procedural programming
language constructs such as iteration, conditional branching.
2 Write the order of precedence for validation of a column in a table ?
I. done using Database triggers.
ii. done using Integarity Constraints.
I & ii.
Exception :
3 Where the Pre_defined_exceptions are stored ?
In the standard package.
Procedures, Functions & Packages ;
4 What are % TYPE and % ROWTYPE ? What are the advantages of using these over datatypes?
% TYPE provides the data type of a variable or a database column to that variable.
% ROWTYPE provides the record type that represents a entire row of a table or view or columns
selected in the cursor.
The advantages are : I. Need not know about variable's data type
ii. If the database definition of a column in a table changes, the data type of a variable changes
accordingly.
5 What will happen after commit statement ?
Cursor C1 is
Select empno,
ename from emp;
Begin
open C1; loop
Fetch C1 into
[Link];
Exit When
C1 %notfound;-----
commit;
end loop;
end;
The cursor having query as SELECT .... FOR UPDATE gets closed after COMMIT/ROLLBACK.
The cursor having query as SELECT.... does not get closed even after COMMIT/ROLLBACK.
6 What is the basic structure of PL/SQL ?
PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks can be used
in PL/SQL.
7 What is Raise_application_error ?
Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue an
user_defined error messages from stored sub-program or database trigger.
8 What is Pragma EXECPTION_INIT ? Explain the usage ?
The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle error. To
get an error message of a specific oracle error.
e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)
9 What is PL/SQL table ?
Objects of type TABLE are called "PL/SQL tables", which are modeled as (but not the same as)
database tables, PL/SQL tables use a primary PL/SQL tables can have one column and a primary
key.
Cursors
10 What is Overloading of procedures ?
The Same procedure name is repeated with parameters of different datatypes and parameters in
different positions, varying number of parameters is called overloading of procedures.
e.g. DBMS_OUTPUT put_line
What is a package ? What are the advantages of packages ?
11 What is difference between a PROCEDURE & FUNCTION ?
A FUNCTION is always returns a value using the return statement.
A PROCEDURE may return one or more values through parameters or may not return at all.
12 What is difference between a Cursor declared in a procedure and Cursor declared in a package
specification ?
A cursor declared in a package specification is global and can be accessed by other procedures or
procedures in a package.
A cursor declared in a procedure is local to the procedure that can not be accessed by other
procedures.
13 What is difference between % ROWTYPE and TYPE RECORD ?
% ROWTYPE is to be used whenever query returns a entire row of a table or view.
TYPE rec RECORD is to be used whenever query returns columns of different
table or views and variables.
E.g. TYPE r_emp is RECORD (eno [Link]% type,ename emp ename %type
);
e_rec emp% ROWTYPE
cursor c1 is select empno,deptno from emp;
e_rec c1 %ROWTYPE.
14 What is an Exception ? What are types of Exception ?
Exception is the error handling part of PL/SQL block. The types are Predefined and user defined.
Some of Predefined exceptions are.
CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
INVALID_NUMBER
LOGON_DENIED
NOT_LOGGED_ON
PROGRAM-ERROR
STORAGE_ERROR
TIMEOUT_ON_RESOURCE
VALUE_ERROR
ZERO_DIVIDE
OTHERS.
15 What is a stored procedure ?
A stored procedure is a sequence of statements that perform specific function.
16 What is a database trigger ? Name some usages of database trigger ?
Database trigger is stored PL/SQL program unit associated with a specific database table. Usages
are Audit data modifications, Log events transparently, Enforce complex business rules Derive
column values automatically, Implement complex security authorizations. Maintain replicate
tables.
17 What is a cursor for loop ?
Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor, fetches rows of values
from active set into fields in the record and closes
when all the records have been processed.
eg. FOR emp_rec IN C1 LOOP
salary_total := salary_total +emp_rec sal;
END LOOP;
18 What is a cursor ? Why Cursor is required ?
Cursor is a named private SQL area from where information can be accessed. Cursors are required
to process rows individually for queries returning multiple rows.
19 What happens if a procedure that updates a column of table X is called in a database trigger of
the same table ?
Mutation of table occurs.
20 What are two virtual tables available during database trigger execution ?
The table columns are referred as OLD.column_name and NEW.column_name.
For triggers related to INSERT only NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name NEW.column_name values only available.
For triggers related to DELETE only OLD.column_name values only available.
21 What are two parts of package ?
The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY.
Package Specification contains declarations that are global to the packages and local to the
schema.
Package Body contains actual procedures and local declaration of the procedures and cursor
declarations.
22 What are the two parts of a procedure ?
Procedure Specification and Procedure Body.
23 What are the return values of functions SQLCODE and SQLERRM ?
SQLCODE returns the latest code of the error that has occurred.
SQLERRM returns the relevant error message of the SQLCODE.
24 What are the PL/SQL Statements used in cursor processing ?
DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO or Record types,
CLOSE cursor name.
25 What are the modes of parameters that can be passed to a procedure ?
IN,OUT,IN-OUT parameters.
26 What are the datatypes a available in PL/SQL ?
Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN.
Some composite data types such as RECORD & TABLE.
27 What are the cursor attributes used in PL/SQL ?
%ISOPEN - to check whether cursor is open or not
% ROWCOUNT - number of rows fetched/updated/deleted.
% FOUND - to check whether cursor has fetched any row. True if rows are fetched.
% NOT FOUND - to check whether cursor has fetched any row. True if no rows are featched.
These attributes are proceeded with SQL for Implicit Cursors and with Cursor name for Explicit
Cursors.
28 What are the components of a PL/SQL Block ?
Declarative part, Executable part and Exception part.
Datatypes PL/SQL
29 What are the components of a PL/SQL block ?
A set of related declarations and procedural statements is called block.
30 What are advantages fo Stored Procedures /
Extensibility,Modularity, Reusability, Maintainability and one time compilation.
31 Name the tables where characteristics of Package, procedure and functions are stored ?
User_objects, User_Source and User_error.
32 Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database
Trigger ? Why ?
It is not possible. As triggers are defined for each table, if you use COMMIT of ROLLBACK in a
trigger, it affects logical transaction processing.
33 How packaged procedures and functions are called from the following?
a. Stored procedure or anonymous block
b. an application program such a PRC C, PRO COBOL
c. SQL *PLUS
a. PACKAGE [Link] NAME (parameters);
variable := PACKAGE [Link] NAME (arguments);
EXEC SQL EXECUTE
b.
BEGIN
PACKAGE [Link] NAME (parameters)
variable := PACKAGE [Link] NAME (arguments);
END;
END EXEC;
c. EXECUTE PACKAGE [Link] if the procedures does not have any
out/in-out parameters. A function can not be called.
34 How many types of database triggers can be specified on a table ? What are they ?
Insert Update Delete
Before Row o.k. o.k. o.k.
After Row o.k. o.k. o.k.
Before Statement o.k. o.k. o.k.
After Statement o.k. o.k. o.k.
If FOR EACH ROW clause is specified, then the trigger for each Row affected by the statement.
If WHEN clause is specified, the trigger fires according to the returned Boolean value.
35 Give the structure of the procedure ?
PROCEDURE name (parameter list.....)
is
local variable declarations
BEGIN
Executable statements.
Exception.
exception handlers
end;
36 Give the structure of the function ?
FUNCTION name (argument list .....) Return datatype is
local variable declarations
Begin
executable statements
Exception
execution handlers
End;
37 Explain the usage of WHERE CURRENT OF clause in cursors ?
WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest row fetched from
a cursor.
Database Triggers
38 Explain the two type of Cursors ?
There are two types of cursors, Implicit Cursor and Explicit Cursor.
PL/SQL uses Implicit Cursors for queries.
User defined cursors are called Explicit Cursors. They can be declared and used.
39 Explain how procedures and functions are called in a PL/SQL block ?
Function is called as part of an expression.
sal := calculate_sal ('a822');
procedure is called as a PL/SQL statement
calculate_bonus ('A822');
How do you view the last record added to a table?
In order to get Last record added to the table, you should first get an idea on table dattype..
1) Whether any sequence no in any column defined which will update when ever row is inserted.
2) will get by retrieving max rowid from the table
truncate is permanently remove from database so once u commit after truncate the data.u cant
[Link] even after deleting the data using delete [Link] after commit we can get the
data
How to retrieve 2nd highest sal in each departement from emp and dept tables using
group by?
SELECT MAX([Link]),[Link] FROM EMP A,(SELECT MAX(SAL) MSA,DEPTNO FROM EMP GROUP BY
DEPTNO) B WHERE [Link] <> MSA AND [Link] = [Link] GROUP BY [Link];
Select from table without using column name
Select column_name from all_tab_columns where table_name=megamind;
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.
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.
WHERE clause can contains condition that must be met and should directly follow the from clause.
And HAVING clause can precede GROUP BY clause,but it is more logical to declared in after GROUP
BY clau...
we have to apply the condition Before grouping the records then you have to use WHERE clause.
we have to apply the condition after grouping the records then you have to apply HAVING clause.
Difference between an implicit & an explicit cursor.
PL/SQL declares a cursor implicitly for all SQL data manipulation statements , including quries that
return only one row. However,queries that return more than one row you must declare an explicit
cursor or use a cursor for [Link] cursor is a cursor in which the cursor name is explicitly
assigned...
Its an explicit cursor not only because it returns more than one row as a result, but because it is
declared explicitly. Visually you wont see the orthodox CURSOR cursor_name IS ........ etc kind of
d...
Explicit cursor. Here we do not require a cursor definition, open, fetch and close here because
CURSOR FOR LOOP was used. You can use SQL%ROWCOUNT inside the loop to see how many rows
it returns, if it were a implicit cursor. You will find NULL, thats because its an explicit cursor.
Display the number value in words?
SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))from emp;
There is a % sign in one field of a column. What will be the query to find it?
'' should be used before '%'.
The below code selects the column with a substring % (e.g.) reg%istration
Code
1. SELECT * FROM game WHERE name LIKE %\%% escape ;
The below code will select the row having column as %
Code
SELECT * FROM table_name WHERE column_name LIKE !%escape!
Nth Highest Sal
SELECT * FROM (SELECT e.*,rownum rnm FROM (SELECT * FROM emp e ORDER BY sal DESC) e)
WHERE rnm=2;
Write a query to display employee records having same salary?
select [Link],[Link],count(*) samesalary from emp e1,emp e2 where [Link]=[Link] group by
[Link],[Link] having count(*)>1
How to select the recently updated records from the table?
select * from emp e where rowid in( select max(rowid) from emp );
Can you use a commit statement within a database trigger?
No.
How to find the two minimum salaries ?
SELECT ename,sal FROM (SELECT * FROM emp ORDER BY sal ASC)WHERE rownum<=2;
Display the emploee records who joins the department before their manager?
SELECT * FROM employees e , employees m WHERE e.manager_id=m.employee_id
AND e.hire_date < m.hire_date;
Dispaly employee records who gets more salary than the average salary in their
department?
select * from emp a where salary >(select avg(salary) from emp b where a.dept_no = b.dept_no);
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.
What is a pseudo column. Give some examples?
7 answers
It is a column that is not an actual column in the [Link] user, uid, sysdate, rownum, rowid, null,
and level.
1) Pseudo columns behave like a table column, but it is not actually stored in a table.
2) Upon pseudo columns only select statements can be implemented. Insert, delete,update cannot
be implemented. ...
[Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link]
A cursor is just like an pointer variable which processes in the memories. Cursors can be used to
process multirecord set. There are two types of cursors implicit and explicit cursors.
how we can eliminate duplicates without using distinct command?
DELETE FROM emp WHERE rowid IN(SELECT eno,ename,sal,max(rowid) FROM emp GROUPBY
eno,ename,sal);
Delete the Records selected from the below query:
select a.* from emp1 a, emp1 b where [Link] = [Link] and [Link] < [Link]
Difference between procedure and function.
Asked By: Interview Candidate | Asked On: Aug 29th, 2004
14 answers
Functions are named PL/SQL blocks that return a value and can be called with arguments
procedure a named block that can be called with parameter. A procedure all is a PL/SQL statement
by itself, while a function call is called as part of an expression.
Answered by: usha` on: Aug 19th, 2011
Functions can be used in a select statement where as procedures cannot.
functions cannot return values where as procedures can.
functions can be used as user defines data types in create table but procedures cannot.
Answered by: Prakash Jayabalan on: Oct 29th, 2009
Procedure:
Parameters IN, OUT and IN OUT and can return n number of values via sys cursor.
Function:
Only IN parameter and must return a value by using RETURN.
Can be used in where clause of the Query but performance issue will raise.
There are 5 types of joins. Those are
1. Equi Join / Inner Join
2. Non-Equi Join
3. Outer Join ( Left Outer Join, Right Outer Join, Full Outer Join )
4. Self Join
5. Cross Join
We have two type of constraints - Table Level and Column Level. Which is better and
why..?
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.
List all the employees who have atleast one person reporting to themlist the employee
details if and only if more than 10 employees are presently in department 10
select manager_id,last_name,count(employee_id) over (partition by manager_id ) cnt from
employe 2* order by cnt
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.
Suppose a customer table is having different columns like customer no, [Link]
will be the query to select top three max payments?
Select customer_no, payments from customer c1where 3<=(select count(*) from customer
c2where [Link] <= [Link])
Primay Key Unique key
----------- ------------------
There is only one there may be more than 1
Primary key for Unique Key in table
1 table
It can not contain It Can contain Null Value
Null value
There are 5 database objects:-
[Link]
[Link]
[Link]
[Link]
[Link]
objectes privileges such as select,delete,update,connect
-- To get nth Highest
select distinct salary
from (select salary,dense_rank() over(order by salary desc) as salfrom Table )where sal = &n
--To get nth Lowest
select distinct salary
from (select salary,dense_rank() over(order by salary) as salfrom Table )
where sal = &n
CORRELATED SUBQUERIES: Is evaluated for each row processed by the Main query. Execute the
Inner query based on the value fetched by the Outer query. Continues till all the values returned
by the main query are matched. The INNER Query is driven by the OUTER Query
EX: SELECT empno,fname,sal,deptid FROM emp
e WHERE sal=(SELECT AVG(sal) FROM empWHERE deptid=[Link])
The Correlated subquery specifically computes the avg(sal) for each department.
SUBQUERY: Runs first,executed once,returns values to be used by the MAIN Query. The OUTER
Query is driven by the INNER QUERY
subquery: ( subquery executes only once and gives the output ot outer query then outer query
executes)
What is the difference between rownum and rowid
the ROWNUM is a number(like serial no) which is dynamically [Link] the ROWID does not
[Link] it is having the unique address,which is generated by the oracle
Answered by: g_sidhu on: Feb 6th, 2008
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 ...
Difference between database triggers and form triggers?
Asked By: Interview Candidate | Asked On: Aug 29th, 2004
4 answers
Data base trigger(dbt) fires when a dml operation is performed on a data base table. Form
trigger(ft) fires when user presses a key or navigates between fields on the screencan be row level
or statement level no distinction between row level and statement [Link] manipulate data
stored in Oracle tables...
Answered by: rajakumar_na on: Nov 14th, 2007
Database Trigger: We can't invoke a Form Trigger in Database
From Trigger: We can invoke a Database Trigger in Forms
Answered by: Mohit Dhamija on: Jul 3rd, 2006
Even 'Form Trigger' can be fired before and after the event. ex- Triggers like Pre Block / Pre
Record / Post Block / Post Record ..
What are different modes of parameters used in functions and procedures?
Asked By: Interview Candidate | Asked On: Aug 29th, 2004
2 answers
Inoutinout
Answered by: roopali on: Jun 1st, 2007
IN : lets you pass values to the subprogram being called
OUT: lets you return values to the caller of subprogram
INOUT: lets you to pass values to the subprogram and return values to the caller of the subprogram
BLOB is generally used to store pictures . It stands for Binary Large Object. The maximum storage
limit is 4GB.
How find to find column value without knowing table name
you can use view "user_tab_columns". in this view you will get. In this you will get table_name,
column_name, datatype and all things..
select * from user_tab_columns;
1. SP can not return the table datatype whereas function can return.
2. in UDFunction if one sql statement raise the error then whole function is terminated where in SP
if one sql statement raise the error then other sql statement can be executed.
1) My table is Emp
Eno ename loc
1 Raj Delhi
2 Gaur Rajasthan
I want to display like this
Eno ename loc
1 Raj Rajasthan
2 Gaur Delhi
Ans.) select eno,ename,
case when loc=’Rajasthan’ then ‘delhi’
when loc = 'Delhi' then 'Rajasthan' else loc end as loc from emp
2) A,B two tables.
In A I have 10 columns and
in B I have 0 columns
So, whenever I write a Query likes
Select *
from A,B
What will be the output of the above query?
Ans.)We cannot create table with zero columns so query will not give any results.
3) I have a table 'Student'
stdid maths phy che Eng
1 25 52 32 12
5 25 42 23 44
Now, I want to highest marks in each student
and the output should be like this:
stdid highestmarks
1 52
5 44
Ans.)Select stdid, greatest(maths,phy,che,eng) from student;
4) How will find the same columns names from n number of tables.
Say for eg. I have 50 tables, few have same column names. So, I want to
display how many tables have same column names.
Ans.) [Link] Column_Name, count(0) From User_Tab_Columns Group By Column_Name Having
Count(0)>1
for getting the table name as well:
Select Column_Name, Table_Name From User_Tab_Columns Where Column_Name In (
Select Column_Name From User_Tab_Columns Group By Column_Name Having Count(0)>1)
order by Column_Name, Table_Name
5) I want to display 3rd & 8th row from my table which has n number of rows?
Ans.) Example: Id, name, sal
Select id,name,sal from (select id,name,sal, row_number() over (order by id) as chk from tbl) where
chk in (3,8)
6) How Groupby, Having, where & Order by are used. Put then in correct sequence.
Ans.)Where,Group by,having & Order by
7) How to display all the rows of a table except the last row.
Ans)except last row
Select * from tablename where rownum<=&n
minus
select * from tablename where rownum<=&n-1
8)How to display all the rows of a table except the first row.
Ans.)except first row
select * from tablename where rownum<=&n
minus
select * from tablename where rownum<=1
9)How to find avg salaries in table with out using AVG function?
Ans.) select sum(sal)/count(sal) "Avg Salary" from emp
10) Find the records whose salary is more than average salary in each group?
Ans.)Must use Correlated subquery and below is the snippet
select T1.Emp_id, [Link]
from TestSallary T1
where [Link] > (SELECT AVG([Link])
from TestSallary T2
where T1.Emp_ID = T2.Emp_ID)
11)how to print the number of posive signs and negetive signs and number of zeros in a particular
column?
Ans.)Must use derived table (first derive the data into the table and the apply your conditions later
on) snippet below
select COUNT(*),Salary
from (SELECT EMP_ID,
(Case when SAL = 0 then 'Zero'
when sal > 0 then 'Positive'
else 'Negative'
End) as Salary
from TestSallary) as DERIVEDSAL
group by Salary
12)How to find the latest(most recent) update records in a table?
Ans.)this can be done by simple subquery : assuming its phone records
select * from PhoneRecords
where Record_id in (select max(Record_id) from PhoneRecords
group by PhoneNumber)
13)Write a query which display total salary department wise with the employee name?
Ans.)Select Ename, DEPT_NO, SUM(SAL) OVER (PARTITION BY DEPT_NO) FROM EMPLOYEE
14)Comparing & validating Source to Target where source DB is different than the Target DB.
Say Suppose :
1) Source is MYSQL & Target is ORACLE
2) Source is flat file or .CSV file & Target is MYSQL or ORACLE
What will be the approach to test/validate the data between S & T ?
Ans.) 1. If the source is a flat file or a CSV then first we need to import data in DB (source)
2. Then we need to create view using Source that would return us data into the form of tables used
in Target DB
(For this sake, we can create Templates for creating views and these templates should be the
replica of the Target DB tables)
3. Once those views (using Source DB) are created and data is visible
4. We need to write a procedure to compare Source DB (views) to the Target DB
(OR)
1)If source is mysql and target is other rdbms then we follow some validation/comparison methods
while in sql queries
A)Count comparison:We simply count the records in source and target database using count
function-say suppose we are extracting 50 records from the source then we will count total no of
records in target database/table before and after running etl job.
After running etl job count should be increased by 50 in target database.
B)Checksum comparison:Generaly we do have summry/aggregate data/column in target database-
we will compare summary data of target database against the source database, for exp salary of
an employee for a year should be matched against aggreated sum of monthly salary for that
employee in source database.
C)Domain comprasion:Duplicate records may come in target database in this case no of records
can be matched in both the database-we have to use distinct keywork before the coulmn while
counting the records
2)In case of flat file its quite simple we do have trailer(no of records) record in a flat file,i.e we
already have no of counts of records of souce database ,anyone of method mentioned above can
be used
21. Query for removing all non-numeric :
SELECT
TRANSLATE(LOWER(ssn),'abcdefghijklmnopqrstuvwxyz- ','')
FROM DUAL;
22. Query for translating a column values to INITCAP :
SELECT
TRANSLATE(INITCAP(temp),
SUBSTR(temp, INSTR(temp,'''')+1,1), LOWER(SUBSTR(temp, INSTR(temp,'''')+1)))
FROM srinu1;
4. Function for displaying Numbers in Words:
SELECT TO_CHAR( TO_DATE( SUBSTR( TO_CHAR(5373484),1),'j'),'Jsp') FROM DUAL;
Only up to integers from 1 to 5373484
25. Query for deleting alternate even rows FROM a table :
DELETE
FROM srinu
WHERE (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,2)
FROM srinu);
26. Query for deleting alternate odd rows FROM a table :
DELETE
FROM srinu
WHERE (ROWID,1) IN (SELECT ROWID, MOD(ROWNUM,2)
FROM srinu);
28. Alternate Query for DECODE function :
SELECT case
WHEN sex = 'm' THEN 'male'
WHEN sex = 'f' THEN 'female'
ELSE 'unknown'
END
FROM mytable;
29. Create table adding Constraint to a date field to SYSDATE or 3 months later:
CREATE TABLE srinu(dt1 date DEFAULT SYSDATE, dt2 date,
CONSTRAINT check_dt2 CHECK ((dt2 >= dt1) AND (dt2 <= ADD_MONTHS(SYSDATE,3)));
30. Query to list all the suppliers who supply all the parts supplied by supplier 'S2' :
SELECT DISTINCT [Link]
FROM ORDERS a
WHERE [Link] != 'S2'
AND [Link] IN
(SELECT DISTINCT PARTS FROM ORDERS WHERE supp = 'S2')
GROUP BY [Link]
HAVING
COUNT(DISTINCT [Link]) >=
(SELECT COUNT(DISTINCT PARTS) FROM ORDERS WHERE supp = 'S2');
Table : orders
SUPP PARTS
-------------------- -------
33. Query to SELECT last N rows FROM a table :
SELECT empno FROM emp WHERE ROWID in
(SELECT ROWID FROM emp
MINUS
SELECT ROWID FROM emp WHERE ROWNUM <= (SELECT COUNT(*)-5 FROM emp));
39. Query for getting the current SessionID :
SELECT SYS_CONTEXT('USERENV','SESSIONID') Session_ID FROM DUAL;
40. Query to display rows FROM m to n :
To display rows 5 to 7 :
SELECT DEPTNO, ENAME, SAL
FROM EMP
WHERE ROWID IN
(SELECT ROWID FROM EMP
WHERE ROWNUM <= 7
MINUS
SELECT ROWID FROM EMP
WHERE ROWNUM < 5);
OR
SELECT ename
FROM emp
GROUP BY ROWNUM, ename
HAVING ROWNUM > 1 and ROWNUM < 3;
41. Query to count no. Of columns in a table:
SELECT COUNT(column_name)
FROM user_tab_columns
WHERE table_name = 'MYTABLE';
[Link] between SQL and MS-Access :
Difference 1:
Oracle : select name from table1 where name like 'k%';
Access: select name from table1 where name like 'k*';
Difference 2:
Access: SELECT TOP 2 name FROM Table1;
Oracle : will not work there is no such TOP key word.
49. Query to display random number between any two given numbers :
SELECT DBMS_RANDOM.VALUE (1,2) FROM DUAL;
50. How can I get the time difference between two date columns :
SELECT
FLOOR((date1-date2)*24*60*60)/3600)
|| ' HOURS ' ||
FLOOR((((date1-date2)*24*60*60) -
FLOOR(((date1-date2)*24*60*60)/3600)*3600)/60)
|| ' MINUTES ' ||
ROUND((((date1-date2)*24*60*60) -
FLOOR(((date1-date2)*24*60*60)/3600)*3600 -
(FLOOR((((date1-date2)*24*60*60) -
FLOOR(((date1-date2)*24*60*60)/3600)*3600)/60)*60)))
|| ' SECS ' time_difference
FROM my_table;
51. Using INSTR and SUBSTR
I have this string in a column named location
LOT 8 CONC3 RR
Using instr and substr, I want to take whatever value follows LOT and put
it into a different column and whatever value follows CONC and put it into
a different column
select substr('LOT 8 CONC3 RR',4,instr('LOT 8 CONC3 RR','CONC')-4) from
dual;
select substr('LOT 8 CONC3 RR',-(length('LOT 8 CONC3 RR')-(instr('LOT 8
CONC3 RR','CONC')+3)))
from dual
53. To convert signed number to number in oracle
select to_number('-999,999.99', 's999,999.99') from dual; -999,999.99
select to_number('+0,123.45', 's999,999,999.99') from dual; 123.45
select to_number('+999,999.99', 's999,999.99') from dual; 999,999.99
54. Columns of a table
select column_name from user_tab_columns where TABLE_NAME = 'EMP'
select column_name from all_tab_columns where TABLE_NAME = 'EMP'
select column_name from dba_tab_columns where TABLE_NAME = 'EMP'
select column_name from cols where TABLE_NAME = 'EMP'
55. Delete rows conditionally
I have a table have
a,b,c field,
a,b should be unique, and leave max(c) row in.
How can I delete other rows?
delete from 'table'
where (a,b,c) not in (select a,b,max(c) from 'table' group by a,b);
60. Table comparison
The table in both the schemas should have exactly the same structure. The data in
it could be same or different
a-b and b-a
select * from a.a minus select * from b.a and select * from b.a minus select * from a.a
61. Running Jobs
select * from user_jobs;
exec dbms_job.remove(job_no);
62. Switching Columns
Update tblname
Set column1 = column2,
Column2 = column1;
63. Replace and Round
I have the number e.g. 63,9823874012983 and I want to round it to 63,98 and at the same
time change the , to a .
select round(replace('63,9823874012983',',','.'),2) from dual;
64. First date of the year
select trunc(sysdate, 'y') from dual;
01-jan-2002
last year this month through a select statement
select add_months(sysdate, -12) from dual;
05-APR-01
65. Create Sequence
create sequence sh increment by 1 start with 0;
66. Cursors
cursor is someting like pointers in C language.
u fetch the data using cursor.( wiz...store it somewhere temporarily). u
can do any manipulation to the data that is fetched by the cursor. like
trim, padd, concat or validate. all this are done in temporary areas called
as context area or the cursor area. u can insert this data again in some
other table or do anything u want!!...like setting up some flags etc.
U can display the contents of cursor using the dbms_output only. U can
create an anonymous plsql block or a stored procedure. the major advantage
of cursors is that you can fetch more thatn one row and u can loop through
the resultset and do the manupulations in a secure manner.
set serveroutput on;
declare
cursor c1 is select * from emp;
begin
for var in c1 loop
exit when c1%notfound;
dbms_output.put_line('the employee' || [Link] ||'draws a
salary of '|| [Link]);
end loop;
end;
67. Current Week
select next_day(sysdate-7,'SUNDAY'), next_day(sysdate,'SATURDAY') from dual;
NEXT_DAY( NEXT_DAY(
--------- ---------
07-APR-02 13-APR-02
Q: What is the relationship between primary and foreign keys?
A: Relationships between two tables are normally established by defining
primary or foreign keys. It will establish a child and parent relationships. A
foreign key is a column in a table (child) that references to a primary key
column in another table (parent).
Q: Describe the Entity Relationship diagram and Logical Data Model.
A: "Entity Relationship Diagram" or "Logical Data Model" is used to establish
relationships between entities.
Q: What is a composite index?
A: If an index key or a primary key were composed of more than one column. We
call it a composite index.
Q: What are the responsibilities of an Oracle DBA and Oracle Developer?
A: The integrity, security, connectivity, performance, and tuning of a database
will be maintained by DBAs. One of the responsibilities of a DBA is to plan a
contingency for disaster and ensure recovery of the database. On the other hand
developers use front-end and back-end tools along with management tools to
perform their tasks. They develop applications to manipulate a database’s data.
Their application will query, insert, delete and update a record or records. They
use front-end tools such as "form builder," "report builder," and "graphics
builder." They use back-end tools such as "schema builder," "procedure builder,"
and "query builder." They use project builder tools to manage and deliver their
applications to their clients.
Q: What is a Database?
A: A collection of all tables under a single or many different schemas can be
stored and maintained in a database. A database, in effect, is a collection of
objects such as tables, indexes, stored procedures, etc.
Q: Query the employee names and their salaries from the employee table.
A: SQL > SELECT ename, sal FROM emp;
Q: Do the above query and use an “as” clause for the “salary” column aliases orcolumn headings.
A: SQL > SELECT ename, sal AS salary FROM emp;
Q: Repeat the previous query and have “Full Name” for the ename’s column
heading and “Salary” for the “sal” column heading.
A: SQL > SELECT ename “Full Name”, sal "Salary"
FROM emp;
Q: What is the result of 100 + NULL ?
A: NULL.
Q: Query the employee names with their commissions.
A: SQL > SELECT ename, comm commission FROM emp;
Q: Use the (NVL ) the null value function to assign zero to any null value in
the commission column for the previous query.
A: SQL > SELECT ename, NVL(comm,0) commission
FROM emp;
Q: Concatenate the customers’ last name and first name separated by comma.
A: SQL > SELECT last_name || ', ' || first_name AS "full name"
FROM customers;
Q: Query the employees name sorted by ascending order.
A: SQL > SELECT ename
FROM emp
ORDER BY ename ASC;
Q: Query the employees name sorted by descending order.
A: SQL > SELECT ename FROM emp
ORDER BY ename DESC;
Q: Query the employee information whose employee number is 7788.
A: SQL > SELECT *
FROM emp
WHERE empno = 7788;
Q: Query the employees name whose names start with the letter “M.”
A: SQL > SELECT ename
FROM emp
WHERE ename LIKE 'M%';
Q: Query the employees name whose names end with the letter “R.”
A: SQL > SELECT ename
FROM emp
WHERE ename LIKE '%R';
Q: Query the employees name whose salaries between 2000 and 3000 dollars.
A: SQL > SELECT ename
FROM emp
WHERE sal BETWEEN 2000 AND 3000;
Q: Query the employees name and their department name using the “DECODE”
function. If the department number is 10 then print "accounting.” If the
department number is 20 then print "research," or if the department number is 30
then print "sales." Anything else prints others.
A: SQL > SELECT ename, DECODE (deptno, 10, 'Accounting',
20,
'Research',
30,
'Sales',
'Others') AS "Department"
FROM emp;
Q: What is an ambiguous column?
A: An ambiguous column is a column that is not defined clearly. Having two
tables with the same column name, you should reference them such that there is noambiguity on
their ownerships.
Q: How can you resolve an ambiguous column problem?
A: The column name should be identified by alias to make it clear that to what
table that column is belong.
Q: What is a Cartesian product?
A: A “Cartesian” product is caused by joining “N” number of tables while you
have less than “N-1” joins condition in the query.
Q: How can you avoid a Cartesian product ?
A: To avoid it, just when joining “N” number of tables you should have more or
equal “N-1” joins condition in the query.
Q: What is an inner join or equi-join?
A: Joining two or more tables together using the WHERE clause with the equal
sign (=) in a query. This type of query will retrieve records that have exact
match and will be called inner join or equi-join.
Q: What is an outer join?
A: Joining two or more tables using OUTER join, not only you retrieve all
matching records but also you retrieve the records that do not match.
Q: What is a self join?
A: When a table refers to itself in the WHERE clause, we call that join is a
self-join.
Q: Query all the employee names and their department including all the
departments with no employees.
A: SQL > SELECT ename, dname
FROM emp e, dept d
WHERE [Link] (+) = [Link];
Q: Query the managers’ name with their employees sorted by the manager name.
A: SQL > SELECT [Link] “Manager Name”, [Link] “Employee Name”
FROM emp mgr, emp e
WHERE [Link] = [Link]
ORDER BY [Link];
Q: Query the department number and their total, average, min, and max salaries
for each department.
A: SQL > SELECT deptno, SUM(sal), AVG(sal), MIN(sal), MAX(sal)
FROM emp
GROUP BY deptno;
Q: Query the department no and their total salaries that have more than 5
employees working in their department.
A: SQL > SELECT deptno, SUM(sal)
FROM emp
GROUP BY deptno
HAVING count(*) > 5;
Q: Query the employees name that work for the Research or Sales department (the
department number 20 or 30).
A: SQL > SELECT ename, deptno
FROM emp
WHERE deptno IN (20, 30);
Q: Query the employees name that work in the "accounting" department. Assuming
the department number is unknown.
A: SQL > SELECT ename
FROM emp
WHERE deptno IN
(SELECT deptno
FROM dept
WHERE dname = "ACCOUNTING");
Q: Query the employees name and use the runtime variable to substitute the
department number? Then run it for following department no 10, 20, and 30.
A: SQL > SELECT ename
FROM emp
WHERE deptno = &deptno;
SQL > /
Q: Query the customer names which have more than four orders.
A: SQL > SELECT name
FROM customer c
WHERE exists
(SELECT 'T'
FROM ord
WHERE custid = [Link]
GROUP BY custid
HAVING count(*) > 4);
Q: Create an employee table that contains five columns:
Such as Employee Id, last name, First name, Phone number and Department number
with the following constraints.
The last name and first name should be not null.
Make a check constraint to check the department number is between 9 and 100.
Make a primary constraint on the employee ID column.
Make a foreign key on the department number column.
Use the "delete cascade" to delete all records if parent gets deleted.
Use the "phone number" as a unique key.
A: SQL > CREATE TABLE employee
(empid NUMBER(10),
lastname VARCHAR2(20) not null,
firstname VARCHAR2 (20) not null,
phone_no VARCHAR2 (15),
deptno NUMBER(2) CHECK (deptno BETWEEN 9 AND 100),
constraint pk_employee_01 PRIMARY KEY (empid),
constraint fk_dept_01 FOREIGN KEY (deptno)
references dept (deptno) ON DELETE CASCADE,
constraint uk_employee_01 UNQUE (phone_no));
Q: Create a composite index on the employee table that contains two index
columns (last name and first name).
A: SQL > CREATE INDEX employee_lname_fname_ind_01
ON employee (lastname, firstname);
Q: Query the tables that you as a user own.
A: SQL > SELECT table_name
FROM user_tables
ORDER BY table_name;
Q: Query the index tables that belong to the employee table and owns by the
iself user.
A: SQL > SELECT index_name, uniqueness
FROM user_indexes
WHERE table_name = 'EMPLOYEE';
Q: Change the size of the "column_name" to 30 characters logically (for display
only).
A: SQL > COLUMN column_name FORMAT a30
Q: Query the indexes columns of the employee table.
A: SQL > SELECT index_name, column_name, column_position
FROM user_ind_columns
WHERE table_name = 'EMPLOYEE';
Q: Insert a record into the "employee" table using column names.
A: SQL > INSERT INTO employee
(empid, lastname, deptno, firstname, phone_no)
VALUES (100, 'smith', 10,'joe', ‘7038212211');
Q: Insert a record using the column position format.
A: SQL> INSERT INTO employeeVALUES (200, 'KING', 'Allen', 5464327532, 10);
Q: How do you save the inserted transaction?
A: COMMIT;
Q: Change the "last_name" column value from “Smith” to “Judd” where the
"employee id" is 100.
A: SQL > UPDATE employee
SET lastname = 'Judd'
WHERE empid = 100;
Q: Delete all the employee records from the "employee" table using the delete
command and the truncate command.
A: SQL > DELETE FROM employee;
OR
SQL > TRUNCATE TABLE employee;
Q: How do you undo a transaction?
A: ROLLBACK;
Q: What is the difference between the delete statement and the truncate
statement?
A: Notice that the TRUNCATE command is a DDL statement and all DDL statements
have commit inclusive. That is why the ROLLBACK action after truncation does not
work. Also, if you want to delete all records from a table, you should use the
TRUNCATE statement. It will change the table watermark. The table watermark is an
address that indicates a last location of a record in a table. On the DELETE
statement the watermark will not change. But using the TRUNCATE statement will
change the watermark to the beginning of the table.
Q: Copy the “EMP” table to another table and name the new table "employee." In
the new employee table use the employee name, job, commission and department
number.
A: SQL > CREATE TABLE employee
AS SELECT ename, job, comm, deptno
FROM emp;
Q: Add a salary column to the employee table.
A: SQL > ALTER TABLE employee
ADD (salary NUMBER(8,2));
Q: Modify the "ename" column size from varchar10 to varchar15.
A: SQL > ALTER TABLE employee
MODIFY (ename VARCHAR2(15));
Q: Rename the "employee" table to the "iself_employee" table.
A: SQL > RENAME employee TO iself_employee;
Q: Create a view to display the employee names of the “Accounting” department
only.
A: SQL > CREATE VIEW employee_name
AS SELECT ename
FROM iself_employee
WHERE deptno = 10;
Q: Why do you use the view?
A: You use view to present rows and columns of a table in the way you want.
You may use it for security reason. For example, you may eliminate some rows and
columns that are very sensitive information. These changes are transparent to a
user.
Q: How do you compile the view?
A: SQL > ALTER VIEW employee_name COMPILE;
Q: How do you delete the view?
A: SQL > DROP VIEW employee_name;
Q: Create an index on the employee table on the ename column only and name it
employee_indx.
A: SQL > CREATE INDEX employee_indx
ON employee (ename);
Q: Reorganize the “employee_indx” index table.
A: SQL > ALTER INDEX employee_ indx REBUILD;
Q: Drop the employee_ename index table.
A: SQL > DROP INDEX employee_indx;
Q: Create a user with username “newuser” and password "newpass." Its default
tablespace should be the "iself_data" tablespace.
A: SQL > CREATE USER newuser IDENTIFIED BY by newpass
DEFAULT TABLESPACE iself_data;
Q: Grant the resource and connect roles to newuser.
A: SQL > GRANT resource, connect TO newuser;
Q: Change the newuser password to "mypass".
A: SQL > ALTER USER newuser IDENTIFIED BY mypass;
Q: Can the above new user access to any other user tables?
A: No.
Q: What is a public synonym?
A: It is a synonym that public users can use. We create public synonym so that
the users don’t need to type schema name to a table when they query the table.
Creating a public synonym does not mean that oracle users can access to that
table or object. Still the owner of the object has to grant access to a user on
its table.
Q: What is the syntax to create a public synonym?
A: SQL > CREATE PUBLIC SYNONYM employees FOR iself.iself_employee;
Q: What is the difference between public and private synonym?
A: The private synonym is only for the user who owns or created the synonym,
but the public synonym can be used by every users.
Q: Create and drop a private synonym.
A: SQL > CREATE SYNONYM emp_table FOR iself.iself_employee;
To drop:
SQL > DROP SYNONYM emp_table;
Q: Revoke an object privilege on a table from a user.
A: SQL > REVOKE UPDATE, SELECT ON employee FROM newuser;
Q: What does the LIST or ‘L’ command line editor?
A: It lists the current SQL statement that was typed in the Oracle buffer.
Q: What does the INSERT or ‘I’ command line editor?
A: It inserts a command in the Oracle buffer after the current active line
that was indicated with an *.
Q: What does the DEL or ‘D’ command line editor?
A: It deletes the current active line in the Oracle Buffer.
Q: How do you change a string in the Oracle Buffer?
A: First, mark the line as a current active line and then type the‘del’
command.
Q: How do you save the SQL script in the Oracle Buffer?
A: SQL> save c:\[Link]
Q: How do you open the SQL Script into the Oracle Buffer?
A: SQL> get c:\[Link]
Q: How do you use the notepad editor?
A: Just type: the ed command to open the default editor.
Q: What is [Link]?
A: The "[Link]" file is a place that into which SQL *PLUS stores the most
recently executed SQL statement.
Q: How do you change your text editor in the SQLPLUS tool?
A: Issue the define_editor='your editor' statement from the SQL *PLUS prompt.
Q: What does the ed command in the SQLPLUS tool?
A: We use the "ed" command, to open your default word editor.
Q: Can you have multiple SQL statements in the [Link] file?
A: No. You can only use one SQL statement at a time.
Q: How do you use the notepad editor as an independent tool in the SQLPLUS
utility?
A: Just open your notepad editor outside of your SQLPLUS.
Q: How do you execute or run a SQL script?
A: SQL> run c:\[Link] or start c:\myscript
Q: What is the SQL ANSI statement?
A: It is some standard roles that provided by American National Standards
Institute.
Q: What is the difference between the SQL ANSI statement and Original Oracle
statement?
A: The Original Oracle statements are not follow the role of American National
Standards Institute.
Q: Is the SET command a SQL statement?
A: No.
Q: How do you change your workstation’s page size or line size?
A: SQL > SET LINESIZE 100 PAGESIZE 55
Q: What does the JOIN syntax in the Oracle SQL (DML) statement?
A: It does innor join using the ON clause.
SQL > SELECT ename, [Link], dname
FROM emp JOIN dept
ON [Link] = [Link]
AND dname <> 'SALES'
/
Q: What is the difference between the JOIN syntax and the NATURAL JOIN syntax?
A: In the NATURAL JOIN syntax, you don't need the ON clause if the column’s
names are the same.
Q: What does the USING clause in the Oracle SQL statement?
A: It joins two tables and in the USING clause the join column names must be
the same.
Q: What is the advantage of the NATURAL JOIN syntax?
A: It is less typing.
Q: What does the CROSS JOIN syntax in the Oracle SQL statement?
A: We can use the Oracle9i ANSI standard CROSS JOIN syntax with no WHERE
clause to create a Cartesian product .
Q: What does the IN clause in the Oracle SQL statement?
A: The IN clause in the Oracle SQL statement is an equivalent of the OR
condition in the SQL statement.
Q: What do the OUTER JOIN, RIGHT OUTER JOIN, LEFT OUTER JOIN, and FULL OUTER
JOIN syntax in the Oracle SQL statement?
A: We use the OUTER option when we want all records that have exact match plus
those records that have no match.
Q: How can you perform the FULL OUTER JOIN syntax using the Original Oracle
syntax?
A: Although it is possible but it is very difficult to perform the full outer
join using the original Oracle syntax.
Q: When do you use the WITH … AS clause in the SQL statement?
A: If we have a query which it needs to process the same sub-query several
times, we should consider using the WITH …AS clause in our statement.
Q: How does the WITH … AS clause help your performance?
A: The query will create a temporary table to query it over and over.
Q: Write a query to list all the department names that their total paid
salaries are more than 1/3 of the total salary of the company.
A: SQL > WITH summary_totals AS
(SELECT dname,
SUM (sal) AS totals
FROM emp NATURAL JOIN dept
GROUP BY dname)
SELECT dname, totals
FROM summary_totals
WHERE totals > (SELECT SUM(totals)*1/3
FROM summary_totals)
ORDER BY totals DESC
SQL >/
Q: What are the multiple columns in the SQL statement? Where or how do you use
them?
A: We use multiple columns to match the multiple columns returned from the
sub-query.
Q: Write a SQL statement to query the name of all employees who earn the
maximum salary in their department using the multiple columns syntax.
A: SQL > SELECT deptno, ename, job, sal
FROM emp
WHERE (deptno, sal) IN
(SELECT deptno, MAX (sal)
FROM emp
GROUP BY deptno)
/
Q: What is the inline view in the Oracle SQL statement?
A: If we have a sub-query in a FROM clause in the Oracle SQL statement, is
called an inline view.
Q: Write a SQL statement to query all of the employee names, jobs, and salaries
where their salary is more than 10% of the total company paid salary.
A: SQL > SELECT ename, job, sal
FROM (SELECT ename, job, sal
FROM emp
WHERE sal > (SELECT SUM (sal) * .1
FROM emp)
ORDER BY 3)
/
Q: What does the MERGE statement in the SQL statement?
A: We use the MERGE statement to merge one table into another table.
Q: Can you update, insert, or delete any records while you are using the MERGE
statement?
A: Yes.
Q: What is a Materialized View?
A: A materialized view (MVIEW) is a replica of a target master from a single
point in time.
Q: What are the Materialized View types?
A: Read-Only Materialized Views
Updatable Materialized Views
Sub-query Materialized Views
Row-id vs. Primary Key Materialized Views
Q: Write the difference between ROWID and PRIMARY KEY in the Materialized View.
A: Fast refresh requires association between rows at snapshot and master sites.
Snapshots that use ROWIDs to refresh are called ROWID snapshots while those that
use primary keys are called primary key snapshots.
Q: What is the difference between a Materialized View and View?
A: A Materialized View is a physical duplicated data in a table, but a View is
just a logical presentation of a table.
Q: When or why do you use a Materialized View?
A: You use Materialized Views to create summaries in a data warehouse
environment or replicate a data in a distributed environment. In data warehouses,
you can use materialized views to pre-compute and store aggregated data such as
the sum of sales. In distributed environments, you can use materialized views to
replicate data from a master site to other distributed sites.
Q: What is a materialized view log?
A: A materialized view log is a holder that contains updated, inserted, or
deleted records’ information in the primary table.
Q: What are the PRIMARY KEY and ROWID in the Materialized View Log?
A: The Materialized View log that use ROWIDs to refresh are called ROWID view
log while those that use primary keys are called primary key view log.
Q: What does the USER_SNAPSHOT_LOGS view contain?
A: It shows if our log was created successfully and its name (MLOG$_EMP).
Q: Create a materialized view that contains the department number, number of
employees, and total salaries paid to employees by department.
A: SQL > CREATE MATERIALIZED VIEW mv_sal
BUILD IMMEDIATE
REFRESH ON DEMAND
AS SELECT deptno,
COUNT(1) AS no_of_emp, SUM (sal) AS salary
FROM emp
GROUP BY deptno
SQL> /
Q: Who can create a materialized view?
A: The one that was granted the CREATE MATERIALIZED VIEW privilege.
Q: What does the USER_MVIEWS view contain?
A: It contains all the Materialized Views’ information that were created by the
user.
Q: How do you refresh a materialized view?
A: SQL > EXECUTE dbms_snapshot.refresh('mv_sal','C');
Q: What parameter should be used to update the materialized view every month
automatically without human intervention?
A: The START WITH SYSDATE option will create an immediate data, and the
NEXT(SYSDATE+30) option will update the table every 30 days.
Q: What does the USER_JOBS view contain?
A: It contains all users’ jobs in the Oracle queue.
Q: How do you remove a job from the Oracle Job Queue?
A: SQL > EXECUTE dbms_job.remove(job_number);
Q: How do you drop a materialized view log and a materialized view?
A: SQL > DROP MATERIALIZED VIEW LOG ON emp;
To drop it:
SQL> DROP MATERIALIZED VIEW mv_sal;
Q: What does the BREAK ON clause in SQLPLUS?
A: It builds a break on a column.
Q: What do the REPHEADER and REPFOOTER commands in SQLPLUS?
A: They make a report header and footer.
Q: What does the following commands?
COLUMN sal HEADING 'Salary' FORMAT $99,999.99 --Creates heading format.
COLUMN ename HEADING 'Employee' FORMAT a20 – Creates heading format.
REPHEADER '' – Creates report heading.
BREAK ON dname SKIP 1 – Creates control bread on a column and skip 1 line after
the break.
COMPUTE SUM OF sal ON dname – Computes total salary within a department.
SPOOL c:\[Link] -- Activates spooling.
SPOOL OFF -- Deactivate spooling.
REPFOOTER '' – Creates report footer.
CLEAR BUFFER -- Clear the Oracle buffer.
CLEAR COLUMNS – Clears columns.
CLEAR COMPUTE -- Clears compute functions.
Q: What does the CLEAR command in SQLPLUS?
A: Note that all the values in REPHEADER , REPFOOTER , BUFFER, COLUMNS, COMPUTE
and etc are going to stay the same during your open session. In order to clean
them, you should use the CLEAR command for BUFFER, COLUMNS, and COMPUTE. And
input NULL to REPHEADER and REPFOOTER.
Q: What does the UNION statement in the SQL statement?
A: It will query all the records that match or not match with the base table.
Q: What does the INTERSET statement in the SQL statement?
A: It will query all the records that match with the base table. It is the same
as joining two tables.
Q: What does the MINUS statement in the SQL statement?
A: It will query all the records that are not matching against your base table.
Q: Why it is important to eliminate duplicate records?
A: To keep your database integrity.
Q: What does the following SQL statement?
SQL > DELETE FROM dup_emp
WHERE ROWID IN (SELECT MAX (ROWID)
FROM dup_emp
GROUP BY empno
HAVING COUNT (empno) > 1)
SQL> /
A: Deletes all the rows that have the same employee number except the first
one.
Q: What is a data partitioning in the Oracle database?
A: The data partitioning in the Oracle database is that the data will be
partitioned in multi-tablespaces for ease of maintenances.
Q: When should you use data partitioning?
A: When you have a huge data file and can be classified to some partitions.
Q: What is the advantage of using a data partitioning?
A: It is faster to access. It is easier to maintain.
Q: What is a partition key?
A: It is used to separate data and associates them to their own assigned
tablespace.
Q: What is a local index in the data partitioning?
A: A Local index is one that is partitioned exactly like the table to which it
belongs.
Q: What is a global index in the data partitioning?A: A Global index, unlike local indexes, you
should explicitly partition range
boundaries using the “VALUE LESS THAN” methods.
Q: What are the differences between local and global indexes?
A: In the local index you don’t define explicitly partition range.
Q: How does the ‘VALUE LESS THAN’ method work in the data partitioning?
A: The VALUES LESS THAN clause indicates the partition key value must be less
then its assigned value in order to be illegible for any DML transaction on its
assigned tablespace.
Q: Why do you need multiple tablespaces?
A: Multiple tablespaces give us more flexibility to maintain a tablespace
without affecting any performance or downtime to others.
Q: Create a range-based partitioning table named p_emp. Make sure that the data
entry of the each department goes to its own provided tablespaces such as the
accounting department goes to the dept10ts tablespace, the data entry of the
research department goes to the dept20ts tablespace, etc.
A: SQL > CREATE TABLE p_emp (
empno NUMBER(4) PRIMARY KEY ,
ename VARCHAR2 (10),
job VARCHAR2(9),
mgr NUMBER(4),
hiredate DATE ,
sale NUMBER(7,2),
comm NUMBER(7,2),
deptno NUMBER(2))
STORAGE (INITIAL 5K
NEXT 5K
PCTINCREASE 0)
PARTITION BY RANGE (deptno)
(PARTITION dept10
VALUES LESS THAN (20)
TABLESPACE dept10ts,
PARTITION dept20
VALUES LESS THAN (30)
TABLESPACE dept20ts,
PARTITION dept30
VALUES LESS THAN (40)
TABLESPACE dept30ts,
PARTITION deptxx
VALUES LESS THAN (MAXVALUE )
TABLESPACE deptxxts)
SQL > /
Q: What does the MAXVALUE parameter mean in the data partitioning?
A: It means as large as the column can hold.
Q: How do you analyze a partition table?
A: SQL > ANALYZE TABLE p_emp COMPUTE STATISTICS;
Q: What does the USER_TAB_PARTITIONS view contain?
A: A user can query its partitions table’s information that was created by the
user.
Q: Write a query to list the accounting employees from the partition table. Use
the partition option.
A: SQL > SELECT * FROM p_emp PARTITION (dept10);
Q: Write a query to list employee number 7900 from the sales department?
A: SQL > SELECT * FROM p_emp PARTITION (dept30)
WHERE empno = 7900
SQL> /
Q: How do you create a local partition index?
A: SQL > CREATE INDEX p_emp_ind ON p_emp (deptno) LOCAL;
Q: How do you analyze a partition table index?
A: SQL > ANALYZE INDEX p_emp_ind COMPUTE STATISTICS;
Q: What does the USER_IND_PARTITIONS view contain?
A: It contains information in regard to the user’s partition indexes.
Q: What does the ROLLUP operator?
A: The ROLLUP operator returns both ‘regular rows’ and ‘super-aggregate rows.’
Super-aggregate rows are rows that contain a sub-total value.
Q: What does the CUBE function?
A: The CUBE operator returns cross-tabulation values, thus produces totals in
all possible dimensions, and is used for warehousing aggregated data reports.
Q: What are the differences between the CUBE and ROLLUP functions?
A: See the output…
Q: What environments may use the CUBE and ROLLUP functions most?
A: Warehousing.
Q: Write a query to list an aggregation sum report for each job, in each year,
using the ROLLUP grouping option.
A: SQL > SELECT year, job, SUM (sal), COUNT(*)
FROM emp
GROUP BY ROLLUP (year, job)
SQL> /
Q: Write a query to list an aggregation sum report for each job, in each year,
using the CUBE grouping option.
A: SQL > SELECT year, job, SUM (sal), COUNT(*)
FROM emp
WHERE deptno = 20
GROUP BY CUBE (year, job)
SQL> /
Q: What is an object type?
A: The object type in the Oracle database is like the class eliminate in the
C++ developer tool or any object oriented tool.
Q: What is a collection object?
A: The collection object in the Oracle database is like a nested table and a
variable array in a table.
Q: Create an object type with two columns to hold the employee's child name and
date of birth and name it employee_kids .
A: SQL > CREATE TYPE employee_kids AS OBJECT (
NAME VARCHAR2 (30),
dob DATE
)
SQL> /
Q: Create a table type using employee_kids and name it employee_kids_table.
A: SQL > CREATE TYPE employee_kids_table
IS TABLE OF employee_kids;
Q: Create the emp_family table containing the kid’s column with a type of
employee_kids_table.
A: SQL > CREATE TABLE emp_family
(empno NUMBER,
kids employee_kids_table)
NESTED TABLE kids STORE AS nested_employee_kids_table
SQL> /
Q: How do you insert a record in the object type?
A: SQL > INSERT INTO emp_family VALUES
(7902,
employee_kids_table(employee_kids('David','08-AUG-01'),
employee_kids('Peter','10-JUN-88'),
employee_kids('Mark','30-OCT-92')
)
)
Q: What is the constructor?
A: The constructor creates an empty nested table as opposed to leaving it null.
Notice that without using the constructor, it is not possible to refer to the
nested table with the "THE" clause.
Q: What is the ‘THE’ sub-query?
A: To query a nested table you should use the "THE" clause. Also, the "THE"
sub-query is used to identify the nested table to INSERT INTO.
Q: How do you query a record using the ‘THE’ sub-query?
A: SQL > SELECT name
FROM
THE(SELECT kids FROM emp_family WHERE empno = 7788)
SQL> /
Q: What is a nested table?
A: It is a table within a table.
Q: How do you insert a record to a nested table?
A: SQL> INSERT INTO
THE(SELECT kids FROM emp_family
WHERE empno = 7900)
VALUES ('Sue','10-DEC-99');
Q: How do you update a record to nested table?
A: SQL > UPDATE emp_family
SET kids = employee_kids_table(
employee_kids('Sara','08-OCT-88'))
WHERE empno = 7788
SQL> /
Q: How do you add a unique index to a nested table?
A: SQL > CREATE UNIQUE INDEX i_nested_employee_kids_table
ON nested_employee_kids_table(nested_table_id,name)
SQL> /
Q: What is a data replica?
A: A duplicated data in a different location.
Q: What is the difference between a materialized view and a materialized view
log?
A: The Materialized view is a real duplicated data from a primary table but the
materialized view log is an on going logs generated due to the table changes
after the last refresh.
Q: What is an OID (Object ID)?
A: It is a unique ID assigned to an object by Oracle.
Q: How do you retrieve an object ID?
A: SQL > SELECT OWNER, TYPE_OID FROM DBA_TYPES
WHERE TYPE_NAME LIKE 'ADDRESS%';
Q: How do you use an object ID to create an object type?
A: SQL > CREATE OR REPLACE TYPE address_book_type_object
OID ‘XXXXXXXXXXXXXXXXXXXXX’
AS OBJECT (
id_address NUMBER(1),
address VARCHAR2 (20));
Q: What is the relationship between primary and foreign keys?
A: The relationships between two tables are normally established by defining
primary or foreign keys. A primary key has the immutable responsibility of
serving as a unique identifier in a table. A foreign key is a column that refers
to the primary key of another table. To join two tables, a “where clause” is used
to set up a table relationship between primary and foreign keys.
Q: What is a composite index?
A: A primary key can be composed of more than one column. We call it a
composite index.
Q: What is the result of 100 + NULL ?
A: NULL value.
Q: Write a query to concatenate the customers’ last name and first name
separated by comma.
A: SELECT last_name || ‘, ‘ || first_name
as “Full Name”
FROM customers
/
Q: Query the employees name and their department name using the “DECODE”
function. If the department number is 10 then print "accounting.” If the
department number is 20 then print "research," or if the department number is 30
then print "sales." Anything else prints others.
A: SELECT ename, DECODE (deptno, 10, 'Accounting',
20,
'Research',
30,
'Sales',
'Others') AS "Department"
FROM emp
/
Q: Query the department number and their total salaries that have more than 5
employees working in their department.
A: SELECT deptno, SUM(sal)
FROM emp
GROUP BY deptno
HAVING count(*) > 5
/
Q: query the customer names which have more than four orders.
A: SELECT name FROM customer c
WHERE exists (SELECT 'T' FROM ord
WHERE custid = [Link]
GROUP BY custid
HAVING count(*) > 4)
/
Q: Create an employee table that contains five columns:
Such as Employee Id, last name, First name, Phone number and Department number
with the following constraints.
The last name and first name should be not null.
Make a check constraint to check the department number is between 9 and 100.
Make a primary constraint on the employee ID column.
Make a foreign key on the department number column.
Use the "delete cascade" to delete all records if parent gets deleted.
Use the "phone number" as a unique key.
A: CREATE TABLE employee
(empid NUMBER(10),
lastname VARCHAR2(20) not null,
firstname VARCHAR2 (20) not null,
phone_no VARCHAR2 (15),
deptno NUMBER(2) CHECK (deptno BETWEEN 9 AND 100),
constraint pk_employee_01 PRIMARY KEY (empid),
constraint fk_dept_01 FOREIGN KEY (deptno)
references dept (deptno) ON DELETE CASCADE,
constraint uk_employee_01 UNQUE (phone_no))
Q: What is the difference between the delete statement and the truncate
statement?
A: On the DELETE statement the watermark will not change. But using the
TRUNCATE statement will change the watermark to the beginning of the table.
Q: Copy the “EMP” table to another table and name the new table "employee." In
the new employee table use the employee name, job, commission and department
number.
A: CREATE TABLE employee
AS SELECT ename, job, comm, deptno
FROM emp
/
Q: Reorganize the “employee_indx” index table.
A: ALTER INDEX employee_indx REBUILD
/
Q: What is the difference between public and private synonym?
A: You create synonym so that the users don’t need to type schema name to a
table when they query the table. The Public Synonym is available to all database
users but the Private Synonym is available only to the owner of synonym.
Q: Can you have multiple SQL statements in the [Link] file?
A: No.
Q: How do you execute or run a SQL script?
A: SQL> @my_sql_script; or start my_sql_script;
Q: Write a query to list all the department names that their total paid
salaries are more than 1/3 of the total salary of the company.
A: SQL > WITH summary_totals AS
(SELECT dname,
SUM (sal) AS totals
FROM emp NATURAL JOIN dept
GROUP BY dname)
SELECT dname, totals
FROM summary_totals
WHERE totals > (SELECT SUM (totals)*1/3
FROM summary_totals)
ORDER BY totals DESC
SQL >/
Q: What is a Materialized View?
A: A materialized view (MVIEW) is a replica of a target master from a single
point in time. You use Materialized Views to create summaries in a data warehouse
environment or replicate a data in a distributed environment. In data warehouses,
you can use materialized views to pre-compute and store aggregated data such as
the sum of sales. In distributed environments, you can use materialized views to
replicate data from a master site to other distributed sites.
Q: What does the following SQL statement?
SQL > DELETE FROM dup_emp
WHERE ROWID IN (SELECT MAX (ROWID)
FROM dup_emp
GROUP BY empno
HAVING COUNT (empno) > 1)
SQL> /
A: Deletes duplicated records.
Q: What does the MAXVALUE parameter mean in the data partitioning?
A: It is the maximum possible value that can be store into a column.
Q: What does the following SQL statement?
SQL > INSERT INTO THE(SELECT kids FROM emp_family
WHERE empno = 7900)VALUES ('Sue','10-DEC-99')
SQL > /
A: Inserts a record to a nested object in a table.
How can I format xxxxxxxxx like xxx-xx-xxxx in Oracle?
SELECT TO_CHAR(0123456789, '000g00g0000','nls_numeric_characters=.-') phone from
dual
PHONE
123-45-6789
SUBSTR(data, 1, 3) ||'-'||SUBSTR(data, 4, 2)||'-'||SUBSTR(data, 6, 4)
select substr(replace('999,999,9999', ',', ''), -3)||'-' ||substr(replace('999,999,9999', ',',
''),4,3)||'-'|| substr(replace('999,999,9999', ',', ''),7) phone from dual
with src as (select 123 area ,4506789 pnum from dual) SELECT area||'-'||
REGEXP_REPLACE(pnum,'([0-9]{3})([0-9]{4})','\1-\2') pnum from src;
Oracle’s default format for DATE is “DD-MON-YY”.
select sysdate, to_char(sysdate, 'DD/MM/YYYY') Date1,
to_char(sysdate, 'MM/DD/YYYY') Date2,
to_char(sysdate, 'DD/MM/YY') Date3 from dual;
SYSDATE DATE1 DATE2 DATE3
02-JUL-14 02/07/2014 07/02/2014 02/07/14
select replace('The wall has &number insects', '&') text from dual;
The wall has number insects
How to trim the number sequence???
SQL> select
trim(regexp_substr('45789321456697 | 57894632145698723654','[^|]+', 1, 1)) from
dual;
45789321456697
SQL>Select
trim(regexp_substr('45789321456697 |57894632145698723654','[^|]+', 1,2))
from dual;
57894632145698723654
Regular expressions use more CPU time than normal string functions. For basic string
manipulation it is better to use normal string functions, hence why I didn't post a regexp solution.
From the given SELECT statement I assume that your source string is mm\"ll''IP and the required
output is mm\\\\\\"ll\'IP
If this assumption is correct then try..
select regexp_replace('mm\"ll''IP','([^\]+)[\]([^'']+)[''](.*)','\1\\\\\\\\\\\\\2\\''\3') out_str
from dual
SQL> with sd
2 as
3 (
4 select 'bill@[Link], mark@[Link], david@[Link]' as email from dual union all
5 select 'vincent@[Link]; mark@[Link], david@[Link]' as email from dual union all
6 select 'sarah@[Link], hillary@[Link]' as email from dual
7 )
8 select email
9 , regexp_substr(email, '[^,;]+', 1) email_1
10 , substr(email, regexp_instr(email, '[;|,]')+1) email_2
11 from sd;
EMAIL EMAIL_1 EMAIL_2
------------- -------------------- --------------------------------------------------
bill@[Link], mark@[Link], david@[Link] bill@[Link] mark@[Link],
david@[Link]
vincent@[Link]; mark@[Link], david@[Link] vincent@[Link]
mark@[Link], david@[Link]
sarah@[Link], hillary@[Link] sarah@[Link] hillary@[Link]
How to display 1 to 10 numbers
Select level from dual connect by level<=10;
How to delete duplicates records
Delete emp where rowid not in (select min(rowid) from emp group by sal);
How to find highest salary in a table
Select * from emp where sal in (select max(sal) from emp);
How to find second highest salary
1. Select * from emp where sal=(select max(sal) from emp where sal <(select max(sal) from
emp));
2. Select * from (select sal,rank() over (order by sal desc) as rnk from (select distinct sal from
emp)) where rnk=2;
3. Select level,max(sal) from emp where level=&levelno connect by prior sal> sal group by level;
4. Select max(sal) from (select distinct sal from emp where sal not in (select max(sal) from emp));
5. Select sal from(select sal from (select distinct sal from emp order by sal desc) where
rownum<=2 order by sal asc) where rownum=1;
To find highest and lowest values
Select max(sal) from emp
Union
Select min(sal) from emp;
How to get fist and last record from a table in oracle?
Select * from EMP where rownum=1
Union
Select * from EMP where rowid=(select max(rowid) from EMP);
To find the count of duplicate rows
Select ename, count (*) from emp group by ename having count(*) >= 1;
To see the duplicate records
SELECT * FROM EMP WHERE (SAL IN (SELECT sal FROM emp GROUP BY sal HAVING COUNT(sal) >
1));
Query to find a_b format names
Select * from emp where ename like '%A_B%';
Difference between Case and Decode
CASE is a statement and DECODE is a function
We can use the CASE in the where clause and can not use the DECODE in the where clause.
DECODE can check equality operators only where as CASE can support all relational operators
DECODE can be used in sql only where as CASE can be used in SQL AND PL/SQL
CASE is better than DECODE.
Difference between SUB QUERY and JOIN
Sub query is use to retrieve data which have multiple conditions.
Join is use to give joint to 2 different table using a same field of different table it will retrieve data
from two different table.
Difference between count (1) and count (*)
count() executes faster when given a criteria/value which is quicker to resolve in the sql processing
[Link], an integer or rowid are faster to resolve than an '*'which is a wild card symbol for
all the colums in a table and hence it is more time consuming.
Lpad function to pad the left side of a column with any set of characters.
Ex: select lpad('computer',15,'*');
Rpad function to pad the right side of a column with any set of characters.
Ex: select rpad('computer',15,'*');
Nvl2 function contain 3 expressions ,null if function contain 2 expressions
Nvl2 function: syntax: nvl2(expr1 , expr2 , expr3 )
If expr 1 is not null nvl2 returns expr2. If expr1 is null nvl2 returns expr3.
Null if function: syntax null if (expr1 ,expr2)
Compares two expressions and returns null if they are equal or the first if they are not null.
The nvl function is used to convert a null value to an actual value.
Syntax: nvl(expr1 , expr2)
A subquery is a select statement that is embedded in a clause of another select statement. You
can build powerful statements out of simple once by using sub queries.
EX: select ename, sal from emp where sal >
(select sal from emp where ename ='FORD')
A correlated subquery is a subquery that is evaluated once for each row of the outer query.
The inner query executes first and finds a value, the outer query executes once using the value
from the inner query(subquery)
Fetch by the outer query, execute the inner query using the value of the outer query, use the
values resulting from the inner query to qulify or disqualify the outer query(correlated)
Complex Queries in Oracle
To fetch ALTERNATE records from a table. (EVEN NUMBERED )
Select *from emp where rowid in (select decode(mod(rownum,2),0,rowid, null) from emp);
To select ALTERNATE records from a table. (ODD NUMBERED)
select * from emp where rowid in (select decode(mod(rownum,2),0,null ,rowid) from emp);
Find the 3rd MAX salary in the emp table.
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where [Link] <=
[Link]);
Find the 3rd MIN salary in the emp table.
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2where [Link] >=
[Link]);
Select FIRST n records from a table.
select * from emp where rownum <= &n;
Select LAST n records from a table.
select * from emp minus select * from emp where rownum <= (select count(*) - &n from emp);
List dept no., Dept name for all the departments in which there are no employees in the
department.
select * from dept where deptno not in (select deptno from emp);
alternate solution: select * from dept a where not exists (select * from emp b where [Link] =
[Link]);
altertnate solution: select empno,ename,[Link],dname from emp a, dept b where [Link](+)
= [Link] and empno is null;
How to get 3 Max salaries ?
Select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where [Link] <=
[Link]) order by [Link] desc;
How to get 3 Min salaries ?
Select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where [Link] >=
[Link]);
How to get nth max salaries ?
Select distinct hiredate from emp a where &n = (select count(distinct sal) from emp b where [Link]
>= [Link]);
Select DISTINCT RECORDS from emp table.
select * from emp a where rowid = (select max(rowid) from emp b where [Link]=[Link]);
How to delete duplicate rows in a table?
Delete from emp a where rowid != (select max(rowid) from emp b where [Link]=[Link]);
Count of number of employees in department wise.
select count(EMPNO), [Link], dname from emp a, dept b where [Link](+)=[Link] group
by [Link],dname;
Suppose there is annual salary information provided by emp table. How to fetch
monthly salary of each and every employee?
Select ename,sal/12 as monthlysal from emp;
Select all record from emp table where deptno =10 or 40.
Select * from emp where deptno=30 or deptno=10;
Select all record from emp table where deptno=30 and sal>1500.
Select * from emp where deptno=30 and sal>1500;
Select all record from emp where job not in SALESMAN or CLERK.
Select * from emp where job not in ('SALESMAN','CLERK');
Select all record from emp where ename in 'BLAKE','SCOTT','KING'and'FORD'.
Select * from emp where ename in('JONES','BLAKE','SCOTT','KING','FORD');
Select all records where ename starts with ‘S’ and its lenth is 6 char.
Select * from emp where ename like's____';
Select all records where ename may be any no of character but it should end with ‘R’.
Select * from emp where ename like'%R';
Count MGR and their salary in emp table.
Select count(MGR),count(sal) from emp;
In emp table add comm+sal as total sal .
Select ename,(sal+nvl(comm,0)) as totalsal from emp;
Select any salary <3000 from emp table.
Select * from emp where sal> any(select sal from emp where sal<3000);
Select all salary <3000 from emp table.
Select * from emp where sal> all(select sal from emp where sal<3000);
Select all the employee group by deptno and sal in descending order.
Select ename,deptno,sal from emp order by deptno,sal desc;
How can I create an empty table emp1 with same structure as emp?
Create table emp1 as select * from emp where 1=2;
How to retrive record where sal between 1000 to 2000?
Select * from emp where sal>=1000 And sal<2000
Select all records where dept no of both emp and dept table matches.
Select * from emp where exists(select * from dept where [Link]=[Link])
If there are two tables emp1 and emp2, and both have common record. How can I fetch
all the recods but common records only once?
(Select * from emp) Union (Select * from emp1)
How to fetch only common records from two tables emp and emp1?
(Select * from emp) Intersect (Select * from emp1)
How can I retrive all records of emp1 those should not present in emp2?
(Select * from emp) Minus (Select * from emp1)
Count the totalsa deptno wise where more than 2 employees exist.
SELECT deptno, sum(sal) As totalsal
FROM emp
GROUP BY deptno
HAVING COUNT(empno) > 2
A) UID
This will returns the integer value corresponding to the user currently logged in.
Ex:
SQL> select uid from dual;
UID
----------
319
B) USER
This will returns the login’s user name.
Ex:
SQL> select user from dual;
USER
----------------
SAKETH
C) VSIZE
This will returns the number of bytes in the expression.
Ex:
SQL> select vsize(123), vsize('computer'), vsize('12-jan-90') from dual;
VSIZE(123) VSIZE('COMPUTER') VSIZE('12-JAN-90')
------------- ----------------------- ----------------------
3 8 9
D) RANK
This will give the non-sequential ranking.
Ex:
SQL> select rownum,sal from (select sal from emp order by sal desc);
ROWNUM SAL
---------- ----------
1 5000
2 3000
3 3000
4 2975
5 2850
6 2450
7 1600
8 1500
9 1300
10 1250
11 1250
12 1100
13 1000
14 950
15 800
SQL> select rank(2975) within group(order by sal desc) from emp;
RANK(2975)WITHINGROUP(ORDERBYSALDESC)
---------------------------------------------------------
4
D) DENSE_RANK
This will give the sequential ranking.
Ex:
SQL> select dense_rank(2975) within group(order by sal desc) from emp;
DENSE_RANK(2975)WITHINGROUP(ORDERBYSALDESC)
What is integrity constraints?
Integrity constraint is a rule that restricts values to a column in a table.
Difference between group function and analytic function?
Group functions returns one result per each group of the result set, where as analytical functions
returns multi rows per each group i.e. using analytical functions we may display group results
along with individual rows.
Difference between View and Materialized View in Oracle
Difference
View is a logical table Mv is a physical table
View can hold the query Mv can hold the query with refresh data
We can’t create indexes on view We can create indexes on mv
View will create security purpose Mv will create performance issues
What is Materialized View in Oracle
Materialized view is a physical table selective portion of the data from table’s periodically can be
seen, it is used to improve the performance, useful in distributed environment
REFRESH:
FAST REFRESH: Cannot work in complex query. This is only applicable for a simple query like one-
table access.
COMPLETE REFRESH: This requires the same amount of time recreating the materialized view
contents.
REFRESH FORCE: Refresh the materialized view as fast if there are tables which can satisfy the
conditions.
Procedure:
Procedure allow the DML statements without any restrictions
We can’t call procedure in sql language
We can store images in stored procedure
Function:
Function not allow the DML statements (If you need to use we can use pragma)
We can call Function in sql language
Function can’t store images
Group by clause tells oracle to group rows based on distinct values that exists for specified
columns. The group by clause creates a data set , containing several sets of records grouped
together based on condition.
Having Clause: Having clause can be used with GROUP BY clause. Having imposes a condition on
the group by clause which further filters the group created by the GROUP BY clause.
Ex: Select ename,empno From Empl Group by empno having empno > 10;
What are disadvantages of indexes?
Indexes slow down the data speed when dml operation is performed. Because main table and
index table maintained by oracle.
And also it’s an additional space occupied which in turn add maintenance efforts They increase the
disk space requirements of your database
They slow down dml (i.e. Inserts, updates and deletes)
They increase the maintenance requirements of your Oracle database
They may make your queries slower instead of faster
Oracle Analytic Functions
Ranking Functions
The Difference Type of Ranking Functions Is
1. RANK ( ) Function
2. DENSE RANK ( ) Function
PARTITION BY clause
3. ROLLUP
4. CUBE
5. GROUPING SETS
6. NULLS FIRST Clause
7. NULLS LAST Clause
8. CUME DIST ( ) Function
9 .PERCENT RANK ( ) Function
10. NTILE ( ) Function
11. ROW NUMBER ( ) Function
12. INVERSE PERCENTAGE Function
PERCENTILE DIST ( )
PERCENTILE COUNT ( )
Sql tuning/sql optimization techniques:
The sql query becomes faster if you use the actual columns names in select statement instead of
than '*'.
For example: write the query as
Select id, first_name, last_name, age, subject from student_details;
Instead of:
Select * from student_details;
Having clause is used to filter the rows after all the rows are selected. It is just like a filter. Do not
use having clause for any other purposes.
For example: write the query as
Select subject, count(subject)
From student_details
Where subject != 'science'
And subject != 'maths'
Group by subject;
Instead of:
Select subject, count(subject)
From student_details
Group by subject
Having subject!= 'vancouver' and subject!= 'toronto';
Sometimes you may have more than one subqueries in your main query. Try to minimize the
number of subquery block in your query.
For example: write the query as
Select name
From employee
Where (salary, age ) = (select max (salary), max (age)
From employee_details)
And dept = 'electronics';
Instead of:
Select name
From employee
Where salary = (select max(salary) from employee_details)
And age = (select max(age) from employee_details)
And emp_dept = 'electronics';
Use operator exists, in and table joins appropriately in your query.
A) usually in has the slowest performance.
B) in is efficient when most of the filter criteria is in the sub-query.
C) exists is efficient when most of the filter criteria is in the main query.
For example: write the query as
Select * from product p
Where exists (select * from order_items o
Where o.product_id = p.product_id)
Instead of:
Select * from product p
Where product_id in
(select product_id from order_items
Use exists instead of distinct when using joins which involves tables having one-to-many
relationship.
For example: write the query as
Select d.dept_id, [Link]
From dept d
Where exists ( select 'x' from employee e where [Link] = [Link]);
Instead of:
Select distinct d.dept_id, [Link]
From dept d,employee e
Where [Link] = [Link];
Try to use union all in place of union.
For example: write the query as
Select id, first_name
From student_details_class10
Union all
Select id, first_name
From sports_team;
Instead of:
Select id, first_name, subject
From student_details_class10
Union
Select id, first_name
From sports_team;
Be careful while using conditions in where clause.
For example: write the query as
Select id, first_name, age from student_details where age > 10;
Instead of:
Select id, first_name, age from student_details where age != 10;
Write the query as
Select id, first_name, age
From student_details
Where first_name like 'chan%';
Instead of:
Select id, first_name, age
From student_details
Where substr(first_name,1,3) = 'cha';
Write the query as
Select id, first_name, age
From student_details
Where first_name like nvl ( :name, '%');
Instead of:
Select id, first_name, age
From student_details
Where first_name = nvl ( :name, first_name);
Write the query as
Select product_id, product_name
From product
Where unit_price between max(unit_price) and min(unit_price)
Instead of:
Select product_id, product_name
From product
Where unit_price >= max(unit_price)
And unit_price <= min(unit_price)
Write the query as
Select id, name, salary
From employee
Where dept = 'electronics'
And location = 'bangalore';
Instead of:
Select id, name, salary
From employee
Where dept || location= 'electronicsbangalore';
Use non-column expression on one side of the query because it will be processed earlier.
Write the query as
Select id, name, salary
From employee
Where salary < 25000;
Instead of:
Select id, name, salary
From employee
Where salary + 10000 < 35000;
Write the query as
Select id, first_name, age
From student_details
Where age > 10;
Instead of:
Select id, first_name, age
From student_details
Where age not = 10;
Use decode to avoid the scanning of same rows or joining the same table repetitively. Decode
can also be made used in place of group by or order by clause.
For example: write the query as
Select id from employee
Where name like 'ramesh%'
And location = 'bangalore';
Instead of:
Select decode(location,'bangalore',id,null) id from employee
Where name like 'ramesh%';
To store large binary objects, first place them in the file system and add the file path in the
database.
To write queries which provide efficient performance follow the general sql standard rules.
Use single case for all sql verbs
Begin all sql verbs on a new line
Separate all words with a single space
Right or left aligning verbs within the initial sql verb