Vous êtes sur la page 1sur 36

1. What's the difference between a primary key and a unique key?

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.

2. What is difference between DELETE and TRUNCATE commands?

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.

You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint.
Because TRUNCATE TABLE is not logged, it cannot activate a trigger.

TRUNCATE cannot be rolled back.

TRUNCATE is DDL Command.

TRUNCATE Resets identity of the table

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.

DELETE Can be used with or without a WHERE clause


DELETE Activates Triggers.

DELETE can be rolled back.

DELETE is DML Command.

DELETE does not reset identity of the table.

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.

3. When is the use of UPDATE_STATISTICS command?

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.

4. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?

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.

5. What are the properties and different Types of Sub-Queries?

Properties of Sub-Query

A sub-query must be enclosed in the parenthesis.

A sub-query must be put in the right hand of the comparison operator, and

A sub-query cannot contain an ORDER-BY clause.

A query can contain more than one sub-query.

Types of Sub-Query
Single-row sub-query, where the sub-query returns only one row.

Multiple-row sub-query, where the sub-query returns multiple rows,. and

Multiple column sub-query, where the sub-query returns multiple columns

6. What is SQL Profiler?

SQL Profiler is a graphical tool that allows system administrators to monitor events in
an instance of Microsoft SQL Server. You can capture and save data about each event to
a file or SQL Server table to analyze later. For example, you can monitor a production
environment to see which stored procedures are hampering performances by executing
too slowly.

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.

7. What is the difference between a Local and a Global temporary table?

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.

9. What is PRIMARY KEY?

A PRIMARY KEY constraint is a unique identifier for a row within a database table.
Every table should have a primary key constraint to uniquely identify each row and only
one primary key constraint can be created for each table. The primary key constraints
are used to enforce entity integrity.

10. What is UNIQUE KEY constraint?

A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no


duplicate values are entered. The unique key constraints are used to enforce entity
integrity as the primary key constraints.

11. What is FOREIGN KEY?

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.

12. What is CHECK Constraint?

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.

13. What is NOT NULL Constraint?

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 help promote code reuse.

Stored procedures can encapsulate logic. You can change stored procedure code
without affecting clients.

Stored procedures provide better security to your data.

31. What is BCP? When does it used?

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.

SQL Queries Interview Questions and Answers on "SQL Select"

Get all employee details from the employee table

Select * from employee

Get First_Name,Last_Name from employee table

Select first_name, Last_Name from employee

Get First_Name from employee table using alias name “Employee Name”

Select first_name Employee Name from employee

Get First_Name from employee table in upper case

Select upper(FIRST_NAME) from EMPLOYEE

Get First_Name from employee table in lower case

Select lower(FIRST_NAME) from EMPLOYEE

Get unique DEPARTMENT from employee table

select distinct DEPARTMENT from EMPLOYEE

Get FIRST_NAME from employee table after removing white spaces from right
side

select RTRIM(FIRST_NAME) from employee

Get FIRST_NAME from employee table after removing white spaces from left side

select LTRIM(FIRST_NAME) from employee


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

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

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

Get all employee details from the employee table order by First_Name Ascending

Select * from employee order by FIRST_NAME asc

Get all employee details from the employee table order by First_Name descending

Select * from employee order by FIRST_NAME desc

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

Get employee details from employee table whose employee name is “John”

Select * from EMPLOYEE where FIRST_NAME='John'

Get employee details from employee table whose employee name are “John” and
“Roy”

Select * from EMPLOYEE where FIRST_NAME in ('John','Roy')

Get employee details from employee table whose employee name are not “John”
and “Roy”

Select * from EMPLOYEE where FIRST_NAME not in ('John','Roy')

"SQL Wild Card Search" Interview Questions

Get employee details from employee table whose first name starts with 'J'

Select * from EMPLOYEE where FIRST_NAME like 'J%'

Get employee details from employee table whose first name contains 'o'

Select * from EMPLOYEE where FIRST_NAME like '%o%'


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

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)

Get employee details from employee table whose first name starts with 'J' and
name contains 4 letters

Select * from EMPLOYEE where FIRST_NAME like 'J___' (Underscores)

Get employee details from employee table whose Salary greater than 600000

Select * from EMPLOYEE where Salary >600000

Get employee details from employee table whose Salary less than 800000

Select * from EMPLOYEE where Salary <800000

Get employee details from employee table whose Salary between 500000 and
800000

Select * from EMPLOYEE where 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”

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'

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'

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'

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'

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

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

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

Get database date

SQL Queries in Oracle, select sysdate from dual


SQL Queries in SQL Server, select getdate()
SQL Query in MySQL, select now()

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

SQL Queries in Oracle, Select translate(LAST_NAME,'%',' ') from employee


SQL Queries in SQL Server and MySQL, Select REPLACE(LAST_NAME,'%',' ') from
employee

"SQL Group By Query" Interview Questions and Answers

Get department,total salary with respect to a department from employee table.

Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by department

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

Get department,no of employees in a department,total salary with respect to a


department from employee table order by total salary descending

Select DEPARTMENT,count(FIRST_NAME),sum(SALARY) Total_Salary from employee


group by DEPARTMENT order by Total_Salary descending

Get 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

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

select DEPARTMENT,min(SALARY) MinSalary from employee group by DEPARTMENT


order by MinSalary asc

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

"Top N Salary" SQL Interview Questions and Answers

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

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

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

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

Select First_Name,LAST_NAME from employee table as separate rows

select FIRST_NAME from EMPLOYEE union select LAST_NAME from EMPLOYEE

What is the difference between UNION and UNION ALL ?

Both UNION and UNION ALL is used to select information from structurally similar
tables. That means corresponding columns specified in the union should have same data
type. For example, in the above query, if FIRST_NAME is DOUBLE and LAST_NAME is
STRING above query wont work. Since the data type of both the columns are VARCHAR,
union is made possible. Difference between UNION and UNION ALL is that , UNION
query return only distinct values.

Write syntax to delete table employee

DROP table employee;

Write syntax to set EMPLOYEE_ID as primary key in employee table

ALTER TABLE EMPLOYEE add CONSTRAINT EMPLOYEE_PK PRIMARY


KEY(EMPLOYEE_ID)

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)

Write syntax to drop primary key on employee table

Alter TABLE EMPLOYEE drop CONSTRAINT EMPLOYEE_PK;

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)

Write SQL to drop foreign key on employee table

ALTER TABLE INCENTIVES drop CONSTRAINT INCENTIVES_FK;

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.

Different SQL JOINs

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:

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

Then, have a look at a selection from the "Customers" table:

CustomerID CustomerName ContactName

1 Alfreds Futterkiste Maria Anders

2 Ana Trujillo Emparedados y helados Ana Trujillo

3 Antonio Moreno Taquería Antonio Moreno

Inner Join syntax:

SELECT column_name(s) FROM table1 INNER JOIN table2

ON table1.column_name=table2.column_name;
Inner join example:

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate

FROM Orders

INNER JOIN Customers

ON Orders.CustomerID=Customers.CustomerID;

Left Join:

Left outer join:

SELECT column_name(s) FROM table1 LEFT JOIN table2

ON table1.column_name=table2.column_name;

CustomerID CustomerName ContactName Address City

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin


2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la México
helados Constitución 2222 D.F.

3 Antonio Moreno Taquería Antonio Mataderos 2312 México


Moreno D.F.

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate

10308 2 7 1996-09-18

10309 37 3 1996-09-19

10310 77 8 1996-09-20

Left Join example:

SELECT Customers.CustomerName, Orders.OrderID FROM Customers LEFT JOIN Orders

ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName;

RIGHT JOIN Syntax

SELECT column_name(s) FROM table1 RIGHT JOIN table2

ON table1.column_name=table2.column_name;
OrderID CustomerID EmployeeID OrderDate

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:

EmployeeID LastName FirstName BirthDate Photo Notes

1 Davolio Nancy 12/8/1968 EmpID1.pic Education includes a B

2 Fuller Andrew 2/19/1952 EmpID2.pic Andrew received his B

3 Leverling Janet 8/30/1963 EmpID3.pic Janet has a BS degree i

Right outer join example:

SELECT Orders.OrderID, Employees.FirstName FROM Orders RIGHT JOIN Employees

ON Orders.EmployeeID=Employees.EmployeeID

ORDER BY Orders.OrderID;
SQL FULL OUTER JOIN Syntax

SELECT column_name(s) FROM table1 FULL OUTER JOIN table2

ON table1.column_name=table2.column_name;

CustomerID CustomerName ContactName Address City

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin

2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la México


helados Constitución 2222 D.F.

3 Antonio Moreno Taquería Antonio Mataderos 2312 México


Moreno D.F.

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate

10308 2 7 1996-09-18

10309 37 3 1996-09-19

10310 77 8 1996-09-20
Full outer join example:

SELECT Customers.CustomerName, Orders.OrderID FROM Customers FULL OUTER

JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY

Customers.CustomerName;

SQL UNION Example

SELECT City FROM Customers

UNION

SELECT City FROM Suppliers ORDER BY City;

To fetch ALTERNATE records from a table. (EVEN NUMBERED)

select * from emp where rowid in (select decode(mod(rownum,2),0,rowid, null) from

emp);

To select ALTERNATE records from a table. (ODD NUMBERED)

select * from emp where rowid in (select decode(mod(rownum,2),0,null ,rowid) from

emp);

Find the 3rd MAX salary in the emp table.

select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where

e1.sal <= e2.sal);


Find the 3rd MIN salary in the emp table.

select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2where

e1.sal >= e2.sal);

Select FIRST n records from a table.

select * from emp where rownum <= &n;

Select LAST n records from a table

select * from emp minus select * from emp where rownum <= (select count(*) - &n from

emp);

List dept no., Dept name for all the departments in which there are no employees in the

department.

select * from dept where deptno not in (select deptno from emp);

alternate solution: select * from dept a where not exists (select * from emp b where

a.deptno = b.deptno);

altertnate solution: select empno,ename,b.deptno,dname from emp a, dept b where

a.deptno(+) = b.deptno and empno is null;

How to get 3 Max salaries ?

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

a.sal <= b.sal) order by a.sal desc;


How to get 3 Min salaries ?

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

a.sal >= b.sal);

How to get nth max salaries ?

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

where a.sal >= b.sal);

Select DISTINCT RECORDS from emp table.

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

where a.empno=b.empno);

How to delete duplicate rows in a table?

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

where a.empno=b.empno);

Count of number of employees in department wise.

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

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

Suppose there is annual salary information provided by emp table. How to fetch

monthly salary of each and every employee?

select ename,sal/12 as monthlysal from emp;

Select all record from emp table where deptno =10 or 40.
select * from emp where deptno=30 or deptno=10;

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

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

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

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

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

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

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

select * from emp where ename like'S____';

Select all records where ename may be any no of character but it should end with

‘R’.

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

Count MGR and their salary in emp table.

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

In emp table add comm+sal as total sal .

Select all the details of the employee from emp table

SELECT * FROM emp;


Select only the names of all the employees in emp table;

SELECT ename FROM emp;

Select records using multiple columns;

SELECT eno,ename,sal FROM emp;

Select records Using alias;

SELECT eno,ename,salary AS sal FROM emp;

Select records using multiple alias

SELECT eno AS empno,ename AS empname ,sal AS salary FROM emp;

Using functions to enhance alias

SELECT count(sal) as totalsal FROM emp;

Derived or Computed fields: Columns values were manipulated as it gets retrived.

Find the monthly salary of employee,( The salary stored is on Annum basis)

SELECT sal / 12 FROM emp;

Using Alias to decorate derived or computed fields.

SELECT sal / 12 AS monthly_salary FROM emp

Calculate the sum of monthly salary and the commissions of the employee.

SELECT ename,(sal / 12) + nvl(comm,0) AS monthsalwithcomm FROM emp;


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

Select any salary <3000 from emp table.

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

Select all salary <3000 from emp table.

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

Select all the employee group by deptno and sal in descending order.

select ename,deptno,sal from emp order by deptno,sal desc;

How can I create an empty table emp1 with same structure as emp?

Create table emp1 as select * from emp where 1=2;

How to retrive record where sal between 1000 to 2000?

Select * from emp where sal>=1000 And sal<2000

Select all records where dept no of both emp and dept table matches.

select * from emp where exists(select * from dept where 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?

(Select * from emp) Union (Select * from emp1)

How to fetch only common records from two tables emp and emp1?

(Select * from emp) Intersect (Select * from emp1)


How can I retrive all records of emp1 those should not present in emp2?

(Select * from emp) Minus (Select * from emp1)

Count the totalsa deptno wise where more than 2 employees exist.

SELECT deptno, sum(sal) As totalsal

FROM emp

GROUP BY deptno

HAVING COUNT(empno) > 2

Using Aggregate functions: Count,Min,Max,Sum,Avg.

Find the number of rows in emp ?

SELECT count(*) FROM emp;

Find the how many different Job profile are there in Employee table ?

SELECT COUNT(DISTINCT job) FROM emp;

Find out how many people were given commision ? ( Count function does n't

include null as it counts)

SELECT COUNT(comm)FROM emp;

Select records from two tables;

SELECT e.ename, d.deptno,e.sal FROM emp e,dept d;


Select records from two tables depending condition suppose where deptno of

from both emp and dept mathes

Select e.ename, d.deptno,e.sal from emp e,dept d where e.deptno=d.deptno;

Select records using where clause;

SELECT ename,sal FROM emp WHERE sal>2000

Select records from emp and dept where both deptno matches

SELECT e.ename,e.sal,d.deptno FROM emp e,dept d WHERE

e.deptno=d.deptno

Select secords where empno=1003

SELECT * FROM emp WHERE empno=1003

Select records where ename is KING

SELECT * FROM emp WHERE ename='KING';

SELECT * FROM emp WHERE city='LONDON' OR city='PARIS'

SELECT * FROM emp WHERE sal>2000 OR comm IS NOT NULL

Q8: Select records using between and;

SELECT * FROM emp WHERE sal BETWEEN 2000 AND 3000

SELECT * FROM dept WHERE deptno BETWEEN 20 AND 40;


SELECT * FROM emp WHERE empno BETWEEN 1001 TO 1010;

Q10: Select records using not in;

SELECT * FROM emp WHERE ename NOT IN('SCOTT','WARD','ALLEN')

Q11: Select records using null;

SELECT * FROM emp WHERE comm IS NULL;

Q12: Select records using not null;

SELECT * FROM emp WHERE comm IS NOT NULL;

Q13: Select records using like;

SELECT * FROM emp WHERE ename LIKE'S%';

Select records using multiple conditions.

SELECT * FROM emp WHERE comm IS NOT NULL AND sal >2000 AND deptno>20;

SELECT * FROM emp WHERE deptno<20 AND comm IS NOT NULL OR sal

IN{1000,2000,3000,4000};

SELECT * FROM emp WHERE ename LIKE 'sC___';

SELECT * FROM emp WHERE ename LIKE 'AL%';

SELECT * FROM emp WHERE ename LIKE 'A_L_N';

13.5 SELECT * FROM emp WHERE ename LIKE '___L%';


Select records using not like;

SELECT * FROM emp WHERE ename NOT LIKE 'A%';

Select records using function;

SELECT ename,sum(sal+comm) AS total FROM emp

SELECT count(*) FROM emp;

SELECT deptno,avg(sal) AS avgsal FROM emp GROUP BY deptno;

Select records using order by;

SELECT * FROM emp ORDER BY sal

SELECT ename,sal FROM emp ORDER BY salename

SELECT empno,ename,sal FROM emp ORDER BY sal DESC,empno,empname

Select records using group by;

SELECT deptno,sum(sal)FROM emp GROUP BY deptno

SELECT deptno,sum(sal) FROM emp GROUP BY deptno,ename ,empno

Select records using group by and having clause;

SELECT deptno,sum(sal) GROUP BY deptno HAVING deptno>20

Select with-in select;

SELECT * FROM emp WHERE max(sal)<(SELECT max(sal) FROM emp)


SELECT * FROM emp WHERE deptno=(SELECT deptno FROM dept);

SELECT * FROM emp WHERE deptno NOT IN (SELECT deptno FROM dept);

Create a table by selecting record from another table;

CREATE TABLE emp2 AS SELECT * FROM emp;

Select records using exist;

SELECT deptno FROM dept d WHERE EXISTS (SELECT * FROM emp e WHERE d.deptno = e.deptno

Select sysdate;

SELECT sysdate FROM dual;

Select constraint name, constraint_type;

SELECT constraint_name, constraint_type FROM user_constraints WHERE

table_name = 'emp';

Select nextval, currval from sequence;

SELECT emp_sequence.nextval FROM dual

SELECT emp_sequence.currval FROM dual


SQL Query to find second highest salary of Employee

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

Employee );

2. SQL Query to find Max Salary from each department

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

3. Write SQL Query to display current date

SELECT GetDate();

4. Write an SQL Query to check whether date passed to Query is date of given

format or not

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

5. Write a SQL Query to print the name of distinct employee whose DOB is

between 01/01/1960 to 31/12/1975

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

AND ‘31/12/1975’;

6. Write an SQL Query find number of employees according to gender whose DOB

is between 01/01/1960 to 31/12/1975

SELECT COUNT(*), sex from Employees WHERE DOB BETWEEN '01/01/1960' AND

'31/12/1975' GROUP BY sex;

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

10000

SELECT EmpName FROM Employees WHERE Salary>=10000;


8. Write a SQL Query to find year from date

You can use the following query to find year from a date in SQL server 2008.

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

9. Write SQL Query to find duplicate rows in a database? and then write SQL query

to delete them?

You can use simple query like this to select specific date in distinct record –

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

a.empno=b.empno)

To delete :

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

a.empno=b.empno);

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 i.e. list of

above average students

This query can be written using sub query as shown below.

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

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

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

Employee );

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


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

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

e.DeptId = d.DeptID GROUP BY DeptName;

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 if

there is no reference of dept_id on Employee table.

Question 3: Write an SQL Query to check whether date passed to Query is the date

of given format or not.

Answer: SQL has IsDate() function which is used to check passed value is a date or not

of specified format, it returns 1(true) or 0(false) accordingly. Remember ISDATE() is an

MSSQL function and it may not work on Oracle, MySQL or any other database but there

would be something similar.

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

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

Question 5: Write an SQL Query to print the name of the distinct employee whose

DOB is between 01/01/1960 to 31/12/1975.

This SQL query is tricky, but you can use BETWEEN clause to get all records whose date

fall between two dates.


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

AND ‘31/12/1975’;

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

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

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 an employee whose Salary is equal or

greater than 10000.

SELECT EmpName FROM Employees WHERE Salary>=10000;

Question 8: Write an SQL Query to find name of employee whose name Start with

‘M’

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.

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

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

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


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

write SQL query to delete them?

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

a.empno=b.empno)

To Delete:

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

a.empno=b.empno);

Question 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 Index be used

for this operation? For example if Index is on EmpId, EmpFirstName,

and EmpSecondName and you write query like

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

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

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 outer or full

outer join respectively).

Outer Join can be full outer or single outer

What is the difference between JOIN and UNION?

SQL JOIN allows us to “lookup” records on other table based on the given conditions

between two tables. For example, if we have the department ID of each employee, then

we can use this department ID of the employee table to join with the department ID of

department table to lookup department names.

UNION operation allows us to add 2 similar data sets to create resulting data set that

contains all the data from the source data sets. Union does not require any condition for

joining. For example, if you have 2 employee tables with same structure, you can UNION

them to create one result set that will contain all the employees from both of the tables.
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.

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.

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.

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

How to select first 5 records from a table?

In Oracle:

SELECT * FROM EMP WHERE ROWNUM <= 5;

In SQL Server,

SELECT TOP 5 * FROM EMP;

Vous aimerez peut-être aussi