SQL Interview Questions
SQL Interview Questions
Both primary key and unique key enforces uniqueness of the column on which
they are defined. But by default primary key creates a clustered index on the
column, where are unique creates a nonclustered index by default. Another
major difference is that, primary key doesn't allow NULLs, but unique key allows
one NULL only.
Delete command removes the rows from a table based on the condition that we
provide with a WHERE clause. Truncate will actually remove all the rows from a
table and there will be no data in the table after we run the truncate command.
TRUNCATE:
TRUNCATE is faster and uses fewer system and transaction log resources than
DELETE.
TRUNCATE removes the data by deallocating the data pages used to store the
table's data, and only the page deallocations are recorded in the transaction log.
TRUNCATE removes all rows from a table, but the table structure, its columns,
constraints, indexes and so on, remains. The counter used by an identity for new
rows is reset to the seed for the column.
DELETE:
DELETE removes rows one at a time and records an entry in the transaction log
for each deleted row.
If you want to retain the identity counter, use DELETE instead. If you want to
remove table definition and its data, use the DROP TABLE statement.
Note: DELETE and TRUNCATE both can be rolled back when surrounded by
TRANSACTION if the current session is not closed. If TRUNCATE is written in
Query Editor surrounded by TRANSACTION and if session is closed, it can not be
rolled back but DELETE can be rolled back.
This command is basically used when a large processing of data has occurred. If a
large amount of deletions any modification or Bulk Copy into the tables has
occurred, it has to update the indexes to take these changes into account.
UPDATE_STATISTICS updates the indexes on these tables accordingly.
They specify a search condition for a group or an aggregate. But the difference is
that HAVING can be used only with the SELECT statement. HAVING is typically
used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a
WHERE clause. Having Clause is basically used only with the GROUP BY function
in a query whereas WHERE Clause is applied to each row before they are part of
the GROUP BY function in a query.
Properties of Sub-Query
A sub-query must be put in the right hand of the comparison operator, and
Types of Sub-Query
Use SQL Profiler to monitor only the events in which you are interested. If traces
are becoming too large, you can filter them based on the information you want,
so that only a subset of the event data is collected. Monitoring too many events
adds overhead to the server and the monitoring process and can cause the trace
file or trace table to grow very large, especially when the monitoring process
takes place over a long period of time.
A local temporary table exists only for the duration of a connection or, if defined
inside a compound statement, for the duration of the compound statement.
A global temporary table remains in the database permanently, but the rows exist
only within a given connection. When connection is closed, the data in the global
temporary table disappears. However, the table definition remains with the
database for access when database is opened next time.
8. What is the STUFF function and how does it differ from the REPLACE
function?
STUFF function is used to overwrite existing characters. Using this syntax, STUFF
(string_expression, start, length, replacement_characters), string_expression is
the string that will have characters substituted, start is the starting position,
length is the number of characters in the string that are substituted, and
replacement_characters are the new characters interjected into the string.
REPLACE function to replace existing characters of all occurrences. Using the
syntax REPLACE (string_expression, search_string, replacement_string), where
every incidence of search_string found in the string_expression will be replaced
with replacement_string.
A FOREIGN KEY constraint prevents any actions that would destroy links
between tables with the corresponding data values. A foreign key in one table
points to a primary key in another table. Foreign keys prevent actions that would
leave rows with foreign key values when there are no primary keys with that
value. The foreign key constraints are used to enforce referential integrity.
A CHECK constraint is used to limit the values that can be placed in a column. The
check constraints are used to enforce domain integrity.
A NOT NULL constraint enforces that the column will not accept null values. The
not null constraints are used to enforce domain integrity, as the check
constraints.
14. What are the advantages of using Stored Procedures?
Stored procedure can reduced network traffic and latency, boosting application
performance.
Stored procedure execution plans can be reused, staying cached in SQL Server's
memory, reducing server overhead.
Stored procedures can encapsulate logic. You can change stored procedure code
without affecting clients.
BulkCopy is a tool used to copy huge amount of data from tables and views. BCP
does not copy the structures same as source to destination. BULK INSERT
command helps to import a data file into a database table or view in a user-
specified format.
Get First_Name from employee table using alias name “Employee Name”
Get FIRST_NAME from employee table after removing white spaces from left
side
Get First_Name from employee table after replacing 'o' with '$'
Get all employee details from the employee table order by First_Name
Ascending
Get all employee details from the employee table order by First_Name
descending
Get all employee details from the employee table order by First_Name
Ascending and Salary Descending?
Get employee details from employee table whose employee name is “John”
Get employee details from employee table whose employee name are
“John” and “Roy”
Get employee details from employee table whose first name starts with 'J'
Get employee details from employee table whose first name contains 'o'
Get employee details from employee table whose first name ends with 'n'
Get employee details from employee table whose first name ends with 'n'
and name contains 4 letters
Get employee details from employee table whose first name starts with 'J'
and name contains 4 letters
Get employee details from employee table whose Salary greater than
600000
Get employee details from employee table whose Salary less than 800000
Get employee details from employee table whose Salary between 500000
and 800000
Get employee details from employee table whose name is 'John' and
'Michael'
Select * from EMPLOYEE where FIRST_NAME in ('John','Michael')
Get employee details from employee table whose joining year is “2013”
Get employee details from employee table who joined before January 1st
2013
Get employee details from employee table who joined after January 31st
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
'%\%%'
Get Last Name from employee table after replacing special character with
white space
Get department wise average salary from employee table order by salary
ascending
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
Get department wise minimum salary from employee table order by salary
ascending
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
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
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
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
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.
SQL Injection is one of the the techniques uses by hackers to hack a website by
injecting SQL commands in data fields.
Before we continue with examples, we will list the types of the different SQL
JOINs you can use:
• INNER JOIN: Returns all rows when there is at least one match in BOTH
tables
• LEFT JOIN: Return all rows from the left table, and the matched rows
from the right table
• RIGHT JOIN: Return all rows from the right table, and the matched rows
from the left table
• FULL JOIN: Return all rows when there is a match in ONE of the tables
Inner Join:
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
ON table1.column_name=table2.column_name;
FROM Orders
ON Orders.CustomerID=Customers.CustomerID;
Left Join:
Left outer join:
ON table1.column_name=table2.column_name;
10308 2 7 1996-09-18
10309 37 3 1996-09-19
10310 77 8 1996-09-20
Orders
ON Customers.CustomerID=Orders.CustomerID ORDER BY
Customers.CustomerName;
ON table1.column_name=table2.column_name;
10308 2 7 1996-09-18
10309 37 3 1996-09-19
10310 77 8 1996-09-20
And a selection from the "Employees" table:
Employees
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY Orders.OrderID;
ON table1.column_name=table2.column_name;
CustomerID CustomerName ContactName Address Cit
10308 2 7 1996-09-18
10309 37 3 1996-09-19
10310 77 8 1996-09-20
Customers.CustomerName;
UNION
from emp);
from emp);
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp
select * from emp minus select * from emp where rownum <= (select count(*) -
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
select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b
select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b
select distinct hiredate from emp a where &n = (select count(distinct sal) from
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);
Select all record from emp table where deptno =10 or 40.
Select all record from emp table where deptno=30 and sal>1500.
Select all record from emp where job not in SALESMAN or CLERK.
'BLAKE','SCOTT','KING'and'FORD'.
Select all records where ename starts with ‘S’ and its lenth is 6 char.
select * from emp where ename like'S____';
Select all records where ename may be any no of character but it should
retrived.
Find the monthly salary of employee,( The salary stored is on Annum basis)
Calculate the sum of monthly salary and the commissions of the employee.
select * from emp where sal> any(select sal from emp where sal<3000);
select * from emp where sal> all(select sal from emp where sal<3000);
Select all the employee group by deptno and sal in descending order.
How can I create an empty table emp1 with same structure as emp?
Select all records where dept no of both emp and dept table matches.
emp.deptno=dept.deptno)
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?
How to fetch only common records from two tables emp and emp1?
How can I retrive all records of emp1 those should not present in emp2?
Count the totalsa deptno wise where more than 2 employees exist.
FROM emp
GROUP BY deptno
Find out how many people were given commision ? ( Count function does
Select records from two tables depending condition suppose where deptno
e.deptno=d.deptno;
Select records from emp and dept where both deptno matches
e.deptno=d.deptno
deptno>20;
SELECT * FROM emp WHERE deptno<20 AND comm IS NOT NULL OR sal
IN{1000,2000,3000,4000};
dept);
SELECT deptno FROM dept d WHERE EXISTS (SELECT * FROM emp e WHERE d.deptno = e.dep
Select sysdate;
from Employee );
SELECT GetDate();
5. Write a SQL Query to print the name of distinct employee whose DOB is
than 10000
You can use the following query to find year from a date in SQL server 2008.
9. Write SQL Query to find duplicate rows in a database? and then write SQL
You can use simple query like this to select specific date in distinct record –
WHERE a.empno=b.empno)
To delete :
WHERE a.empno=b.empno);
10. 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
table)
from Employee );
In this query, we have used RIGHT OUTER JOIN because we need the name of the
department from Department table which is on the right side of JOIN clause, even
Answer: SQL has IsDate() function which is used to check passed value is a date
Remember ISDATE() is an MSSQL function and it may not work on Oracle, MySQL
Question 5: Write an SQL Query to print the name of the distinct employee
This SQL query is tricky, but you can use BETWEEN clause to get all records
Question 8: Write an SQL Query to find name of employee whose name Start
with ‘M’
Question 9: find all Employee records containing the word "Joe", regardless
Question 10: Write an SQL Query to find the year from date.
Here is how you can find Year from a Date in SQL Server 2008
Question 11: Write SQL Query to find duplicate rows in a database? and
WHERE a.empno=b.empno)
To Delete:
WHERE a.empno=b.empno);
Question 14: You have a composite index of three columns, and you only
provide the value of two columns in WHERE clause of a select query? Will
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
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.
Outer Join
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
SQL JOIN allows us to “lookup” records on other table based on the given
each employee, then we can use this department ID of the employee table to join
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
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
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.
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
on a static field.
What is the difference among UNION, MINUS and INTERSECT?
UNION combines the results from 2 tables and eliminates duplicate records from
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.
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
Self Join is often very useful to convert a hierarchical structure into a flat
structure
In Oracle:
In SQL Server,