Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Friday, January 21, 2011

SQL Queries FAQ

T-SQL Queries
1. 2 tablesEmployee Phone
empid
empname
salary
mgrid empid
phnumber

2. Select all employees who doesn't have phone?










SELECT DISTINCT m1.moviename
FROM MovieTable m1 INNER JOIN
MovieTable m2 ON m1.moviename = m2.moviename
WHERE (m1.person = 'amitabh' AND m2.person = 'vinod' OR
m2.person = 'amitabh' AND m1.person = 'vinod') AND (m1.role = 'actor')
AND (m2.role = 'actor')
ORDER BY m1.moviename

11. There are two employee tables named emp1 and emp2. Both contains
same structure (salary details). But Emp2 salary details are incorrect
and emp1 salary details are correct. So, write a query which corrects
salary details of the table emp2


update a set a.sal=b.sal from emp1 a, emp2 b where a.empid=b.empid

12. Given a Table named "Students" which contains studentid, subjectid
and marks. Where there are 10 subjects and 50 students. Write a Query
to find out the Maximum marks obtained in each subject.

13. In this same tables now write a SQL Query to get the studentid
also to combine with previous results.

14. Three tables – student , course, marks – how do go @ finding name
of the students who got max marks in the diff courses.
SELECT student.name, course.name AS coursename, marks.sid, marks.mark
FROM marks INNER JOIN
student ON marks.sid = student.sid INNER JOIN
course ON marks.cid = course.cid
WHERE (marks.mark =
(SELECT MAX(Mark)
FROM Marks MaxMark
WHERE MaxMark.cID = Marks.cID))

15. There is a table day_temp which has three columns dayid, day and
temperature. How do I write a query to get the difference of
temperature among each other for seven days of a week?
SELECT a.dayid, a.dday, a.tempe, a.tempe - b.tempe AS Difference
FROM day_temp a INNER JOIN
day_temp b ON a.dayid = b.dayid + 1

OR
Select a.day, a.degree-b.degree from temperature a, temperature b
where a.id=b.id+1

16. There is a table which contains the names like this. a1, a2, a3,
a3, a4, a1, a1, a2 and their salaries. Write a query to get grand
total salary, and total salaries of individual employees in one query.
SELECT empid, SUM(salary) AS salary
FROM employee
GROUP BY empid WITH ROLLUP
ORDER BY empid

17. How to know how many tables contains empno as a column in a database?
SELECT COUNT(*) AS Counter
FROM syscolumns
WHERE (name = 'empno')

18. Find duplicate rows in a table? OR I have a table with one column
which has many records which are not distinct. I need to find the
distinct values from that column and number of times it's repeated.
SELECT sid, mark, COUNT(*) AS Counter
FROM marks
GROUP BY sid, mark
HAVING (COUNT(*) > 1)

19. How to delete the rows which are duplicate (don't delete both
duplicate records).
SET ROWCOUNT 1
DELETE yourtable
FROM yourtable a
WHERE (SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1 AND
b.age1 = a.age1) > 1
WHILE @@rowcount > 0
DELETE yourtable
FROM yourtable a
WHERE (SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1 AND
b.age1 = a.age1) > 1
SET ROWCOUNT 0

20. How to find 6th highest salary
SELECT TOP 1 salary
FROM (SELECT DISTINCT TOP 6 salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary

21. Find top salary among two tables
SELECT TOP 1 sal
FROM (SELECT MAX(sal) AS sal
FROM sal1
UNION
SELECT MAX(sal) AS sal
FROM sal2) a
ORDER BY sal DESC

22. Write a query to convert all the letters in a word to upper case
SELECT UPPER('test')

23. Write a query to round up the values of a number. For example even
if the user enters 7.1 it should be rounded up to 8.
SELECT CEILING (7.1)

24. Write a SQL Query to find first day of month?

SELECT DATENAME(dw, DATEADD(dd, - DATEPART(dd, GETDATE()) + 1,
GETDATE())) AS FirstDay
Datepart Abbreviations
year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw
hour hh
minute mi, n
second ss, s
millisecond ms

25. Table A contains column1 which is primary key and has 2 values (1,
2) and Table B contains column1 which is primary key and has 2 values
(2, 3). Write a query which returns the values that are not common for
the tables and the query should return one column with 2 records.
SELECT a.col1
FROM a, b
WHERE a.col1 <>
(SELECT b.col1
FROM a, b
WHERE a.col1 = b.col1)
UNION
SELECT b.col1
FROM a, b
WHERE b.col1 <>
(SELECT a.col1
FROM a, b
WHERE a.col1 = b.col1)

26. There are 3 tables Titles, Authors and Title-Authors. Write the
query to get the author name and the number of books written by that
author, the result should start from the author who has written the
maximum number of books and end with the author who has written the
minimum number of books.

27.
UPDATE emp_master
SET emp_sal =
CASE
WHEN emp_sal > 0 AND emp_sal <= 20000 THEN (emp_sal * 1.01) WHEN emp_sal > 20000 THEN (emp_sal * 1.02)
END
SELECT fname
FROM employee
WHERE (empid IN
(SELECT empid
FROM city a
WHERE city IN
(SELECT city
FROM city b
GROUP BY city
HAVING COUNT(city) > 1)))

10. There is a table named MovieTable with three columns - moviename,
person and role. Write a query which gets the movie details where Mr.

Amitabh and Mr. Vinod acted and their role is actor
.
SELECT *
FROM employee LEFT OUTER JOIN
phone ON employee.empid = phone.empid
WHERE (phone.office IS NULL OR phone.office = ' ')
AND (phone.mobile IS NULL OR phone.mobile = ' ')
AND (phone.home IS NULL OR phone.home = ' ')

8. Find employee who is living in more than one city.
Two Tables:
SELECT e1.empname AS EmpName, e2.empname AS ManagerName
FROM Employee e1 INNER JOIN
Employee e2 ON e1.mgrid = e2.empid
ORDER BY e2.mgrid

7. 2 tables emp and phone.
emp fields are - empid, name
Ph fields are - empid, ph (office, mobile, home). Select all employees
who doesn't have any ph nos.
SELECT empname
FROM employee
WHERE (empid IN
(SELECT DISTINCT mgrid
FROM employee))

6. Write a Select statement to list the Employee Name, Manager Name
under a particular manager?
SELECT TOP 3 empid, salary
FROM employee
ORDER BY salary DESC

5. Display all managers from the table. (manager id is same as emp id)
SELECT empname
FROM employee
WHERE (empid IN
(SELECT empid
FROM phone
GROUP BY empid
HAVING COUNT(empid) > 1))

4. Select the details of 3 max salaried employees from employee table.
SELECT empname
FROM Employee
WHERE (empid NOT IN
(SELECT DISTINCT empid
FROM phone))


3. Select the employee names who is having more than one phone numbers.
Emp City
Empid Empid
empName City

Salary
SELECT empname, fname, lname
FROM employee
WHERE (empid IN
(SELECT empid
FROM city
GROUP BY empid
HAVING COUNT(empid) > 1))

9. Find all employees who is living in the same city. (table is same
as above)

Different Date and Time Format

1)How to get this format
Mon DD YYYY HH:MIAM (or PM)
SELECT CONVERT(VARCHAR(20), GETDATE(), 100)
MM/DD/YY
SELECT CONVERT(VARCHAR(8), GETDATE(), 1) AS [MM/DD/YY]
MM/DD/YYYY
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY]
YY.MM.DD
SELECT CONVERT(VARCHAR(8), GETDATE(), 2) AS [YY.MM.DD]
YYYY.MM.DD
SELECT CONVERT(VARCHAR(10), GETDATE(), 102) AS [YYYY.MM.DD]
DD/MM/YY
SELECT CONVERT(VARCHAR(8), GETDATE(), 3) AS [DD/MM/YY]
DD/MM/YYYY
SELECT CONVERT(VARCHAR(10), GETDATE(), 103) AS [DD/MM/YYYY]
DD.MM.YY
SELECT CONVERT(VARCHAR(8), GETDATE(), 4) AS [DD.MM.YY]
DD.MM.YYYY
SELECT CONVERT(VARCHAR(10), GETDATE(), 104) AS [DD.MM.YYYY]
DD-MM-YY
SELECT CONVERT(VARCHAR(8), GETDATE(), 5) AS [DD-MM-YY]
DD-MM-YYYY
SELECT CONVERT(VARCHAR(10), GETDATE(), 105) AS [DD-MM-YYYY]
DD Mon YY
SELECT CONVERT(VARCHAR(9), GETDATE(), 6) AS [DD MON YY]
DD Mon YYYY
SELECT CONVERT(VARCHAR(11), GETDATE(), 106) AS [DD MON YYYY]
Mon DD, YY
SELECT CONVERT(VARCHAR(10), GETDATE(), 7) AS [Mon DD, YY]
Mon DD, YYYY
SELECT CONVERT(VARCHAR(12), GETDATE(), 107) AS [Mon DD, YYYY]
HH:MM:SS
SELECT CONVERT(VARCHAR(8), GETDATE(), 108)
Mon DD YYYY HH:MI:SS:MMMAM (or PM)
SELECT CONVERT(VARCHAR(26), GETDATE(), 109)
MM-DD-YY
SELECT CONVERT(VARCHAR(8), GETDATE(), 10) AS [MM-DD-YY]
MM-DD-YYYY
SELECT CONVERT(VARCHAR(10), GETDATE(), 110) AS [MM-DD-YYYY]
YY/MM/DD
SELECT CONVERT(VARCHAR(8), GETDATE(), 11) AS [YY/MM/DD]
YYYY/MM/DD
SELECT CONVERT(VARCHAR(10), GETDATE(), 111) AS [YYYY/MM/DD]
YYMMDD
SELECT CONVERT(VARCHAR(6), GETDATE(), 12) AS [YYMMDD]
YYYYMMDD
SELECT CONVERT(VARCHAR(8), GETDATE(), 112) AS [YYYYMMDD]
DD Mon YYYY HH:MM:SS:MMM(24h)
SELECT CONVERT(VARCHAR(24), GETDATE(), 113)
HH:MI:SS:MMM(24H)
SELECT CONVERT(VARCHAR(12), GETDATE(), 114) AS [HH:MI:SS:MMM(24H)]

How to check a primary key exists or not in table

IF OBJECTPROPERTY( OBJECT_ID( '[dbo].[Customers]' ), 'TableHasPrimaryKey' ) = 1
PRINT '[dbo].[Customers] table has a primary key.

How to get first day of week

select DATEADD(DD, 1 - DATEPART(DW, getdate()),getdate())

How to get number of days in a month

select CASE WHEN MONTH(getdate()) IN (1, 3, 5, 7, 8, 10, 12) THEN 31 WHEN MONTH(getdate()) IN (4, 6, 9, 11) THEN 30 ELSE CASE WHEN (YEAR(getdate()) % 4 = 0 AND YEAR(getdate()) % 100 != 0) OR (YEAR(getdate()) % 400 = 0) THEN 29 ELSE 28 END end

How to get number of row in each table in database

SELECT obj.NAME, ind.rowcnt FROM sysindexes AS ind INNER JOIN sysobjects AS obj ON ind.id = obj.id WHERE ind.indid < 2 AND OBJECTPROPERTY(obj.id, 'IsMSShipped') = 0 ORDER BY obj.NAME

How to select all duplicate records from a table

select Col, count(Col) from TableName group by field having count(*) > 1

How to Enable CLR integration in SQL Server

EXEC sp_configure 'clr enabled', 1;
RECONFIGURE WITH OVERRIDE;
Go

How to disable CLR integration in SQL Server

EXEC sp_configure 'clr enabled', 0;
RECONFIGURE WITH OVERRIDE;
Go

How to get number of records in a table

SELECT * FROM table1
SELECT COUNT(*) FROM table1
SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2

What is a join and List different types of joins

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.
Types of joins:
INNER JOINs,
OUTER JOINs,
CROSS JOINs.
OUTER JOINs are further classified as
LEFT OUTER JOINS,
RIGHT OUTER JOINS and
 FULL OUTER JOINS.

Difference between Triggers and Storedprocedures

Triggers are basically used to implement business rules.Triggers is also similar to stored procedures.The difference is that it can be activated when data is added or edited or deleted from a table in a database.Triggers are special kind of stored procedures that get executed automatically when an INSERT,UPDATE or DELETE operation takes place on a table.

How to get number of Maximum connection can be establish to SQL

SELECT @@MAX_CONNECTIONS

What do you mean by Filtered indexes

Filtered indexes are a new feature in SQL 2008 and they allow for an index to contain only some of the rows in the table. Prior to this, an index would always have, at the leaf level, the same number of rows as the table. With filtered indexes, an index can be based on just a subset of the rows.When creating a filtered index, a predicate is specified as part of the index creation statement. There are several limitations on this predicate. The comparison ca
nnot reference a computed column, a column that is declared as a user-defined type, a spatial column or a hierarchyid column.A clustered index cannot be filtered as it is the actual table.

Here are some instruction when creating a store procedure to increase speed

Get top two records without Top keyword

set rowcount 2
select column,column1 from tblEmployeeMaster

Define some facts about Temporary table and there types

Different ways of moving data from databases

There are different methods of moving data
(1)BACKUP and RESTORE
(2)detaching
(3)Attaching databases
(4)Replication
(5) DTS
(6)BCP
(7)logshipping
(8) INSERT...SELECT
(9)SELECT...INTO
(10) creating INSERT scripts to generate data.

What is the advantage of SET NOCOUNT ON

Why not to use prefix sp in store procedure

Thses prefix is used by master database so SQL server first searches in the master database and then in the current session database. So its time taken is much higher master database causes extra overhead and also get wrong result in case of same name in master database.

Table which doesnot have cluster or noncluster index is called

Unindexed table or Heap

Difference Between GETDATE and SYSDATETIME

When we use GETDATE the precision is till miliseconds and in case of SYSDATETIME the precision is till nanoseconds.