Tuesday, 23 September 2014

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
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'
2
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
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
3
(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
Database SQL Queries Interview Questions and answers on "SQL
Order By"
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 Queries Interview Questions and Answers on "SQL Where
Condition" - Examples
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')
4
SQL Queries Interview Questions and Answers on "SQL Wild Card
Search" - Examples
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 Queries Interview Questions and Answers on "SQL Pattern
Matching" - Examples
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
5
29. Get employee details from employee table whose name is 'John'
and 'Michael'
Select * from EMPLOYEE where FIRST_NAME in ('John','Michael')
SQL Queries Interview Questions and Answers on "SQL DATE
Functions" - Examples
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
6
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
7
“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()
SQL Queries Interview Questions and Answers on "SQL Escape
Characters" - Examples
39. 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 '%[%]%'
8
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
SQL Queries in SQL Server and MySQL, Select
REPLACE(LAST_NAME,'%',' ') from employee
SQL Queries Interview Questions and Answers on "SQL Group By
Functions" - Examples
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" - Examples
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
9
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')
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
SQL Queries Interview Questions and Answers on "SQL Joins" -
Examples
10
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.
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
53. Select first_name, incentive amount from employee and incentives
table for all employees who got incentives using left join
11
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
54. 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
Advanced SQL Queries Interview Questions and Answers on "Top N
Salary" - Examples
55. Select TOP 2 salary from employee table
SQL Queries in Oracle, select * from (select * from employee order by
SALARY desc) where rownum < 3
12
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
56. 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
57. 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
58. 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
13
SQL Queries in MySQL, select min(SALARY) from (select * from
employee order by salary desc limit N) a
SQL Queries Interview Questions and Answers on "SQL Union" -
Examples
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.
"Advanced SQL Queries Interview Questions and Answers"
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
14
"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 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.
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
15
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
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.
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
16
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' )
SQL Queries Interview Questions and Answers on "SQL Table
Scripts" - Examples
17
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) )
SQL Server -
CREATE TABLE EMPLOYEE(
EMPLOYEE_ID int NOT NULL,
FIRST_NAME varchar(50) NULL,
LAST_NAME varchar(50) NULL,
SALARY decimal(18, 0) NULL,
JOINING_DATE datetime2(7) default getdate(),
18
DEPARTMENT varchar(50) NULL)
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
19
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
20
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.
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 :
21
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 :
SELECT DeptID, MAX(Salary) FROM Employee GROUP BY DeptID.
Question 3:Write SQL Query to display current date.
Ans:SQL has built in function called GetDate() which returns current
timestamp.
SELECT GetDate();
Question 4:Write an SQL Query to check whether date passed to
Query is date of given format or not.
Ans: 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.
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.
Ans:
SELECT DISTINCT EmpName FROM Employees WHERE
DOB BETWEEN ‘01/01/1960’ AND ‘31/12/1975’;
22
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’
Ans: 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
upper('joe%');
Question 10: Write a SQL Query to find year from date.
Answer : SELECT YEAR(GETDATE()) as "Year";
Top 20 SQL Interview Questions with Answers
Last Updated on Saturday, 29 June 2013 12:21
Written by Super User
SQL is a language for accessing and manipulating database standardized
by ANSI. To be successful with database-centric applications (which
includes most of the applications Data Warehousing domain), one must be
strong enough in SQL. In this article, we will learn more about SQL by
23
breaking the subject in the form of several question-answer sessions
commonly asked in Interviewes.
SET UP OF SAMPLE DATA FOR PRACTICING SQL
For the purpose of our demonstration, we will primarily use two database
tables with just a few records - EMPLOYEE table and DEPT table.
EMPLOYEE table will contain 10 records pertaining to 10 employees
with funny sounding names of an imaginary organization and DEPT or
Department table will contain 5 departments of that organization. Click
here to download the DDL/INSERT statements for this data if you want to
practice the below SQLs in your personal computer
Contents of these tables are not same with Oracle emp and dept tables!!
What is the difference between inner and outer join? Explain with
example.
Inner Join
Inner join is the most common type of Join which is used to combine the
rows from two tables and create a result set containing only such records
that are present in both the tables based on the joining condition
(predicate).
Inner join returns rows when there is at least one match in both tables
If none of the record matches between two tables, then INNER JOIN will
return a NULL set. Below is an example of INNER JOIN and the resulting
set.
SELECT dept.name DEPARTMENT, emp.name EMPLOYEE
FROM DEPT dept, EMPLOYEE emp
WHERE emp.dept_id = dept.id
Department Employee
HR Inno
24
HR Privy
Engineering Robo
Engineering Hash
Engineering Anno
Engineering Darl
Marketing Pete
Marketing Meme
Sales Tomiti
Sales Bhuti
Outer Join
Outer Join can be full outer or single outer
Outer Join, on the other hand, will return matching rows from both tables
as well as any unmatched rows from one or both the tables (based on
whether it is single outer or full outer join respectively).
Notice in our record set that there is no employee in the department 5
(Logistics). Because of this if we perform inner join, then Department 5
does not appear in the above result. However in the below query we
perform an outer join (dept left outer join emp), and we can see this
department.
SELECT dept.name DEPARTMENT, emp.name EMPLOYEE
FROM DEPT dept, EMPLOYEE emp
WHERE dept.id = emp.dept_id (+)
25
Department Employee
HR Inno
HR Privy
Engineering Robo
Engineering Hash
Engineering Anno
Engineering Darl
Marketing Pete
Marketing Meme
Sales Tomiti
Sales Bhuti
Logistics
The (+) sign on the emp side of the predicate indicates that emp is the
outer table here. The above SQL can be alternatively written as below
(will yield the same result as above):
SELECT dept.name DEPARTMENT, emp.name EMPLOYEE
FROM DEPT dept LEFT OUTER JOIN EMPLOYEE emp
ON dept.id = 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
26
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
27
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 dept.name DEPARTMENT, avg(emp.sal) AVG_SAL
FROM DEPT dept, EMPLOYEE emp
WHERE dept.id = emp.dept_id (+)
GROUP BY dept.name
HAVING AVG(emp.sal) > 80
28
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
29
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 e.name EMPLOYEE, m.name MANAGER
30
FROM EMPLOYEE e, EMPLOYEE m
WHERE e.mgr_id = m.id (+)
EMPLOYEE MANAGER
Pete Hash
Darl Hash
Inno Hash
Robo Hash
Tomiti Robo
Anno Robo
Privy Robo
Meme Pete
Bhuti Tomiti
Hash
The only reason we have performed a left outer join here (instead of
INNER JOIN) is we have one employee in this table without a manager
(employee ID = 1). If we perform inner join, this employee will not showup.
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.
31
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 o.name >= i.name) row_num
FROM EMPLOYEE o
order by row_num
NAME SAL ROW_NUM
Anno 80 1
Bhuti 60 2
Darl 80 3
Hash 100 4
Inno 50 5
Meme 60 6
Pete 70 7
Privy 50 8
Robo 100 9
Tomiti 70 10
32
The column that is used in the row number generation logic is called “sort
key”. Here sort key is “name” column. For this technique to work, the sort
key needs to be unique. We have chosen the column “name” because this
column happened to be unique in our Employee table. If it was not unique
but some other collection of columns was, then we could have used those
columns as our sort key (by concatenating those columns to form a single
sort key).
Also notice how the rows are sorted in the result set. We have done an
explicit sorting on the row_num column, which gives us all the row
numbers in the sorted order. But notice that name column is also sorted
(which is probably the reason why this column is referred as sort-key). If
you want to change the order of the sorting from ascending to descending,
you will need to change “>=” sign to “<=” in the query.
As I said before, this method is not very generic. This is why many
databases already implement other methods to achieve this. For example,
in Oracle database, every SQL result set contains a hidden column called
ROWNUM. We can just explicitly select ROWNUM to get sequence
numbers.
How to select first 5 records from a table?
This question, often asked in many interviews, does not make any sense to
me. The problem here is how do you define which record is first and
which is second. Which record is retrieved first from the database is not
deterministic. It depends on many uncontrollable factors such as how
database works at that moment of execution etc. So the question should
really be – “how to select any 5 records from the table?” But whatever it
is, here is the solution:
In Oracle,
SELECT *
FROM EMP
WHERE ROWNUM <= 5;
In SQL Server,
SELECT TOP 5 * FROM EMP;
33
Generic solution,
I believe a generic solution can be devised for this problem if and only if
there exists at least one distinct column in the table. For example, in our
EMP table ID is distinct. We can use that distinct column in the below way
to come up with a generic solution of this question that does not require
database specific functions such as ROWNUM, TOP etc.
SELECT name
FROM EMPLOYEE o
WHERE (SELECT count(*) FROM EMPLOYEE i WHERE i.name <
o.name) < 5
name
Inno
Anno
Darl
Meme
Bhuti
I have taken “name” column in the above example since “name” is
happened to be unique in this table. I could very well take ID column as
well.
In this example, if the chosen column was not distinct, we would have got
more than 5 records returned in our output.
Do you have a better solution to this problem? If yes, post your solution in
the comment.
34
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
name Sal ROWNUM_BY_SAL
Hash 100 1
Robo 100 2
Anno 80 3
Darl 80 4
Tomiti 70 5
Pete 70 6
Bhuti 60 7
Meme 60 8
35
Inno 50 9
Privy 50 10
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
name Sal RANK_BY_SAL
Hash 100 1
Robo 100 1
Anno 80 3
Darl 80 3
Tomiti 70 5
Pete 70 5
Bhuti 60 7
Meme 60 7
36
Inno 50 9
Privy 50 9
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
name Sal DENSE_RANK_BY_SAL
Hash 100 1
Robo 100 1
Anno 80 2
Darl 80 2
Tomiti 70 3
Pete 70 3
Bhuti 60 4
Meme 60 4
Inno 50 5
Privy 50 5

2 comments: