Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Complex Queries in SQL

The document provides a comprehensive guide on complex SQL queries commonly asked in Oracle interviews, including fetching alternate records, calculating maximum and minimum salaries, and handling duplicates. It also covers PL/SQL concepts such as transactions, cursor usage, and exception handling, along with differences between procedures and functions. Additionally, it discusses database triggers, rollback segments, and various SQL operations, making it a valuable resource for interview preparation.

Uploaded by

Rameshwar Alure
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Complex Queries in SQL

The document provides a comprehensive guide on complex SQL queries commonly asked in Oracle interviews, including fetching alternate records, calculating maximum and minimum salaries, and handling duplicates. It also covers PL/SQL concepts such as transactions, cursor usage, and exception handling, along with differences between procedures and functions. Additionally, it discusses database triggers, rollback segments, and various SQL operations, making it a valuable resource for interview preparation.

Uploaded by

Rameshwar Alure
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Complex Queries in SQL ( Oracle )

These questions are the most frequently asked in interviews.

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

1. 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.

2.
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where
e1.sal <= e2.sal);

Find the 3rd MIN salary in the emp table.

select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2where e1.sal
>= e2.sal);

3. Select FIRST n records from a table.


select * from emp where rownum <= &n;
4. Select LAST n records from a table
select * from emp minus select * from emp where rownum <= (select count(*) - &n
from emp);
5. 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
a.deptno = b.deptno);
altertnate solution: select empno,ename,b.deptno,dname from emp a, dept b where
a.deptno(+) = b.deptno 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
a.sal <= b.sal) order by a.sal desc;
How to get 3 Min salaries ?

select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b
where a.sal >= b.sal);

How to get nth max salaries ?

select distinct hiredate from emp a where &n = (select count(distinct sal) from emp b
where a.sal >= b.sal);

Select DISTINCT RECORDS from emp table.

select * from emp a where rowid = (select max(rowid) from emp b where
a.empno=b.empno);

How to delete duplicate rows in a table?

delete from emp a where rowid != (select max(rowid) from emp b where
a.empno=b.empno);

Count of number of employees in department wise.

select count(EMPNO), b.deptno, dname from emp a, dept b where


a.deptno(+)=b.deptno group by b.deptno,dname;

6. 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;

7. Select all record from emp table where deptno =10 or 40.

select * from emp where deptno=30 or deptno=10;

8. Select all record from emp table where deptno=30 and sal>1500.

select * from emp where deptno=30 and sal>1500;

9. Select all record from emp where job not in SALESMAN or CLERK.

select * from emp where job not in ('SALESMAN','CLERK');

10.Select all record from emp where ename in 'BLAKE','SCOTT','KING'and'FORD'.


select * from emp where ename in('JONES','BLAKE','SCOTT','KING','FORD');

11.Select all records where ename starts with ‘S’ and its lenth is 6 char.

select * from emp where ename like'S____';

12.Select all records where ename may be any no of character but it should end with ‘R’.

select * from emp where ename like'%R';

13.Count MGR and their salary in emp table.

select count(MGR),count(sal) from emp;

14.In emp table add comm+sal as total sal .

select ename,(sal+nvl(comm,0)) as totalsal from emp;

15.Select any salary <3000 from emp table.

select * from emp where sal> any(select sal from emp where sal<3000);

16.Select all salary <3000 from emp table.

select * from emp where sal> all(select sal from emp where sal<3000);

17.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;

18.How to retrive record where sal between 1000 to 2000?


Select * from emp where sal>=1000 And sal<2000
19.Select all records where dept no of both emp and dept table matches.
select * from emp where exists(select * from dept where emp.deptno=dept.deptno)
20.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)
21.How to fetch only common records from two tables emp and emp1?
(Select * from emp) Intersect (Select * from emp1)
22. How can I retrive all records of emp1 those should not present in emp2?
(Select * from emp) Minus (Select * from emp1)
23.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

ORACLE SQL PL/SQL Interview Questions

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------
What are the various types of queries ?
Answer: The types of queries are:
Normal Queries
Sub Queries
Co-related queries
Nested queries
Compound queries

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

What is a transaction ?
Answer: A transaction is a set of SQL statements between any two COMMIT and ROLLBACK statements.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What is implicit cursor and how is it used by Oracle ?
Answer: An implicit cursor is a cursor which is internally created by Oracle.It is created by Oracle for each
individual SQL.

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------
Which of the following is not a schema object : Indexes, tables, public synonyms, triggers and packages ?
Answer: Public synonyms

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What is PL/SQL?
Answer: PL/SQL is Oracle's Procedural Language extension to SQL.The language includes object oriented
programming techniques such as encapsulation, function overloading, information hiding (all but
inheritance), and so, brings state-of-the-art programming to the Oracle database server and a variety of
Oracle tools.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Is there a PL/SQL Engine in SQL*Plus?
Answer: No.Unlike Oracle Forms, SQL*Plus does not have a PL/SQL engine.Thus, all your PL/SQL are
send directly to the database engine for execution.This makes it much more efficient as SQL statements are
not stripped off and send to the database individually.

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

Is there a limit on the size of a PL/SQL block?


Answer: Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and the maximum code size is
100K.You can run the following select statement to query the size of an existing package or procedure. SQL> select *
from dba_object_size where name = 'procedure_name'

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------
Can one read/write files from PL/SQL?
Answer: Included in Oracle 7.3 is a UTL_FILE package that can read and write files.The directory you intend writing to
has to be in your INIT.ORA file (see UTL_FILE_DIR=...parameter).

Before Oracle 7.3 the only means of writing a file was to use DBMS_OUTPUT with the SQL*Plus SPOOL command.
DECLARE
fileHandler UTL_FILE.FILE_TYPE;
BEGIN
fileHandler := UTL_FILE.FOPEN('/home/oracle/tmp', 'myoutput','W');
UTL_FILE.PUTF(fileHandler, 'Value of func1 is %sn', func1(1));
UTL_FILE.FCLOSE(fileHandler);
END;

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------

How can I protect my PL/SQL source code?


Answer: PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQL programs to
protect the source code.This is done via a standalone utility that transforms the PL/SQL source code into
portable binary object code (somewhat larger than the original).This way you can distribute software
without having to worry about exposing your proprietary algorithms and methods.SQL*Plus and SQL*DBA
will still understand and know how to execute such scripts.Just be careful, there is no "decode" command
available. The syntax is: wrap name=myscript.sql

oname=xxxx.yyy

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in a procedure ? How ?
Answer: From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic SQL statements.
Eg: CREATE OR REPLACE PROCEDURE DYNSQL AS
cur integer;
rc integer;
BEGIN
cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur,'CREATE TABLE X (Y DATE)',

DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------

What are the various types of Exceptions ?


Answer: User defined and Predefined Exceptions.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can we define exceptions twice in same block ?
Answer: No.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What is the difference between a procedure and a function ?
Answer: Functions return a single variable by value whereas procedures do not return any variable by
value.Rather they return multiple variables by passing variables by reference through their OUT parameter.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can you have two functions with the same name in a PL/SQL block ?
Answer: Yes.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can you have two stored functions with the same name ?
Answer: Yes.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can you call a stored function in the constraint of a table ?
Answer: No.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What are the various types of parameter modes in a procedure ?
Answer: IN, OUT AND INOUT.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What is Over Loading and what are its restrictions ?
Answer: OverLoading means an object performing different functions depending upon the no.of parameters
or the data type of the parameters passed to it.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can functions be overloaded ?
Answer: Yes.

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------
Can 2 functions have same name & input parameters but differ only by return datatype
Answer: No.

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

What are the constructs of a procedure, function or a package ?


Answer: The constructs of a procedure, function or a package are :

variables and constants


cursors
exceptions

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

Why Create or Replace and not Drop and recreate procedures ?


Answer: So that Grants are not dropped.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can you pass parameters in packages ? How ?
Answer: Yes.You can pass parameters to procedures or functions in a package.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What are the parts of a database trigger ?
Answer: The parts of a trigger are:

A triggering event or statement


A trigger restriction
A trigger action

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

What are the various types of database triggers ?


Answer: There are 12 types of triggers, they are combination of :

Insert, Delete and Update Triggers.


Before and After Triggers.
Row and Statement Triggers.

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

What is the advantage of a stored procedure over a database trigger ?


Answer: We have control over the firing of a stored procedure but we have no control over the firing of a trigger.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What is the maximum no.of statements that can be specified in a trigger statement ?
Answer: One.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can views be specified in a trigger statement ?
Answer: No

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What are the values of :new and :old in Insert/Delete/Update Triggers ?
Answer: INSERT : new = new value, old = NULL
DELETE : new = NULL, old = old value
UPDATE : new = new value, old = old value

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------

What are cascading triggers? What is the maximum no of cascading triggers at a time?
Answer: When a statement in a trigger body causes another trigger to be fired, the triggers are said to be
cascading.Max = 32.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What are mutating triggers ?
Answer: A trigger giving a SELECT on the table on which the trigger is written.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What are constraining triggers ?
Answer: A trigger giving an Insert/Updat e on a table having referential integrity constraint on the triggering
table.

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

Describe Oracle database's physical and logical structure ?


Answer:

Physical : Data files, Redo Log files, Control file.


Logical : Tables, Views, Tablespaces, etc.

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

Can you increase the size of a tablespace ? How ?


Answer: Yes, by adding datafiles to it.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can you increase the size of datafiles ? How ?
Answer: No (for Oracle 7.0)
Yes (for Oracle 7.3 by using the Resize clause )

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What is the use of Control files ?
Answer: Contains pointers to locations of various data files, redo log files, etc.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What is the use of Data Dictionary ?
Answer: It Used by Oracle to store information about various physical and logical Oracle structures
e.g.Tables, Tablespaces, datafiles, etc

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What are the advantages of clusters ?
Answer: Access time reduced for joins.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What are the disadvantages of clusters ?
Answer: The time for Insert increases.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can Long/Long RAW be clustered ?
Answer: No.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can null keys be entered in cluster index, normal index ?
Answer: Yes.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can Check constraint be used for self referential integrity ? How ?
Answer: Yes.In the CHECK condition for a column of a table, we can reference some other column of the
same table and thus enforce self referential integrity.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What are the min.extents allocated to a rollback extent ?
Answer: Two

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What are the states of a rollback segment ? What is the difference between partly available and needs
recovery ?
Answer: The various states of a rollback segment are :

ONLINE
OFFLINE
PARTLY AVAILABLE
NEEDS RECOVERY
INVALID.

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------
What is the difference between unique key and primary key ?
Answer: Unique key can be null; Primary key cannot be null.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
An insert statement followed by a create table statement followed by rollback ? Will the rows be inserted ?
Answer: No.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can you define multiple savepoints ?
Answer: Yes.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can you Rollback to any savepoint ?
Answer: Yes.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What is the maximum no.of columns a table can have ?
Answer: 254.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What is the significance of the & and && operators in PL SQL ?
Answer: The & operator means that the PL SQL block requires user input for a variable.The && operator
means that the value of this variable should be the same as inputted by the user previously for this same
variable

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can you pass a parameter to a cursor ?
Answer: Explicit cursors can take parameters, as the example below shows.A cursor parameter can appear in
a query wherever a constant can appear.

CURSOR c1 (median IN NUMBER) IS


SELECT job, ename FROM emp WHERE sal > median;

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------

What are the various types of RollBack Segments ?


Answer: The types of Rollback sagments are as follows :

Public Available to all instances


Private Available to specific instance

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

Can you use %RowCount as a parameter to a cursor ?


Answer: Yes
----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Is the query below allowed :
Select sal, ename Into x From emp Where ename = 'KING' (Where x is a record of Number(4) and
Char(15))
Answer: Yes

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Is the assignment given below allowed :
ABC = PQR (Where ABC and PQR are records)
Answer: Yes

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Is this for loop allowed : For x in &Start..&End Loop
Answer: Yes

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
How many rows will the following SQL return : Select * from emp Where rownum < 10;
Answer: 9 rows

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
How many rows will the following SQL return : Select * from emp Where rownum = 10;
Answer: No rows

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Which symbol preceeds the path to the table in the remote database ?
Answer: @

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Are views automatically updated when base tables are updated ?
Answer: Yes

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can a trigger written for a view ?
Answer: No

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
If all the values from a cursor have been fetched and another fetch is issued, the output will be : error, last
record or first record ?
Answer: Last Record

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
A table has the following data : [[5, Null, 10]].What will the average function return ?
Answer: 7.5
----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Is Sysdate a system variable or a system function?
Answer: System Function

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Consider a sequence whose currval is 1 and gets incremented by 1 by using the nextval reference we get the
next number 2.Suppose at this point we issue an rollback and again issue a nextval.What will the output be ?
Answer: 3

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Definition of relational DataBase by Dr.Codd (IBM)?
Answer: A Relational Database is a database where all data visible to the user is organized strictly as tables
of data values and where all database operations work on these tables.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What is Multi Threaded Server (MTA) ?
Answer: In a Single Threaded Architecture (or a dedicated server configuration) the database manager
creates a separate process for each database user.But in MTA the database manager can assign multiple
users (multiple user processes) to a single dispatcher (server process), a controlling process that queues
request for work thus reducing the databases memory requirement and resources.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Which are initial RDBMS, Hierarchical & N/w database ?
Answer:

RDBMS - R system
Hierarchical - IMS
N/W - DBTG

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

Difference between Oracle 6 and Oracle 7


Answer:

ORACLE 7 ORACLE 6
Cost based optimizer Rule based optimizer
Shared SQL Area SQL area allocated for each user
Multi Threaded Server Single Threaded Server
Hash Clusters Only B-Tree indexing
Roll back Size Adjustment No provision
Truncate command No provision
Distributed Database Distributed Query
Table replication & snapshots No provision
Client/Server Tech No provision

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------

What is Functional Dependency?


Answer: Given a relation R, attribute Y of R is functionally dependent on attribute X of R if and only if each
X-value has associated with it precisely one -Y value in R

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What is Auditing ?
Answer: The database has the ability to audit all actions that take place within it. a) Login attempts, b)
Object Accesss, c) Database Action Result of Greatest(1,NULL) or Least(1,NULL) NULL

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
While designing in client/server what are the 2 imp.things to be considered ?
Answer: Network Overhead (traffic), Speed and Load of client server

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What are the disadvantages of SQL ?
Answer: Disadvantages of SQL are :

Cannot drop a field


Cannot rename a field
Cannot manage memory
Procedural Language option not provided
Index on view or index on index not provided
View updation problem

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

When to create indexes ?


Answer: To be created when table is queried for less than 2% or 4% to 25% of the table rows.

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------
How can you avoid indexes ?
Answer: To make index access path unavailable Use FULL hint to optimizer for full table scan Use INDEX or AND-
EQUAL hint to optimizer to use one index or set to indexes instead of another. Use an expression in the Where
Clause of the SQL.

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

What is the result of the following SQL : Select 1 from dual UNION Select 'A' from dual;
Answer: Error

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can database trigger written on synonym of a table and if it can be then what would be the effect if original
table is accessed.
Answer: Yes, database trigger would fire.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can you alter synonym of view or view ?
Answer: No

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can you create index on view
Answer: No.

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------
What is the difference between a view and a synonym ?
Answer: Synonym is just a second name of table used for multiple link of database.View can be created with many
tables, and with virtual columns and with conditions.But synonym can be on view.

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

What's the length of SQL integer ?


Answer: 32 bit length

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What is the difference between foreign key and reference key ?
Answer: Foreign key is the key i.e.attribute which refers to another table primary key. Reference key is the
primary key of table referred by another table.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Can dual table be deleted, dropped or altered or updated or inserted ?
Answer: Yes

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
If content of dual is updated to some value computation takes place or not ?
Answer: Yes

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
If any other table same as dual is created would it act similar to dual?
Answer: Yes

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
For which relational operators in where clause, index is not used ?
Answer: <> , like '%...' is NOT functions, field +constant, field||''

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
Assume that there are multiple databases running on one machine.How can you switch from one to another ?
Answer: Changing the ORACLE_SID

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------
What are the advantages of Oracle ?
Answer: Portability : Oracle is ported to more platforms than any of its competitors, running on more than 100
hardware platforms and 20 networking protocols. Market Presence : Oracle is by far the largest RDBMS vendor and
spends more on R & D than most of its competitors earn in total revenue.This market clout means that you are
unlikely to be left in the lurch by Oracle and there are always lots of third party interfaces available. Backup and
Recovery : Oracle provides industrial strength support for on-line backup and recovery and good software fault
tolerence to disk failure.You can also do point-in-time recovery. Performance : Speed of a 'tuned' Oracle Database
and application is quite good, even with large databases.Oracle can manage > 100GB databases. Multiple database
support : Oracle has a superior ability to manage multiple databases within the same transaction using a two-phase
commit protocol.

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------
What is a forward declaration ? What is its use ?
Answer: PL/SQL requires that you declare an identifier before using it.Therefore, you must declare a subprogram
before calling it.This declaration at the start of a subprogram is called forward declaration.A forward declaration
consists of a subprogram specification terminated by a semicolon.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
What are actual and formal parameters ?
Answer: Actual Parameters : Subprograms pass information using parameters.The variables or expressions
referenced in the parameter list of a subprogram call are actual parameters.For example, the following
procedure call lists two actual parameters named emp_num and amount:
Eg.raise_salary(emp_num, amount);Formal Parameters : The variables declared in a subprogram
specification and referenced in the subprogram body are formal parameters.For example, the following
procedure declares two formal parameters named emp_id and increase:
Eg.PROCEDURE raise_salary (emp_id INTEGER, increase REAL) IS current_salary REAL;

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

What are the types of Notation ?

Answer: Position, Named, Mixed and Restrictions.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------

What all important parameters of the init.ora are supposed to be increased if you want to increase the SGA
size ?
Answer: In our case, db_block_buffers was changed from 60 to 1000 (std values are 60, 550 & 3500)
shared_pool_size was changed from 3.5MB to 9MB (std values are 3.5, 5 & 9MB) open_cursors was
changed from 200 to 300 (std values are 200 & 300) db_block_size was changed from 2048 (2K) to 4096
(4K) {at the time of database creation}. The initial SGA was around 4MB when the server RAM was 32MB
and The new SGA was around 13MB when the server RAM was increased to 128MB.

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------

If I have an execute privilege on a procedure in another users schema, can I execute his procedure even
though I do not have privileges on the tables within the procedure ?
Answer: Yes

----------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------

What are various types of joins ?


Answer: Types of joins are:

Equijoins
Non-equijoins
self join
outer join

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

What is a package cursor ?


Answer: A package cursor is a cursor which you declare in the package specification without an SQL statement.The
SQL statement for the cursor is attached dynamically at runtime from calling procedures.

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------

If you insert a row in a table, then create another table and then say Rollback.In this case will the row be inserted ?
Answer: Yes.Because Create table is a DDL which commits automatically as soon as it is executed.The DDL commits
the transaction even if the create statement fails internally (eg table already exists error) and not syntactically.

Bottom of Form

Saturday, April 27, 2013

10 Frequently asked SQL Query Interview Questions


In this article I am giving some examples of SQL queries which is frequently asked when you
go for a programming interview, having one or two year experience on this field .Whether you
go for Java developer position or any other technology programmer position, may interviewer
expect you to answer basic questions from Database and SQL. It's also obvious that if you are
working from one or two years on any project there is good chance that you come across to
handle database, writing SQL queries to insert, update, delete and select records. One simple
but effective way to check candidate's SQL skill is by asking these types of simple query. They
are are neither very complex nor very big, but yet they cover all key concept a programmer
should know about SQL. These queries test your SQL skill on Joins, both INNER and OUTER
join, filtering records by using WHERE and HAVING clause, grouping records using GROUP BY
clause, calculating sum, average and counting records using aggregate function like AVG(), SUM()
and COUNT, searching records using wildcards in LIKE operator, searching records in a bound
using BETWEEN and IN clause, DATE and TIME queries etc. If you have faced any interesting
SQL query or you have any problem and searching for solution, you can post it here for
everyone's benefit.

SQL Query Interview Questions

Question 1: SQL Query to find second highest salary of Employee


Answer : There are many ways to find second highest salary of Employee in SQL, you can
either use SQL Join or Subquery to solve this problem. Here is SQL query using Subquery :

select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary)


from Employee );

See How to find second highest salary in SQL for more ways to solve this problem.

Question 2: SQL Query to find Max Salary from each department.


Answer : You can find maximum salary for each department by grouping all records by DeptId
and then using MAX() function to calculate maximum salary in each group or each
department.

SELECT DeptID, MAX(Salary) FROM Employee GROUP BY DeptID.

This questions become more interesting if Interviewer will ask you to print department name instead of department
id, in that case you need to join Employee table with Department using foreign key DeptID, make sure you do LEFT
or RIGHT OUTER JOIN to include departments without any employee as well. Here is the query

SELECT DeptName, MAX(Salary) FROM Employee e RIGHT JOIN Department d ON


e.DeptId = d.DeptID GROUP BY DeptName;

In this query we have use RIGHT OUTER JOIN because we need name of department from Department table which is
on right side of JOIN clause, even if there is no reference of dept_id on Employee table.
Question 3: Write SQL Query to display current date.
Answer : SQL has built in function called GetDate() which returns current timestamp. This will
work in Microsoft SQL Server, other vendors like Oracle and MySQL also has equivalent
functions.

SELECT GetDate();

Question 4: Write an SQL Query to check whether date passed to Query is date of
given format or not.

Answer : SQL has IsDate() function which is used to check passed value is date or not of
specified format ,it returns 1(true) or 0(false) accordingly. Remember ISDATE() is a
MSSQL function and it may not work on Oracle, MySQL or any other database but there would
be something similar.

SELECT ISDATE('1/08/13') AS "MM/DD/YY";

It will return 0 because passed date is not in correct format.

Question 5: Write a SQL Query to print the name of distinct employee whose DOB is
between 01/01/1960 to 31/12/1975.

Answer : This SQL query is tricky but you can use BETWEEN clause to get all records whose
date fall between two dates.

SELECT DISTINCT EmpName FROM Employees WHERE DOB BETWEEN ‘01/01/1960’


AND ‘31/12/1975’;

Question 6: Write an SQL Query find number of employees according to gender


whose DOB is between 01/01/1960 to 31/12/1975.
Answer :

SELECT COUNT(*), sex from Employees WHERE DOB BETWEEN '01/01/1960' AND
'31/12/1975' GROUP BY sex;

Question 7: Write an SQL Query to find employee whose Salary is equal or greater
than 10000.

Answer :

SELECT EmpName FROM Employees WHERE Salary>=10000;

Question 8: Write an SQL Query to find name of employee whose name Start with
‘M’
Answer :

SELECT * FROM Employees WHERE EmpName like 'M%';

Question 9: find all Employee records containing the word "Joe", regardless of
whether it was stored as JOE, Joe, or joe.
Answer :

SELECT * from Employees WHERE UPPER(EmpName) like '%JOE%';

Question 10: Write a SQL Query to find year from date.


Answer : Here is how you can find Year from a Date in SQL Server 2008

SELECT YEAR(GETDATE()) as "Year";

Question 11 : Write SQL Query to find duplicate rows in a database? and then write SQL
query to delete them?

Answer : You can use following query to select distinct records :

SELECT * FROM emp a WHERE rowid = (SELECT MAX(rowid) FROM EMP b WHERE
a.empno=b.empno)

to Delete:

DELETE FROM emp a WHERE rowid != (SELECT MAX(rowid) FROM emp b WHERE
a.empno=b.empno);

Question 12 : There is a table which contains two column Student and Marks, you need to find all the students,
whose marks are greater than average marks i.e. list of above average students.
Answer : This query can be written using sub query as shown below :

SELECT student, marks from table where marks > SELECT AVG(marks) from table)

Question 13 : How do you find all employees which are also manager? .
You have given an standard employee table with an additional column mgr_id, which contains employee id of
manager.
Answer : You need to know about self join to solve this problem. In Self Join, you can join two instances of same
table to find out additional details as shown below
SELECT e.name, m.name FROM Employee e, Employee m WHERE e.mgr_id = m.emp_id;

this will show employee name and manger name in two column e.g.

name manager_name
John David

One follow-up is to modify this query to include employees which doesn't have manager. To solve that, instead of
using inner join, just use left outer join, this will also include employees without managers.

Question 14 : You have a composite index of three columns, and you only provide value of two columns in WHERE
clause of a select query? Will Index be used for this operation? For example if Index is on EmpId, EmpFirstName
and EmpSecondName and you write query like

SELECT * FROM Employee WHERE EmpId=2 and EmpFirstName='Radhe'

If the given two columns are secondary index column then index will not invoke, but if the given 2 columns contain
primary index(first col while creating index) then index will invoke. In this case Index will be used because EmpId
and EmpFirstName are primary columns.

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"


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

Don't Miss - SQL and Database theory Interview Questions

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

SQL Server Equivalent of Oracle SUBSTR is SUBSTRING, Query : select


substring(FIRST_NAME,0,3) from employee

MySQL Server Equivalent of Oracle SUBSTR is SUBSTRING. In MySQL start position is 1,


Query : select substring(FIRST_NAME,1,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'
SQL Server Equivalent of Oracle INSTR is CHARINDEX, Query: Select
CHARINDEX('o',FIRST_NAME,0) from employee where first_name='John'

MySQL Server Equivalent of Oracle INSTR is LOCATE, Query: Select LOCATE('o',FIRST_NAME)


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

Oracle,MYSQL Equivalent of SQL Server Len is Length , Query :select length(FIRST_NAME)


from employee

SQL Server Equivalent of Oracle,MYSQL Length is Len, Query :select len(FIRST_NAME) from
employee

12. Get First_Name from employee table after replacing 'o' with '$'

select REPLACE(FIRST_NAME,'o','$') from employee


Immediate Job Openings in Java .Net C Developer C++ PHP DBA - Apply Now

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

SQL Server Equivalent of MySQL concat is '+', Query : Select FIRST_NAME + '_'
+LAST_NAME from EMPLOYEE

MySQL Equivalent of Oracle '||' is concat, Query : Select


concat(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

SQL Queries in SQL Server, select SUBSTRING (convert(varchar,joining_date,103),7,4) ,


SUBSTRING (convert(varchar,joining_date,100),1,3) , SUBSTRING
(convert(varchar,joining_date,100),5,2) from EMPLOYEE

SQL Queries in MySQL, select year(joining_date),month(joining_date), DAY(joining_date)


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

"SQL Where Condition" Interview Questions

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


Immediate Job Openings in Govt Bank Mechanical Civil Electrical Defence - Apply Now

"SQL Wild Card Search" Interview Questions

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'

"SQL Pattern Matching" Interview Questions

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”

SQL Queries in Oracle, Select * from EMPLOYEE where to_char(joining_date,'YYYY')='2013'

SQL Queries in SQL Server, Select * from EMPLOYEE where


SUBSTRING(convert(varchar,joining_date,103),7,4)='2013'

SQL Queries in MySQL, Select * from EMPLOYEE where year(joining_date)='2013'

31. 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'

SQL Queries in SQL Server, Select * from EMPLOYEE where


SUBSTRING(convert(varchar,joining_date,100),1,3)='Jan'

SQL Queries in MySQL, Select * from EMPLOYEE where month(joining_date)='01'

32. 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')

SQL Queries in SQL Server (Format - “MM/DD/YYYY”), Select * from EMPLOYEE where
joining_date <'01/01/2013'

SQL Queries in MySQL (Format - “YYYY-DD-MM”), Select * from EMPLOYEE where joining_date
<'2013-01-01'
33. 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')

SQL Queries in SQL Server and MySQL (Format - “MM/DD/YYYY”), Select * from EMPLOYEE
where joining_date >'01/31/2013'

SQL Queries in MySQL (Format - “YYYY-DD-MM”), Select * from EMPLOYEE where joining_date
>'2013-01-31'

35. 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

SQL Queries in SQL Server, Select convert(varchar(19),joining_date,121) from EMPLOYEE

SQL Queries in MySQL, Select CONVERT(DATE_FORMAT(joining_date,'%Y-%m-%d-%H:


%i:00'),DATETIME) from EMPLOYEE

36. Get Joining Date,Time including milliseconds from employee table

SQL Queries in Oracle, select to_char(JOINING_DATE,'dd/mm/yyyy HH:mi:ss.ff') from


EMPLOYEE . Column Data Type should be “TimeStamp”

SQL Queries in SQL Server, select convert(varchar,joining_date,121) from EMPLOYEE

SQL Queries in MySQL, Select MICROSECOND(joining_date) from EMPLOYEE

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

SQL Queries in SQL Server, select getdate()

SQL Query in MySQL, select now()

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
SQL Queries Interview Questions and Answers on "SQL Mathematical Operations using
Group By"

43. Get department,no of employees in a department,total salary with respect to a department from
employee table order by total salarydescending

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 salaryascending

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 salaryascending

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

SQL Queries in SQL Server, select datepart (YYYY,JOINING_DATE) Join_Year,datepart


(MM,JOINING_DATE) Join_Month,count(*) Total_Emp from employee group by
datepart(YYYY,JOINING_DATE), datepart(MM,JOINING_DATE)

SQL Queries in MySQL, select year (JOINING_DATE) Join_Year,month (JOINING_DATE)


Join_Month,count(*) Total_Emp from employee group by year(JOINING_DATE),
month(JOINING_DATE)

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 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.

50. 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 queries.We 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.

51. 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.

52. 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.

53. 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
SQL Queries in SQL Server and MySQL, SELECT case DEPARTMENT when 'Banking' then 'Bank
Dept' when 'Insurance' then 'Insurance Dept' when 'Services' then 'Services Dept' end
FROM EMPLOYEE

Explanation : Here "DECODE" keyword is used to specify the alias name. In oracle we had specify,
Column Name followed by Actual Name and Alias Name as arguments. In SQL Server and MySQL, we can
use the earlier switch case statements for alias names.

54. 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.

55. 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''')

56. Select Last Name from employee table which contain only numbers

Select * from EMPLOYEE where lower(LAST_NAME)=upper(LAST_NAME)

Explanation : 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.

57. 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 : 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.

58. Update incentive table where employee name is 'John'

update INCENTIVES set INCENTIVE_AMOUNT='9000' where EMPLOYEE_REF_ID=(select EMPLOYEE_ID


from EMPLOYEE where FIRST_NAME='John' )

Explanation : 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

59. 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

60. 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

61. 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

62. 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.
SQL Queries in Oracle, Select FIRST_NAME,nvl(INCENTIVE_AMOUNT,0) from employee a left
join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

SQL Queries in SQL Server, Select FIRST_NAME, ISNULL(INCENTIVE_AMOUNT,0) from employee


a left join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

SQL Queries in MySQL, Select FIRST_NAME, IFNULL(INCENTIVE_AMOUNT,0) from employee a


left join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

63. Select first_name, incentive amount from employee and incentives table for all employees who got
incentives using left join

SQL Queries in Oracle, Select FIRST_NAME,nvl(INCENTIVE_AMOUNT,0) from employee a right


join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

SQL Queries in SQL Server, Select FIRST_NAME, isnull(INCENTIVE_AMOUNT,0) from employee


a right join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

SQL Queries in MySQL, Select FIRST_NAME, IFNULL(INCENTIVE_AMOUNT,0) from employee a


right join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

64. Select max incentive with respect to employee from employee and incentives table using sub query

SQL Queries in Oracle, select DEPARTMENT,(select nvl(max(INCENTIVE_AMOUNT),0) from


INCENTIVES where EMPLOYEE_REF_ID=EMPLOYEE_ID) Max_incentive from EMPLOYEE

SQL Queries in SQL Server, select DEPARTMENT,(select ISNULL(max(INCENTIVE_AMOUNT),0)


from INCENTIVES where EMPLOYEE_REF_ID=EMPLOYEE_ID) Max_incentive from EMPLOYEE

SQL Queries in SQL Server, select DEPARTMENT,(select IFNULL (max(INCENTIVE_AMOUNT),0)


from INCENTIVES where EMPLOYEE_REF_ID=EMPLOYEE_ID) Max_incentive from EMPLOYEE

"Top N Salary" SQL Interview Questions and Answers

65. Select TOP 2 salary from employee table

SQL Queries in Oracle, select * from (select * from employee order by SALARY desc)
where rownum <3

SQL Queries in SQL Server, select top 2 * from employee order by salary desc

SQL Queries in MySQL, select * from employee order by salary desc limit 2

66. Select TOP N salary from employee table

SQL Queries in Oracle, select * from (select * from employee order by SALARY desc)
where rownum <N + 1

SQL Queries in SQL Server, select top N * from employee

SQL Queries in MySQL, select * from employee order by salary desc limit N

67. 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)

SQL Queries in SQL Server, select min(SALARY) from (select top 2 * from employee) a

SQL Queries in MySQL, select min(SALARY) from (select * from employee order by salary
desc limit 2) a

68. 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)

SQL Queries in SQL Server, select min(SALARY) from (select top N * from employee) a

SQL Queries in MySQL, select min(SALARY) from (select * from employee order by salary
desc limit N) a

"SQL Union" Query Interview Questions

69. Select First_Name,LAST_NAME from employee table as separate rows

select FIRST_NAME from EMPLOYEE union select LAST_NAME from EMPLOYEE

70. 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.

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 Procedure81. 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.

You might also like