Few Interesting Questions and concepts

 There are 3 tables Titles, Authors and Title-Authors (check PUBS db). 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.

SELECT authors.au_lname, COUNT(*) AS BooksCount FROM authors INNER JOIN titleauthor ON authors.au_id = titleauthor.au_id INNER JOIN titles ON titles.title_id = titleauthor.title_id GROUP BY authors.au_lname ORDER BY BooksCount DESC

Write a SQL Query to find first day of month?

SELECT DATENAME(dw, DATEADD(dd, DATEPART(dd, GETDATE()) + 1, GETDATE())) AS FirstDay  

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 this query

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

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 salaryFROM employeeGROUP BY empid WITH ROLLUP ORDER BY empid

Update With Case

EmpID EmpName Gender
1 Raja Male
2 Rani Female

In the above table using one query u need to change Gender male to female and who is female need to change male. 

UPDATE Emp1 SET Gender=CASE Gender WHEN ‘Male’ THEN ‘Female’WHEN ‘female’ THEN ‘Male’END;

Query to find the maximum salary of an employee  

Select * from Employee where salary = (Select max(Salary) from Employee) 

Query to Find the Nth Maximum Salary 

Select * From Employee E1 Where    (31) = (Select Count(Distinct(E2.Salary)) From Employee E2 Where            E2.Salary > E1.Salary) 

Query to Find the 2nd Maximum Salary 

SELECT SALARY FROM    EMPLOYEEWHERE  SALARY=(SELECT MAX(SALARY) FROM    EMPLOYEE WHERE  SALARY <> (SELECT MAX (SALARY) FROM  EMPLOYEE)) 

select max(salary) as Salary from Emplo where salary!=(select max(salary) from Emplo) 

SELECT MAX(E1.salary)  FROM emplo E1 , emplo E2WHERE E1.salary< E2.salary

Creating a foreign-key constraint between columns of two tables defined with two different datatypes will produce an error

Ans : Yes

Important concepts

What’s the difference between a primary key and a unique key?
 Both primary key and unique enforce 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.

Define candidate key, alternate key, composite key.
 A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys. A key formed by combining at least two or more columns is called composite key.
What is a transaction and what are ACID properties?
 A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more information and explanation of these properties, see SQL Server books online or any RDBMS fundamentals text book. Explain different isolation levels An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you customize the isolation level at the connection level. Read Committed – A transaction operating at the Read Committed level cannot see changes made by other transactions until those transactions are committed. At this level of isolation, dirty reads are not possible but nonrepeatable reads and phantoms are possible. Read Uncommitted – A transaction operating at the Read Uncommitted level can see uncommitted changes made by other transactions. At this level of isolation, dirty reads, nonrepeatable reads, and phantoms are all possible. Repeatable Read – A transaction operating at the Repeatable Read level is guaranteed not to see any changes made by other transactions in values it has already read. At this level of isolation, dirty reads and nonrepeatable reads are not possible but phantoms are possible. Serializable – A transaction operating at the Serializable level guarantees that all concurrent transactions interact only in ways that produce the same effect as if each transaction were entirely executed one after the other. At this isolation level, dirty reads, nonrepeatable reads, and phantoms are not possible.
What’s the difference between DELETE TABLE and TRUNCATE TABLE commands?
 DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won’t log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back. TRUNCATE TABLE is functionally identical to DELETE statement with no WHERE clause: both remove all rows in the table. But TRUNCATE TABLE is faster and uses fewer system and transaction log resources than DELETE. The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE 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 TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column. 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. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint; instead, use DELETE statement without a WHERE clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger. TRUNCATE TABLE may not be used on tables participating in an indexed view

What are the steps you will take to improve performance of a poor performing query?
 This is a very open ended question and there could be a lot of reasons behind the poor performance of a query. But some general issues that you could talk about would be: No indexes, table scans, missing or out of date statistics, blocking, excess recompilations of stored procedures, procedures and triggers without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much normalization, excess usage of cursors and temporary tables. Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000 Performance monitor, Graphical execution plan in Query Analyzer

 What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
  Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other’s piece. Each process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one user’s process. A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely. Check out SET DEADLOCK_PRIORITY and “Minimizing Deadlocks” in SQL Server books online

What are statistics, under what circumstances they go out of date, how do you update them?
  Statistics determine the selectivity of the indexes. If an indexed column has unique values then the selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses these indexes in determining whether to choose an index or not while executing a query. Some situations under which you should update statistics: 1) If there is significant change in the key values in the index 2) If a large amount of data in an indexed column has been added, changed, or removed (that is, if the distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE statement and then repopulated 3) Database is upgraded from a previous version. Look up SQL Server books online for the following commands: UPDATE STATISTICS, STATS_DATE, DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats, sp_updatestats

 Index Optimization tips
• 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.
• 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.
• Try to create indexes on columns that have integer values rather than character values.
• 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.
• If you want to join several tables, try to create surrogate integer keys for this purpose and create indexes on their columns.
• Create surrogate integer primary key (identity for example) if your table will not have many insert operations.
• 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.
• If your application will be performing the same query over and over on the same table, consider creating a covering index on the table.
• You can use the SQL Server Profiler Create Trace Wizard with “Identify Scans of Large Tables” trace to determine which tables in your database may need indexes. This trace will show which tables are being scanned by queries instead of using an index.
• You can use sp_MSforeachtable undocumented stored procedure to rebuild all indexes in your database. Try to schedule it to execute during CPU idle time and slow production periods.
sp_MSforeachtable @command1=”print ‘?’ DBCC DBREINDEX (‘?’)”

Explain about Clustered and non clustered index? How to choose between a Clustered Index and a Non-Clustered Index?
There are clustered and nonclustered indexes. A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.
A nonclustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf nodes of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.
Consider using a clustered index for:
o Columns that contain a large number of distinct values.
o Queries that return a range of values using operators such as BETWEEN, >, >=, <, and <=.
o Columns that are accessed sequentially.
o Queries that return large result sets.
Non-clustered indexes have the same B-tree structure as clustered indexes, with two significant differences:
o The data rows are not sorted and stored in order based on their non-clustered keys.
o The leaf layer of a non-clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows. Each index row contains the non-clustered key value and one or more row locators that point to the data row (or rows if the index is not unique) having the key value.
o Per table only 249 non clustered indexes

 How many types of Joins?
Joins can be categorized as:
• Inner joins (the typical join operation, which uses some comparison operator like = or <>). These include equi-joins and natural joins.
Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table. For example, retrieving all rows where the student identification number is the same in both the students and courses tables.
• Outer joins. Outer joins can be a left, a right, or full outer join.
Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause:
• LEFT JOIN or LEFT OUTER JOIN -The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table.
• RIGHT JOIN or RIGHT OUTER JOIN – A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table.
• FULL JOIN or FULL OUTER JOIN – A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.
• Cross joins – Cross joins return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products. (A Cartesian join will get you a Cartesian product. A Cartesian join is when you join every row of one table to every row of another table. You can also get one by joining every row of a table to every row of itself.

What are the difference between a function and a stored procedure?
  Functions can be used in a select statement where as procedures cannot 
  Procedure takes both input and output parameters but Functions takes only input parameters
  Functions cannot return values of type text, ntext, image & timestamps where as procedures can
  Functions can be used as user defined datatypes in create table but procedures cannot
***Eg:-create table <tablename>(name varchar(10),salary getsal(name))
Here getsal is a user defined function which returns a salary type, when table is created no storage is allotted for salary type, and getsal function is also not executed, But when we are fetching some values from this table, getsal function get’s executed and the return
Type is returned as the result set.

What is the basic functions for master, msdb, tempdb databases?
Microsoft® SQL Server 2000 systems have four system databases:
• master – The master database records all of the system level information for a SQL Server system. It records all login accounts and all system configuration settings. master is the database that records the existence of all other databases, including the location of the database files.
• tempdb – tempdb holds all temporary tables and temporary stored procedures. It also fills any other temporary storage needs such as work tables generated by SQL Server. tempdb is re-created every time SQL Server is started so the system starts with a clean copy of the database.
By default, tempdb autogrows as needed while SQL Server is running. If the size defined for tempdb is small, part of your system processing load may be taken up with autogrowing tempdb to the size needed to support your workload each time to restart SQL Server. You can avoid this overhead by using ALTER DATABASE to increase the size of tempdb.
• model – The model database is used as the template for all databases created on a system. When a CREATE DATABASE statement is issued, the first part of the database is created by copying in the contents of the model database, then the remainder of the new database is filled with empty pages. Because tempdb is created every time SQL Server is started, the model database must always exist on a SQL Server system.
• msdb – The msdb database is used by SQL Server Agent for scheduling alerts and jobs, and recording operators.

1st Normal Form (1NF)
Definition: A table (relation) is in 1NF if
1. There are no duplicated rows in the table.
2. Each cell is single-valued (i.e., there are no repeating groups or arrays).
3. Entries in a column (attribute, field) are of the same kind.
Note: The order of the rows is immaterial; the order of the columns is immaterial.
Note: The requirement that there be no duplicated rows in the table means that the table has a key (although the key might be made up of more than one column—even, possibly, of all the columns).
Rule 1: Eliminate Repeating Groups. Make a separate table for each set of related attributes, and give each table a primary key.
2nd Normal Form (2NF)
Definition: A table is in 2NF if it is in 1NF and if all non-key attributes are dependent on all of the key.
Note: Since a partial dependency occurs when a non-key attribute is dependent on only a part of the (composite) key, the definition of 2NF is sometimes phrased as, “A table is in 2NF if it is in 1NF and if it has no partial dependencies.”
Rule 2: Eliminate Redundant Data. If an attribute depends on only part of a multi-valued key, remove it to a separate table.
3rd Normal Form (3NF)
Definition: A table is in 3NF if it is in 2NF and if it has no transitive dependencies.
Rule 3: Eliminate Columns Not Dependent on Key. If attributes do not contribute to a description of the key, remove them to a separate table.
Boyce-Codd Normal Form (BCNF)
Definition: A table is in BCNF if it is in 3NF and if every determinant is a candidate key.
4th Normal Form (4NF)
Definition: A table is in 4NF if it is in BCNF and if it has no multi-valued dependencies.
Rule 4: Isolate Independent Multiple Relationships. No table may contain two or more l:n or n:m relationships that are not directly related.
5th Normal Form (5NF)
Definition: A table is in 5NF, also called “Projection-Join Normal Form” (PJNF), if it is in 4NF and if every join dependency in the table is a consequence of the candidate keys of the table.
Rule 5: Isolate Semantically Related Multiple Relationships. There may be practical constraints on information that justify separating logically related many-to-many relationships.
Domain-Key Normal Form (DKNF)
Definition: A table is in DKNF if every constraint on the table is a logical consequence of the definition of keys and domains.

Keep on coming…. Dayaa

Comments
  1. Charanjot Singh says:

    Hello Dear,
    Its really very good questions for interview, actually i have faced these questions in interview and it helps us me alot to solve my query but i want more question of SQL Server which generally asked in interview.
    Thank You n Thank you very much.

  2. Ajay says:

    Brillent topic and very imp. meterial u have provided.
    keep it budy.

    with best wishes….

  3. Murali says:

    Good material ..keep posting such material….

  4. Murali says:

    Good…keep posting….

  5. Murali says:

    Good …keep posting…

  6. Anirudh kumar says:

    hello sir

    good material and very help ful for me.

    so keep posting

  7. Vikas Gupta says:

    gr8 collection of FAQ’s
    seriously all of these questions wer askd to me in in interview

    unfortunately dat tym i didnt knw abt this forum 😛

  8. ANIL CHOW says:

    Awesome collection!!!
    I really appreciate all the members for time and effort in this topic.
    If everybody share we can get a lot.

  9. Satyam says:

    Hi
    Its Really usefull article,
    I am working as a .Net and SQL server developer in Hyderabad for 21 months but i am very much interested to work as a fulltime SQL Server developer.
    I passed out my MCA(Master of Computer Applications) in the year 2007.Can any body clarify me how to search as a fulltime sql developer and how the future for it.
    thanks in advance.

    Ragards
    Satyam.

  10. yes,good,but all the concepts are explained in lengthy,i am expecting the answers all very short

    anyway

    thanks for your blog
    regards
    rajesh

  11. pavan says:

    good material and need more

  12. Bindiya says:

    useful and great questions..please keep updating

  13. Maverik says:

    really very helpful…ans answer are really elaborated and written very well thanks a lot

  14. Maverik says:

    i have created a table and a unique key on column..but im able to enter null twice in that column..but as per first conceptual question its not possible..please explain me…

  15. poetryman69 says:

    cool, thanks for the practice

  16. Rohit says:

    Can you also add query related to deletion of duplicate records?

    It is also asked most of the time in interviews.

  17. Gunjan says:

    Good practice query and q/a .Keep it up…
    Thanks a lot for sharing!
    Please add more queries with tables.

  18. Sush says:

    Its Realy very helpfull for me.. thanks a lot for this blog..

  19. Ranjeet says:

    Hi,

    I have an interesting query to find nth MAX/MIN Salary etc. It goes like this,

    SELECT DISTINCT (a.Salary) FROM Emp1 a WHERE &N =(SELECT COUNT (DISTINCT (b.Salary)) FROM Emp1 b WHERE a.Salary<=b.Salary)

    Enter value for '&N'

  20. Chris says:

    A very good site for SQL server interview questions organised by topic. If you feel you need to brush up interview questions related to specific topics, this website will be of great use. God bless the person who has contributed to this site. Very useful.

    http://venkatsqlinterview.blogspot.com/2011/05/sql-server-interview-questions.html

  21. Lak says:

    Thanks a lot for the questions..

  22. We appreciate you for writing articles such as these to sustain awareness.
    Be sure to check out my blog and follow it, too!

  23. I really love your blog.. Great colors & theme. Did you make this web site yourself?
    Please reply back as I’m trying to create my own site and
    want to find out where you got this from or exactly what the theme is named.
    Many thanks!

  24. Simply want to say your article is as astounding.
    The clearness to your publish is simply spectacular and i could assume you’re an expert
    in this subject. Well together with your permission let me
    to take hold of your feed to stay updated with forthcoming post.
    Thanks 1,000,000 and please carry on the rewarding
    work.

Leave a comment