Sql Interview Questions.

1.What is the difference between clustered and non clustered index in SQL?
There are mainly two type of indexes in SQL, Clustered index and non clustered index. The differences between these two indexes is very important from SQL performance perspective.
1) One table can have only one clustered index but it can have many non clusteredindex. (approximately 250).

2) clustered index determines how data is stored physically in table. Actually clustered index stores data in cluster, related data is stored together so it makes simple to retrieve data.

3) reading from a clustered index is much faster than reading from non clustered index from the same table.

4) clustered index sort and store data rows in the table or view based on their key value, while non cluster have a structure separate from the data row.

2.What is "TRIGGER" in SQL?

Trigger allows you to execute a batch of SQL code when an insert, update or delete command is executed against a specific table.
Actually triggers are special type of stored procedures that are defined to execute automatically in place or after data modifications.

3.Write an SQL query to get third maximum salary of an employee from a table named employee_table.

SELECT TOP 1 salary   
FROM (  
SELECT TOP 3 salary  
FROM employee_table  
ORDER BY salary DESC ) AS emp  
ORDER BY salary ASC;  
4.What is ACID property in database?

ACID property is used to ensure that the data transactions are processed reliably in a database system.
A single logical operation of a data is called transaction.
ACID is an acronym for Atomicity, Consistency, Isolation, Durability.
Atomicity: it requires that each transaction is all or nothing. It means if one part of the transaction fails, the entire transaction fails and the database state is left unchanged.
Consistency: the consistency property ensure that the data must meet all validation rules. In simple words you can say that your transaction never leaves your database without completing its state.
Isolation: this property ensure that the concurrent property of execution should not be met. The main goal of providing isolation is concurrency control.
Durability: durability simply means that once a transaction has been committed, it will remain so, come what may even power loss, crashes or errors.



1. Get First_Name from employee table in lower case
Select lower(FIRST_NAME) from EMPLOYEE
2. Select first 3 characters of FIRST_NAME from EMPLOYEE
select substring(FIRST_NAME,0,3) from employee
3. Get position of 'o' in name 'John' from employee table
Select CHARINDEX('o',FIRST_NAME,0) from employee where first_name='John'
4. Get FIRST_NAME from employee table after removing white spaces from left side
select LTRIM(FIRST_NAME) from employee     (for right side RTRIM)
5. Get length of FIRST_NAME from employee table
selectlen(FIRST_NAME) from employee
6. Get First_Name from employee table after replacing 'o' with '$'
select REPLACE(FIRST_NAME,'o','$') from employee
7. Get First_Name and Last_Name as single column from employee table separated by a '_'
Select FIRST_NAME + '_' +LAST_NAME from EMPLOYEE
8. Get FIRST_NAME ,Joining year,Joining Month and Joining Date from employee table
SelectFIRST_NAME, 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
          (note: CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
100 =  monddyyyyhh:miAM (or PM)
103 = dd/mm/yyyy
          )
9. Get all employee details from the employee table order by First_Name Ascending/descending.
Select * from employee order by FIRST_NAME asc/desc
10. Get all employee details from the employee table order by First_Name Ascending and Salary descending
Select * from employee order by FIRST_NAME asc,SALARYdesc
11. Get employee details from employee table whose employee name are “John” and “Roy
Select * from EMPLOYEE where FIRST_NAME in ('John','Roy')
12. Get employee details from employee table whose employee name are not “John” and “Roy”
Select * from EMPLOYEE where FIRST_NAME not in ('John','Roy')
13. Get employee details from employee table whose first name ends with 'n'
Select * from EMPLOYEE where FIRST_NAME like '%n'
14. 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)
15. Get employee details from employee table whose Salary less than 800000
Select * from EMPLOYEE where Salary <800000
16. Get employee details from employee table whose Salary between 500000 and 800000
Select * from EMPLOYEE where Salary between 500000 and 800000
17. Get employee details from employee table whose joining year is “2013”
Select * from EMPLOYEE where SUBSTRING(convert(varchar,joining_date,103),7,4)='2013'
18. Get employee details from employee table whose joining month is “January”
Select * from EMPLOYEE where SUBSTRING(convert(varchar,joining_date,100),1,3)='Jan'
19. Get employee details from employee table who joined before January 1st 2013
Select * from EMPLOYEE where joining_date<'01/01/2013'
20. Get Joining Date and Time from employee table
Select convert(varchar(19),joining_date,121) from EMPLOYEE
21. 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
22. Database date-select getdate()
23. Get names of employees from employee table who has '%' in Last_Name. Tip : Escape character for special characters in a query.
Select FIRST_NAME from employee where Last_Name like '%[%]%'
24. Get Last Name from employee table after replacing special character with white space
Select REPLACE(LAST_NAME,'%',' ') from employee
25. Get department,total salary with respect to a department from employee table.
Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by department
26. 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
27. Get department,no of employees in a department,total salary with respect to a department from employee table order by total salarydescending
Select DEPARTMENT,count(FIRST_NAME),sum(SALARY) Total_Salary from employee group by DEPARTMENT order by Total_Salary descending
28. Get department wise average salary from employee table order by salaryascending
selectDEPARTMENT,avg(SALARY) AvgSalary from employee group by DEPARTMENT order by AvgSalaryasc
29. Get department wise minimum salary from employee table order by salary ascending
selectDEPARTMENT,min(SALARY) MinSalary from employee group by DEPARTMENT order by MinSalaryasc
30. Select no of employees joined with respect to year and month from employee table
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)
31. 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_Salarydesc
32. Select employee details from employee table if data exists in incentive table ?
select * from EMPLOYEE where exists (select * from INCENTIVES)
33. 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
34. 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
35. 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
36. Select Banking as 'Bank Dept', Insurance as 'Insurance Dept' and Services as 'Services Dept' from employee table
SELECT case DEPARTMENT when 'Banking' then 'Bank Dept' when 'Insurance' then 'Insurance Dept' when 'Services' then 'Services Dept' end FROM EMPLOYEE
37. 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.
38. 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''')
39. Select Last Name from employee table which contain only numbers
Select * from EMPLOYEE where lower(LAST_NAME)=upper(LAST_NAME)
40. 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.
41. 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' )
42. 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
43. 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
44. 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
45. 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.
Select FIRST_NAME, ISNULL(INCENTIVE_AMOUNT,0) from employee a left join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID
46. Select first_name, incentive amount from employee and incentives table for all employees who got incentives using left join
Select FIRST_NAME, isnull(INCENTIVE_AMOUNT,0) from employee a right join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID
47. Select max incentive with respect to employee from employee and incentives table using sub query
select DEPARTMENT,(select ISNULL(max(INCENTIVE_AMOUNT),0) from INCENTIVES where EMPLOYEE_REF_ID=EMPLOYEE_ID) Max_incentive from EMPLOYEE
48. Select TOP 2 salary from employee table
select top 2 * from employee order by salary desc
49. Select TOP N salary from employee table
select top N * from employee
50. Select 2nd Highest salary from employee table
select min(SALARY) from (select top 2 * from employee) a
51. Select Nth Highest salary from employee table
select min(SALARY) from (select top N * from employee) a
52. Select First_Name,LAST_NAME from employee table as separate rows
select FIRST_NAME from EMPLOYEE union select LAST_NAME from EMPLOYEE
53. 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. 
54. Write syntax to delete table employee
DROP table employee;
55. Write syntax to set EMPLOYEE_ID as primary key in employee table
ALTER TABLE EMPLOYEE add CONSTRAINT EMPLOYEE_PK PRIMARY KEY(EMPLOYEE_ID)
56. 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)
57. Write syntax to drop primary key on employee table.
Alter TABLE EMPLOYEE drop CONSTRAINT EMPLOYEE_PK;
58. 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)
59. Write SQL to drop foreign key on employee table
ALTER TABLE INCENTIVES drop CONSTRAINT INCENTIVES_FK;
60. 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_nonumber(12);
BEGIN
select EMPLOYEE_ID_SEQ.nextval into seq_no from dual ;
:new EMPLOYEE_ID :=seq_no;
END;
SHOW ERRORS;
61. What is SQL Injection ?
SQL Injection is one of the techniques uses by hackers to hack a website by injecting SQL commands in data fields.
62. Select 3rd Highest salary from employee table without using top query.
WITH CTE AS
(
    SELECT EmpID, EmpName, EmpSalary,
           RN = ROW_NUMBER() OVER (ORDER BY EmpSalary DESC)
    FROM dbo.Salary
)
SELECT EmpID, EmpName, EmpSalary
FROM CTE
WHERE RN = @NthRow  // put 3 to get the 3rd 
63. Switching values in a column with one update statement.
(change the column value from M to W and W to M) 
sol 1.
UPDATE TableName
SET gender = CASE WHEN gender = 'M' THEN 'W' 
                  WHEN gender = 'W' THEN 'M'
                  ELSE gender END
sol 2.
UPDATE TableName
SET gender = CASE WHEN gender = 'M' THEN 'W' 
                  WHEN gender = 'W' THEN 'M' END
WHERE gender IN ('M','W')
sol 3.
/*For SQL Server 2012+*/
UPDATE TableName
SET    gender = IIF(gender = 'M', 'W', 'M')
WHERE  gender IN ( 'M', 'W' ); 












Comments

Popular posts from this blog

Configure Typescripts in Visual Studio 2013

Maintain Session For Login User Using ActionFilter in Asp.Net MVC