Database/SQL Interview Questions and
Answers for Freshers, Experienced
1. What is DBMS ?
The database management system is a collection of
programs that enables user to store, retrieve, update and
delete information from a database.
2. What is RDBMS ?
Relational Database Management system (RDBMS) is a
database management system (DBMS) that is based on the
relational model. Data from relational database can be
accessed or reassembled in many different ways without
having to reorganize the database tables. Data from
relational database can be accessed using an API ,
Structured Query Language (SQL).
3. What is SQL ?
Structured Query Language(SQL) is a language designed specifically for
communicating with databases. SQL is an ANSI (American National Standards
Institute) standard.
4. What are the different type of SQL's statements ?
This is one of the most frequently asked SQL Interview
Questions for freshers. SQL statements are broadly
classified into three. They are
1. DDL – Data Definition Language
DDL is used to define the structure that holds the data. For example, Create,
Alter, Drop and Truncate table.
2. DML– Data Manipulation Language
DML is used for manipulation of the data itself. Typical operations are Insert,
Delete, Update and retrieving the data from the table. The Select statement is
considered as a limited version of the DML, since it can't change the data in the
database. But it can perform operations on data retrieved from the DBMS,
before the results are returned to the calling function.
3. DCL– Data Control Language
DCL is used to control the visibility of data like granting database access and set
privileges to create tables, etc. Example - Grant, Revoke access permission to
the user to access data in the database.
5. What are the Advantages of SQL ?
1. SQL is not a proprietary language used by specific database vendors.
Almost every major DBMS supports SQL, so learning this one language will
enable programmers to interact with any database like ORACLE, SQL ,MYSQL
etc.
2. SQL is easy to learn. The statements are all made up of descriptive English
words, and there aren't that many of them.
3. SQL is actually a very powerful language and by using its language elements
you can perform very complex and sophisticated database operations.
6. what is a field in a database ?
A field is an area within a record reserved for a specific piece of data.
Examples: Employee Name, Employee ID, etc.
7. What is a Record in a database ?
A record is the collection of values / fields of a specific entity: i.e. an Employee,
Salary etc.
8. What is a Table in a database ?
A table is a collection of records of a specific type. For example, employee table,
salary table etc.
9. What is a database transaction?
Database transaction takes database from one consistent
state to another. At the end of the transaction the system
must be in the prior state if the transaction fails or the
status of the system should reflect the successful
completion if the transaction goes through.
10. What are properties of a transaction?
Expect this SQL Interview Questions as a part of an any
interview, irrespective of your experience. Properties of the
transaction can be summarized as ACID Properties.
1. Atomicity
A transaction consists of many steps. When all the steps in a transaction get
completed, it will get reflected in DB or if any step fails, all the transactions are
rolled back.
2. Consistency
The database will move from one consistent state to another, if the transaction
succeeds and remain in the original state, if the transaction fails.
3. Isolation
Every transaction should operate as if it is the only transaction in the system.
4. Durability
Once a transaction has completed successfully, the updated rows/records must
be available for all other transactions on a permanent basis.
11. What is a Database Lock ?
Database lock tells a transaction, if the data item in questions is currently being
used by other transactions.
12. What are the type of locks ?
1. Shared Lock
When a shared lock is applied on data item, other transactions can only read the
item, but can't write into it.
2. Exclusive Lock
When an exclusive lock is applied on data item, other transactions can't read or
write into the data item.
13. What are the different type of normalization?
In database design, we start with one single table, with all possible columns. A
lot of redundant data would be present since it’s a single table. The process of
removing the redundant data, by splitting up the table in a well defined
fashion is called normalization.
1. First Normal Form (1NF)
A relation is said to be in first normal form if and only if all underlying domains
contain atomic values only. After 1NF, we can still have redundant data.
2. Second Normal Form (2NF)
A relation is said to be in 2NF if and only if it is in 1NF and every non key
attribute is fully dependent on the primary key. After 2NF, we can still have
redundant data.
3. Third Normal Form (3NF)
A relation is said to be in 3NF, if and only if it is in 2NF and every non key
attribute is non-transitively dependent on the primary key.
14. What is a primary key?
A primary key is a column whose values uniquely identify every row in a table.
Primary key values can never be reused. If a row is deleted from the table, its
primary key may not be assigned to any new rows in the future. To define a field
as primary key, following conditions had to be met :
1. No two rows can have the same primary key value.
2. Every row must have a primary key value.
3. The primary key field cannot be null.
4. Value in a primary key column can never be modified or updated, if any
foreign key refers to that primary key.
15. What is a Composite Key ?
A Composite primary key is a type of candidate key, which represents a set of
columns whose values uniquely identify every row in a table.
For example - if "Employee_ID" and "Employee Name" in a table is combined
to uniquely identify a row its called a Composite Key.
16. What is a Composite Primary Key ?
A Composite primary key is a set of columns whose values uniquely identify
every row in a table. What it means is that, a table which contains composite
primary key will be indexed based on the columns specified in the primary key.
This key will be referred in Foreign Key tables.
For example - if the combined effect of columns, "Employee_ID" and "Employee
Name" in a table is required to uniquely identify a row, its called a Composite
Primary Key. In this case, both the columns will be represented as primary key.
17. What is a Foreign Key ?
When a "one" table's primary key field is added to a related "many" table in order
to create the common field which relates the two tables, it is called a foreign key
in the "many" table.
For example, the salary of an employee is stored in salary table. The relation is
established via foreign key column “Employee_ID_Ref” which refers
“Employee_ID” field in the Employee table.
18. What is a Unique Key ?
Unique key is same as primary with the difference being the existence of null.
Unique key field allows one value as NULL value.
19. Define SQL Insert Statement ?
SQL INSERT statement is used to add rows to a table. For a full row insert, SQL
Query should start with “insert into “ statement followed by table name and
values command, followed by the values that need to be inserted into the table.
The insert can be used in several ways:
1. To insert a single complete row.
2. To insert a single partial row.
20. Define SQL Update Statement ?
SQL Update is used to update data in a row or set of rows specified in the filter
condition.
The basic format of an SQL UPDATE statement is, Update command followed
by table to be updated and SET command followed by column names and their
new values followed by filter condition that determines which rows should be
updated.
21. Define SQL Delete Statement ?
SQL Delete is used to delete a row or set of rows specified in the filter condition.
The basic format of an SQL DELETE statement is, DELETE FROM command
followed by table name followed by filter condition that determines which rows
should be updated.
22. What are wild cards used in database for Pattern
Matching ?
SQL Like operator is used for pattern matching. SQL 'Like'
command takes more time to process. So before using "like"
operator, consider suggestions given below on when and
where to use wild card search.
1) Don't overuse wild cards. If another search operator will
do, use it instead.
2) When you do use wild cards, try not to use them at the
beginning of the search pattern, unless absolutely
necessary. Search patterns that begin with wild cards are
the slowest to process.
3) Pay careful attention to the placement of the wild card
symbols. If they are misplaced, you might not return the
data you intended.
23. Define Join and explain different type of joins?
Another frequently asked SQL Interview Questions on Joins. In order to avoid
data duplication, data is stored in related tables. Join keyword is used to fetch
data from related tables. "Join" return rows when there is at least one match in
both table. Type of joins are
Right Join
Return all rows from the right table, even if there are no matches in the left table.
Outer Join
Left Join
Return all rows from the left table, even if there are no matches in the right table.
Full Join
Return rows when there is a match in one of the tables.
24. What is Self-Join?
Self-join is query used to join a table to itself. Aliases should be used for the
same table comparison.
25. What is Cross Join?
Cross Join will return all records where each row from the first table is combined
with each row from the second table.
26. What is a view?
The views are virtual tables. Unlike tables that contain data, views simply contain
queries that dynamically retrieve data when used.
27. What is a materialized view?
Materialized views are also a view but are disk based. Materialized views get
updates on specific duration, base upon the interval specified in the query
definition. We can index materialized view.
28. What are the advantages and disadvantages of views in
a database?
Advantages:
1. Views don't store data in a physical location.
2. The view can be used to hide some of the columns from the table.
3. Views can provide Access Restriction, since data insertion, update and
deletion is not possible with the view.
Disadvantages:
1. When a table is dropped, associated view become irrelevant.
2. Since the view is created when a query requesting data from view is triggered,
its a bit slow.
3. When views are created for large tables, it occupies more memory.
29. What is a stored procedure?
Stored Procedure is a function which contains a collection
of SQL Queries. The procedure can take inputs , process
them and send back output.
30. What are the advantages of a stored procedure?
Stored Procedures are precomplied and stored in the
database. This enables the database to execute the queries
much faster. Since many queries can be included in a stored
procedure, round trip time to execute multiple queries from
source code to database and back is avoided.
31. What is a trigger?
Database triggers are sets of commands that get executed when an
event(Before Insert, After Insert, On Update, On delete of a row) occurs on a
table, views.
32. Explain the difference between DELETE , TRUNCATE
and DROP commands?
Once delete operation is performed, Commit and Rollback can be performed to
retrieve data.
Once the truncate statement is executed, Commit and Rollback statement
cannot be performed. Where condition can be used along with delete statement
but it can't be used with truncate statement.
Drop command is used to drop the table or keys like primary,foreign from a
table.
33. What is the difference between Cluster and Non cluster
Index?
A clustered index reorders the way records in the table are physically stored.
There can be only one clustered index per table. It makes data retrieval faster.
A non clustered index does not alter the way it was stored but creates a
completely separate object within the table. As a result insert and update
command will be faster.
34. What is Union, minus and Interact commands?
MINUS operator is used to return rows from the first query but not from the
second query. INTERSECT operator is used to return rows returned by both the
queries.
Top 80 + SQL Query Interview Questions
and Answers with Examples
Frequently asked basic and advanced Top 80 +
SQL Queries Interview Questions and Answers with
Examples for Business Analyst, Data
Analyst, DBA, Freshers and Experienced Java, PHP, Dot
Net programmers in Oracle, MySQL and MS SQL Database.
Are you an Experienced Programmer or Database
Administrator ? If so, visit our Interview Questions on
Advanced and Complex SQL Query section of this
article. For each question, if the SQL Commands differ for
Oracle, MySQL and SQL Server Databases, specific queries
with respect to a database is provided. If the answers are
same for all databases, only one query is
specified. Interview Questions on SQL are based on
following two tables, Employee Table and Employee
Incentive Table.
Table Name : Employee
Departmen
Employee_id First_name Last_name Salary Joining_date
t
01-JAN-13 12.00.00
1 John Abraham 1000000 Banking
AM
01-JAN-13 12.00.00
2 Michael Clarke 800000 Insurance
AM
01-FEB-13 12.00.00
3 Roy Thomas 700000 Banking
AM
01-FEB-13 12.00.00
4 Tom Jose 600000 Insurance
AM
01-FEB-13 12.00.00
5 Jerry Pinto 650000 Insurance
AM
01-JAN-13 12.00.00
6 Philip Mathew 750000 Services
AM
01-JAN-13 12.00.00
7 TestName1 123 650000 Services
AM
01-FEB-13 12.00.00
8 TestName2 Lname% 600000 Insurance
AM
Table Name : Incentives
Incentive_dat
Employee_ref_id Incentive_amount
e
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
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
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
18. Get employee details from employee table whose
employee name is “John”
Select * from EMPLOYEE where FIRST_NAME='John'
19. Get employee details from employee table whose
employee name are “John” and “Roy”
Select * from EMPLOYEE where FIRST_NAME in ('John','Roy')
20. Get employee details from employee table whose
employee name are not “John” and “Roy”
Select * from EMPLOYEE where FIRST_NAME not in ('John','Roy')
21. Get employee details from employee table whose first
name starts with 'J'
Select * from EMPLOYEE where FIRST_NAME like 'J%'
22. Get employee details from employee table whose first
name contains 'o'
Select * from EMPLOYEE where FIRST_NAME like '%o%'
23. Get employee details from employee table whose first
name ends with 'n'
Select * from EMPLOYEE where FIRST_NAME like '%n'
"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()
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 '%[%]%'
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
41. Get department,total salary with respect to a
department from employee table.
Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by
department
42. Get department,total salary with respect to a
department from employee table order by total salary
descending
Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by
DEPARTMENT order by Total_Salary descending
43. Get department,no of employees in a department,total
salary with respect to a department from employee table
order by total salary descending
Select DEPARTMENT,count(FIRST_NAME),sum(SALARY) Total_Salary from
employee group by DEPARTMENT order by Total_Salary descending
44. Get department wise average salary from employee
table order by salary ascending
select DEPARTMENT,avg(SALARY) AvgSalary from employee group by
DEPARTMENT order by AvgSalary asc
45. Get department wise maximum salary from employee
table order by salary ascending
select DEPARTMENT,max(SALARY) MaxSalary from employee group by
DEPARTMENT order by MaxSalary asc
46. Get department wise minimum salary from employee
table order by salary ascending
select DEPARTMENT,min(SALARY) MinSalary from employee group by
DEPARTMENT order by MinSalary asc
47. Select no of employees joined with respect to year and
month from employee table
SQL Queries in Oracle, select to_char (JOINING_DATE,'YYYY')
Join_Year,to_char (JOINING_DATE,'MM') Join_Month,count(*) Total_Emp from
employee group by to_char
(JOINING_DATE,'YYYY'),to_char(JOINING_DATE,'MM')
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
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.
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(),
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
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.