Showing posts with label SQL SERVER. Show all posts
Showing posts with label SQL SERVER. Show all posts

Tuesday, 4 November 2014

sql query interview questions

Write query to get all employee detail from "EmployeeDetail" table?

SELECT * FROM [EmployeeDetail]


Write query to get only "FirstName" column from "EmployeeDetail" table?

SELECT FirstName FROM [EmployeeDetail]


Write query to get FirstName in uppler case as "First Name"?

SELECT UPPER(FirstName) AS [First Name]  FROM [EmployeeDetail]


Write query to get FirstName in lower case as "First Name"?

SELECT LOWER(FirstName) AS [First Name]  FROM [EmployeeDetail]


Write query for combine FirstName and LastName and display it as "Name" (also include white space between first name & last name)?

SELECT FirstName +' '+ LastName AS [Name]  FROM [EmployeeDetail]


Select employee detail whose name is "Vikas"?

SELECT * FROM [EmployeeDetail] WHERE FirstName = 'Vikas'


Get all employee detail from EmployeeDetail table whose "FirstName" start with latter 'a'?

SELECT * FROM [EmployeeDetail] WHERE FirstName like 'a%'



Get all employee details from EmployeeDetail table whose "FirstName" contains 'k'?

 SELECT * FROM [EmployeeDetail] WHERE FirstName like '%k%'



Get all employee details from EmployeeDetail table whose "FirstName" end with 'h'?

 SELECT * FROM [EmployeeDetail] WHERE FirstName like '%h'

  
Get all employee detail from EmployeeDetail table whose "FirstName" start with any single character between 'a-p'?

 SELECT * FROM [EmployeeDetail] WHERE FirstName like '[a-p]%'

Get all employee detail from EmployeeDetail table whose "FirstName" not start with any single character between 'a-p'?

SELECT * FROM [EmployeeDetail] WHERE FirstName like '[^a-p]%'


Get all employee detail from EmployeeDetail table whose "Gender" end with 'le' and contain 4 letters.--The Underscore(_) Wildcard Character represents any single character?

SELECT * FROM [EmployeeDetail] WHERE Gender like '__le' --there are two "_"


Get all employee detail from EmployeeDetail table whose "FirstName" start with 'A' and contain 5 letters?


SELECT * FROM [EmployeeDetail] WHERE FirstName like 'A____' --there are two "_"

Get all employee detail from EmployeeDetail table whose "FirstName" containing '%'. ex:-"Vik%as"?

SELECT * FROM [EmployeeDetail] WHERE FirstName like '%[%]%' --there are two "_"
--According to our table it would return 0 rows, because no name containg '%'


Get all unique "Department" from EmployeeDetail table.

SELECT DISTINCT(Department) FROM [EmployeeDetail]


Get the highest "Salary" from EmployeeDetail table.

SELECT MAX(Salary) FROM [EmployeeDetail]


Get the lowest "Salary" from EmployeeDetail table.

SELECT MIN(Salary) FROM [EmployeeDetail]

Show "JoiningDate" in "dd mmm yyyy" format, ex- "15 Feb 2013"

SELECT CONVERT(VARCHAR(20),JoiningDate,106) FROM [EmployeeDetail]

Show "JoiningDate" in "yyyy/mm/dd" format, ex- "2013/02/15"
SELECT CONVERT(VARCHAR(20),JoiningDate,111) FROM [EmployeeDetail]

Show only time part of the "JoiningDate".

SELECT CONVERT(VARCHAR(20),JoiningDate,108) FROM [EmployeeDetail]


Get only Year part of "JoiningDate".

SELECT DATEPART(YEAR, JoiningDate) FROM [EmployeeDetail] 


Get only Month part of "JoiningDate".

SELECT DATEPART(MONTH,JoiningDate) FROM [EmployeeDetail]

Get system date.

SELECT GETDATE()

Get UTC date.

SELECT GETUTCDATE()

Get the first name, current date, joiningdate and diff between current date and joining date in months.

SELECT FirstName, GETDATE() [Current Date], JoiningDate,
DATEDIFF(MM,JoiningDate,GETDATE()) AS [Total Months] FROM [EmployeeDetail]

Get the first name, current date, joiningdate and diff between current date and joining date in days.

SELECT FirstName, GETDATE() [Current Date], JoiningDate,
DATEDIFF(DD,JoiningDate,GETDATE()) AS [Total Months] FROM [EmployeeDetail]


Get all employee details from EmployeeDetail table whose joining year is 2013.

SELECT * FROM [EmployeeDetail] WHERE DATEPART(YYYY,JoiningDate) = '2013'

Get all employee details from EmployeeDetail table whose joining month is Jan(1).

SELECT * FROM [EmployeeDetail] WHERE DATEPART(MM,JoiningDate) = '1'

Get all employee details from EmployeeDetail table whose joining date between "2013-01-01" and "2013-12-01".

SELECT * FROM [EmployeeDetail] WHERE JoiningDate BETWEEN '2013-01-01' AND '2013-12-01'

Get how many employee exist in "EmployeeDetail" table.

SELECT COUNT(*) FROM [EmployeeDetail]

Select only one/top 1 record from "EmployeeDetail" table.

SELECT TOP 1 * FROM [EmployeeDetail]


Select all employee detail with First name "Vikas","Ashish", and "Nikhil".

SELECT * FROM [EmployeeDetail] WHERE FirstName IN('Vikas','Ashish','Nikhil')


Select all employee detail with First name not "Vikas","Ashish", and "Nikhil".

SELECT * FROM [EmployeeDetail] WHERE FirstName NOT IN('Vikas','Ashish','Nikhil')


Select first name from "EmployeeDetail" table after removing white spaces from right side

SELECT RTRIM(FirstName) AS [FirstName] FROM [EmployeeDetail]


Select first name from "EmployeeDetail" table after removing white spaces from left side

SELECT LTRIM(FirstName) AS [FirstName] FROM [EmployeeDetail]



Display first name and Gender as M/F.(if male then M, if Female then F)

SELECT FirstName, CASE  WHEN Gender = 'Male' THEN 'M'
WHEN Gender = 'Female' THEN 'F'
END AS [Gender]
FROM [EmployeeDetail]

Select first name from "EmployeeDetail" table prifixed with "Hello "

SELECT 'Hello ' + FirstName FROM [EmployeeDetail]

Get employee details from "EmployeeDetail" table whose Salary greater than 600000

SELECT * FROM [EmployeeDetail] WHERE Salary > 600000

Get employee details from "EmployeeDetail" table whose Salary less than 700000

SELECT * FROM [EmployeeDetail] WHERE Salary < 700000


Get employee details from "EmployeeDetail" table whose Salary between 500000 than 600000

SELECT * FROM [EmployeeDetail] WHERE Salary BETWEEN 500000 AND 600000


Select second highest salary from "EmployeeDetail" table.

SELECT TOP 1 Salary FROM
(
      SELECT TOP 2 Salary FROM [EmployeeDetail] ORDER BY Salary DESC
) T ORDER BY Salary ASC



Write the query to get the department and department wise total(sum) salary from "EmployeeDetail" table.

SELECT Department, SUM(Salary) AS [Total Salary] FROM [EmployeeDetail]
GROUP BY Department

Write the query to get the department and department wise total(sum) salary, display it in ascending order according to salary.

SELECT Department, SUM(Salary) AS [Total Salary] FROM [EmployeeDetail]
GROUP BY Department ORDER BY SUM(Salary) ASC

Write the query to get the department and department wise total(sum) salary, display it in descending order according to salary.

SELECT Department, SUM(Salary) AS [Total Salary] FROM [EmployeeDetail]
GROUP BY Department ORDER BY SUM(Salary) DESC
  
Write the query to get the department, total no. of departments, total(sum) salary with respect to department from "EmployeeDetail" table.

SELECT Department, COUNT(*) AS [Dept Counts], SUM(Salary) AS [Total Salary] FROM [EmployeeDetail]
GROUP BY Department

Get department wise average salary from "EmployeeDetail" table order by salary ascending
  
SELECT Department, AVG(Salary) AS [Average Salary] FROM [EmployeeDetail]
GROUP BY Department ORDER BY AVG(Salary) ASC


Get department wise maximum salary from "EmployeeDetail" table order by salary ascending
  
SELECT Department, MAX(Salary) AS [Average Salary] FROM [EmployeeDetail]
GROUP BY Department ORDER BY MAX(Salary) ASC



Get department wise minimum salary from "EmployeeDetail" table order by salary ascending

SELECT Department, MIN(Salary) AS [Average Salary] FROM [EmployeeDetail]
GROUP BY Department ORDER BY MIN(Salary) ASC


Write down the query to fetch Project name assign to more than one Employee

Select ProjectName,Count(*) [NoofEmp] from [ProjectDetail] GROUP BY ProjectName HAVING COUNT(*)>1


Get employee name, project name order by firstname from "EmployeeDetail" and "ProjectDetail" for those employee which have assigned project already.

SELECT FirstName,ProjectName FROM [EmployeeDetail] A INNER JOIN [ProjectDetail] B
ON A.EmployeeID = B.EmployeeDetailID ORDER BY FirstName


Get employee name, project name order by firstname from "EmployeeDetail" and "ProjectDetail" for all employee even they have not assigned project.

SELECT FirstName,ProjectName FROM [EmployeeDetail] A LEFT OUTER JOIN [ProjectDetail] B
ON A.EmployeeID = B.EmployeeDetailID ORDER BY FirstName

Get employee name, project name order by firstname from "EmployeeDetail" and "ProjectDetail" for all employee if project is not assigned then display "-No Project Assigned".

SELECT FirstName, ISNULL(ProjectName,'-No Project Assigned') FROM [EmployeeDetail] A LEFT OUTER JOIN [ProjectDetail] B
ON A.EmployeeID = B.EmployeeDetailID ORDER BY FirstName

Get all project name even they have not matching any employeeid, in left table, order by firstname from "EmployeeDetail" and "ProjectDetail".

SELECT FirstName,ProjectName FROM [EmployeeDetail] A RIGHT OUTER JOIN [ProjectDetail] B
ON A.EmployeeID = B.EmployeeDetailID ORDER BY FirstName


Get complete record(employeename, project name) from both tables([EmployeeDetail],[ProjectDetail]), if no match found in any table then show NULL.

SELECT FirstName,ProjectName FROM [EmployeeDetail] A FULL OUTER JOIN [ProjectDetail] B
ON A.EmployeeID = B.EmployeeDetailID ORDER BY FirstName


Write a query to find out the employeename who has not assigned any project, and display "-No Project Assigned"( tables :- [EmployeeDetail],[ProjectDetail]).

SELECT FirstName, ISNULL(ProjectName,'-No Project Assigned') AS [ProjectName] FROM [EmployeeDetail] A LEFT OUTER JOIN [ProjectDetail] B
ON A.EmployeeID = B.EmployeeDetailID
WHERE ProjectName IS NULL


Write a query to find out the project name which is not assigned to any employee( tables :- [EmployeeDetail],[ProjectDetail]).

SELECT ProjectName FROM [EmployeeDetail] A RIGHT OUTER JOIN [ProjectDetail] B
ON A.EmployeeID = B.EmployeeDetailID
WHERE FirstName IS NULL

Write down the query to fetch EmployeeName & Project who has assign more than one project.

Select EmployeeID, FirstName, ProjectName from [EmployeeDetail] E INNER JOIN [ProjectDetail] P
ON E.EmployeeID = P.EmployeeDetailID
WHERE EmployeeID IN (SELECT EmployeeDetailID FROM [ProjectDetail] GROUP BY EmployeeDetailID HAVING COUNT(*) >1 )

Write down the query to fetch ProjectName on which more than one employee are working along with EmployeeName.

Select FirstName, ProjectName from [EmployeeDetail] E INNER JOIN [ProjectDetail] P
ON E.EmployeeID = P.EmployeeDetailID


Best Ways to Imporve SQL Query Performance

1. Use views and stored procedures instead of heavy-duty queries. This can reduce network traffic, because your client will send to server only stored procedure or view name (perhaps with some parameters) instead of large heavy-duty queries text. This can be used to facilitate permission management also, because you can restrict user access to table columns they should not see.

2. Try to use constraints instead of triggers, whenever possible. Constraints are much more efficient than triggers and can boost performance. So, you should use constraints instead of triggers, whenever possible.

3. Use table variables instead of temporary tables. Table variables require less locking and logging resources than temporary tables, so table variables should be used whenever possible. The table variables are available in SQL Server 2000 only.

4. Try to use UNION ALL statement instead of UNION, whenever possible. The UNION ALL statement is much faster than UNION, because UNION ALL statement does not look for duplicate rows, and UNION statement does look for duplicate rows, whether or not they exist. 

5. Try to avoid using the DISTINCT clause, whenever possible. Because using the DISTINCT clause will result in some performance degradation, you should use this clause only when it is necessary.

6. Try to avoid using SQL Server cursors, whenever possible. SQL Server cursors can result in some performance degradation in comparison with select statements. Try to use correlated sub-query or derived tables, if you need to perform row-by-row operations.

7. Try to avoid the HAVING clause, whenever possible. The HAVING clause is used to restrict the result set returned by the GROUP BY clause. When you use GROUP BY with the HAVING clause, the GROUP BY clause divides the rows into sets of grouped rows and aggregates their values, and then the HAVING clause eliminates undesired aggregated groups. In many cases, you can write your select statement so, that it will contain only WHERE and GROUP BY clauses without HAVING clause. This can improve the performance of your query.

8. If you need to return the total table’s row count, you can use alternative way instead of SELECT COUNT(*) statement. Because SELECT COUNT(*) statement make a full table scan to return the total table’s row count, it can take very many time for the large table. There is another way to determine the total row count in a table. You can use sysindexes system table, in this case. There is ROWS column in the sysindexes table. This column contains the total row count for each table in your database. So, you can use the following select statement instead of SELECT COUNT(*): SELECT rows FROM sysindexes WHERE id = OBJECT_ID(‘table_name’) AND indid < 2 So, you can improve the speed of such queries in several times. 

9. Try to restrict the queries result set by using the WHERE clause. This can results in good performance benefits, because SQL Server will return to client only particular rows, not all rows from the table(s). This can reduce network traffic and boost the overall performance of the query.

10. Use the select statements with TOP keyword or the SET ROWCOUNT statement, if you need to return only the first n rows. This can improve performance of your queries, because the smaller result set will be returned. This can also reduce the traffic between the server and the clients.

11. Try to restrict the queries result set by returning only the particular columns from the table, not all table’s columns. This can results in good performance benefits, because SQL Server will return to client only particular columns, not all table’s columns. This can reduce network traffic and boost the overall performance of the query. 1.Indexes 2.avoid more number of triggers on the table 3.unnecessary complicated joins 4.correct use of Group by clause with the select list 5 In worst cases Denormalization Index Optimization tips

12. Every index increases the time in takes to perform INSERTS, UPDATES and DELETES, so the number of indexes should not be very much. Try to use maximum 4-5 indexes on one table, not more. If you have read-only table, then the number of indexes may be increased.

13.Keep your indexes as narrow as possible. This reduces the size of the index and reduces the number of reads required to read the index.

14. Try to create indexes on columns that have integer values rather than character values.

15. If you create a composite (multi-column) index, the order of the columns in the key are very important. Try to order the columns in the key as to enhance selectivity, with the most selective columns to the leftmost of the key.

16. If you want to join several tables, try to create surrogate integer keys for this purpose and create indexes on their columns.

17. Create surrogate integer primary key (identity for example) if your table will not have many insert operations.

18. Clustered indexes are more preferable than nonclustered, if you need to select by a range of values or you need to sort results set with GROUP BY or ORDER BY.

19. If your application will be performing the same query over and over on the same table, consider creating a covering index on the table.

20. Include SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a T-SQL statement. This can reduce network traffic, because your client will not receive the message indicating the number of rows affected by a T-SQL statement.

Thursday, 28 August 2014