Next part of TSQL Interview Questions, contd. from my previous post.
101. What are the required/mandatory parameters that have to be passed with RAISEERROR statement?
- message _id or message_str
- severity, and
102. Difference between RAISEERROR and THROW
103. What severity level errors are managed in TRY-CATCH block?
104. What are row constructors?
New way to insert multiple records in a table with INSERT statement. Also known as Table Value Constructor.
More on: http://msdn.microsoft.com/en-us/library/dd776382.aspx
105. What is SCD (Slowly Changing Dimensions)? What are its types?
106. How many types of internal joins are there in SQL Server?
- Nested loop join
- Merge join
- Hash join
More on: http://msdn.microsoft.com/en-us/library/ms191426.aspx
107. What are pages in SQL Server? How many types of pages are there?
A page in SQL Server is an 8 KB data storage area.
There are 8 types of pages:
4. Global Allocation Map, Shared Global Allocation Map
5. Page Free Space
6. Index Allocation Map
7. Bulk Changed Map
8. Differential Changed Map
More on: http://msdn.microsoft.com/en-us/library/ms190969.aspx
108. How many data sources are available in SSIS?
- DataReader Source in 2005 & ADO NET Source in 2008 & above.
- Excel Source
- Flat File Source
- OLE DB Source
- Raw File Source
- Script Component
- XML Source
109. How will you deploy an SSIS package in testing, staging & production environments?
The dtutil is the command prompt utility which is used to manage SSIS packages.
This utility can copy, move, delete or verify the existence of a package.
More on: http://msdn.microsoft.com/en-us/library/ms162820.aspx
110. Where will you use Conditional Split transformation?
More info: http://msdn.microsoft.com/en-us/library/ms137886.aspx
111. What is live lock, deadlock and what is Lock escalation?
112. If you are working on a SQL database and if suddenly a developer changes the code and your queries results start giving errors, how will you check using a T-SQL query (on system tables) that what has changed in the database.
select o.name, o.object_id, o.modify_date, c.text
from sys.objects o
join sys.syscomments c
on o.object_id = c.id
113. Difference between Nested loops join, Merge join & Hash Join.
114. What are surrogate keys in a data warehouse?
… I’ll be adding more questions on upcoming post.
Next part of TSQL Interview Questions, contd. from my previous post.
76. What are Running totals and how would you calculate them? Create a single SQL statement starting with SELECT or ;WITH.
77. What are the various SSIS logging mechanisms?
- Text file
- SQL Server Profiler
- SQL Server
- Windows Event Log
- XML File
MS BOL link: http://msdn.microsoft.com/en-us/library/ms140246.aspx
78. On which table the SSIS SQL Server logs are stored?
On 2005 its sysdtslog90 & on 2008 its sysssislog.
More on SSIS logging on: https://sqlwithmanoj.wordpress.com/2011/06/15/logging-in-ssis-using-sql-server-log-provider/
79. Reverse a String value without using REVERSE() function and WHILE loop. Should be a single SQL statement/query.
80. What is the use of BCP utility in SQL Server and how will you use it?
81. Is there any difference between Excel Source in SSIS 2005 & 2008?
82. Difference between Bookmark lookup & RID lookup?
83. How nested transactions behave?
Here is a scenario:
I have a transaction T and inside this there are 2 transactions T1 AND T2.
If TRANSACTION T2 fails then what happens to transaction T and T1
84. How will you check if a stored procedure with 500 line of code is running very slow? What steps will you take to optimize it?
85. New features in SQL Server 2005 compared to SQL Server 2000 you’ve worked with.
PIVOT, UNPIVOT, Ranking functions (row_number, rank, dense_rank, ntile), CTEs, Grouping sets (ROLUP, CUBE), Intersect, Except, OUTPUT clause, Merge statement, Try-Catch, BIDS (SSIS, SSRS, SSAS), CLR, SMO.
New datatypes: XML, VARCHAR(max), NVARCHAR(max), VARBINARY(max) deprecating the TEXT, NTEXT AND IMAGE datatypes.
Database (SMTP) mail, SSMS, DMVs, Express Edition, Service Broker, Data Encryption, MARS
86. How will you copy unique records from duplicates in source to destination in SSIS?
87. What transformation will you use to concatenate First name and Last name in SSIS?
88. What do you mean by selectivity of a column/table?
The selectivity is what goes with the cardinality concept. The “cardinality” refers to the number of “distinct” values, as in the set theory so, take a column “SEX”. The possible values are “male” and “female” (ignoring for the moment other possible values like “unknown” or even “other”) … so, your cardinality for that column would be 2, no matter how many rows you have in that table.
The selectivity is the “number of rows” / “cardinality”, so if you have 10K customers, and search for all “female”, you have to consider that the search would return 10K/2 = 5K rows, so a very “bad” selectivity.
The column for the primary key on the other side is “unique”, and hence the cardinality is equal to the number of rows, by definition. So, the selectivity for searching a value in that column will be 1, by definition, which is the best selectivity possible.
89. Difference between EXISTS & IN, which one gives good performance?
90. What output will “SELECT 1/2″ statement give?
0, it will give zero.
91. What is Database Partitioning?
This involves 4 steps:
1. Create Database with different file groups
2. Create Partition Function
3. Create Partition Scheme
4. Create Partitioned Table or Index
92. What is the use of NOLOCK option?
93. How many types of recovery models are available for a database?
2. Bulk logged
94. How many types of temporary tables are there in SQL Server?
- Local Temp tables (#)
- Global temp tables (##)
- Table variables (@)
95. In how many ways you can get a table’s row count?
--// 1. Using COUNT(*) Select count(*) from Person.Contact --// 2. using COUNT(1) select count(1) from Person.Contact --// 3. Using SUM() aggregate function select sum(1) from Person.Contact --// 4. Using sysindexes view select object_name(id), rows from sys.sysindexes where object_name(id) = 'Contact' and indid<2 --// 5. Using sp_spaceused system SP exec sp_spaceused 'Person.Contact' --// 6. Using DBCC CHECKTABLE function DBCC CHECKTABLE('Person.Contact') --// Note: Before running 5 & 6 you may need to run this script: DBCC UPDATEUSAGE ('AdventureWorks','Person.Contact') WITH COUNT_ROWS
96. In how many ways you can select distinct records from a table?
97. In how many ways you can select top 1 row?
98. What are the new features introduced in SQL Server 2008 R2?
99. What are the new features added SQL Server 2012 (Denali)?
100. What new feature has been added to TRY-CATCH construct?
… more questions on next post Part-5.
Next part of TSQL Interview Questions, contd. from my previous post.
51. What are Integrity Constraints?
52. Difference between:
- Views, Tables & Stored Procedures
- Stored Procedures & Functions
- Sub Query & Co-related sub-query
- Physical & Logical Schema
- Table variable & Temporary Tables
- UNIQUE and CLUSTERED INDEXES
- Triggers and Constraints
- Primary Key & Unique Key
53. What do you mean by Referential Integrity? How will you attain it?
By using Foreign Keys.
54. What is the sequence for logical query processing, what is the order?
FROM, [JOIN CONDITION, JOIN TABLE ...], ON, OUTER, WHERE, GROUP BY, CUBE/ROLLUP/GROUPING SETS, HAVING, SELECT, DISTINCT, ORDER BY, TOP
56. What is ANSI_NULL?
57. How will you rename a table?
By using sp_rename stored procedure.
58. What are ACID properties, define them?
A – Atomicity (Transaction is atomic, if one part fails, then the entire transaction fails)
C – Consistency (Any transaction the database performs will take it from one consistent state to another, only valid data will be written to the database)
I – Isolation (Other operations cannot access data that has been modified during a transaction that has not yet completed)
D – Durability (On a transaction’s success the transaction will not be lost, the transaction’s data changes will survive system failure, and that all integrity constraints have been satisfied)
More on: http://en.wikipedia.org/wiki/ACID
59. What is a Live Lock?
60. Difference between “Dirty Read” & “Phantom Read”. Explain both of them?
61. What is BITMAP index and BITMAP filtering?
62. What are different ISOLATION Levels (High to Low)?
- REPEATABLE READ (phantom read)
- READ COMMITTED
- READ UNCOMMITTED (dirty read)
63. What is the highest, lowest & default ISOLATION Level?
Lowest: READ UNCOMMITTED
Default: READ COMMITTED
64. What is SERIALIZABLE Isolation Level?
65. What is a CTE & how it is different from a Derived table? Example of recursive CTE.
66. What are design considerations for a Clustered Index & Non Clustered Index?
67. What are UDFs and their usage in a SELECT query?
- TABLE VALUED
- MULTI LINE TABLE VALUED
68. What are UNION, UNION ALL, EXCEPT & INTERSECTION keywords?
69. What are File Groups in SQL Server? What is its benefit? Explain any scenario where you will use multiple file groups.
70. How will you handle & avoid Deadlock?
71. What are Implicit Transactions?
72. How will you know Index usage on tables?
- Execution plan
- SET STATISTICS PROFILE ON
73. What are Indexed Views and their use? How will you create them?
A view must meet the following requirements before you can create a clustered index on it:
- The ANSI_NULLS and QUOTED_IDENTIFIER options must have been set to ON when the CREATE VIEW statement was executed.
- The ANSI_NULLS option must have been set to ON for the execution of all CREATE TABLE statements that create tables referenced by the view.
- The view must not reference any other views, only base tables.
- All base tables referenced by the view must be in the same database as the view and have the same owner as the view.
- The view must be created with the SCHEMABINDING option. Schema binding binds the view to the schema of the underlying base tables.
- User-defined functions referenced in the view must have been created with the SCHEMABINDING option.
- Tables and user-defined functions must be referenced by two-part names in the view. One-part, three-part, and four-part names are not allowed.
- If the view definition uses an aggregate function, the SELECT list must also include COUNT_BIG (*).
- If GROUP BY is specified, the view select list must contain a COUNT_BIG(*) expression, and the view definition cannot specify HAVING, ROLLUP, CUBE, or GROUPING SETS.
The SELECT statement in the view cannot contain the following Transact-SQL syntax elements:
- The * or table_name.* syntax to specify columns. Column names must be explicitly stated.
- An expression on a column used in the GROUP BY clause, or an expression on the results of an aggregate.
- A derived table.
- A common table expression (CTE).
- Rowset functions.
- UNION, EXCEPT or INTERSECT operators.
- Outer or self joins.
- TOP clause.
- ORDER BY clause.
- DISTINCT keyword.
- COUNT (COUNT_BIG(*) is allowed.)
- A SUM function that references a nullable expression.
- The OVER clause, which includes ranking or aggregate window functions.
- A CLR user-defined aggregate function.
- The full-text predicates CONTAINS or FREETEXT.
- COMPUTE or COMPUTE BY clause.
- The CROSS APPLY or OUTER APPLY operators.
- The PIVOT or UNPIVOT operators
- Table hints (applies to compatibility level of 90 or higher only).
- Join hints.
- Direct references to Xquery expressions. Indirect references, such as Xquery expressions inside a schema-bound user-defined function, are acceptable.
74. What do you mean by Concurrency control?
75. What do you understand by Star & Snowflake schema and whats the difference between them?
… more questions on next post Part-4.
Next part of TSQL Interview Questions, contd. from my previous post.
26. What are the virtual tables in Triggers?
Inserted & Deleted
27. What is benefit of a having stored-procedure?
28. Can stored-procedures be recursive? And upto how much level?
Yes, 32 levels.
29. How you can load large data in SQL Server?
BulkCopy is a tool used to copy huge amount of data from tables. BULK INSERT command helps to Imports a data file into a database table or view in a user-specified format.
30. What is the trade-offs of a BCP command, when various users are loading data in a particular table at same time?
31. How can you copy schema from one SQL Server to another?
DTS, import/export wizard.
Scripting out Database objects.
32. What is the benefit of a Temporary Table, how would you define it?
33. What is a table called that has ## before its name, what is its scope?
Table with ## (double pound signs) is called Global Temp table. Scope is outside the session but only till the original session lasts.
34. What is the scope of a temporary table?
Scope is limited to its session only.
35. What is Mutex error in Triggers?
MSDN link: http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/c86c97a7-73ea-482e-9529-e2407bd7018c
36. What is the use of WITH (nolock)?
Table Hints, MS BOL: http://msdn.microsoft.com/en-us/library/ms187373(v=SQL.90).aspx
37. What are the various Isolation levels?
a) Read Uncommitted Isolation Level
b) Read Committed Isolation Level
c) Repeatable Read Isolation Level
d) Serializable Isolation Level
e) Snapshot Isolation Level
f) Read Committed Snapshot Isolation Level
38. What are implicit & explicit cursors?
39. Define the life cycle of a Cursor.
40. How would you know that if a cursor is open or closed?
declare @mycursor cursor declare @FirstName varchar(12) select CURSOR_STATUS('variable','@mycursor') --// -2 (Not applicable) set @mycursor = cursor for select FirstName from Person.Contact select CURSOR_STATUS('variable','@mycursor') --// -1 (The cursor is closed) open @mycursor select CURSOR_STATUS('variable','@mycursor') --// 1 (The result set of the cursor has at least one row) fetch next from @mycursor into @FirstName select CURSOR_STATUS('variable','@mycursor') --// 1 (The result set of the cursor has at least one row) close @mycursor select CURSOR_STATUS('variable','@mycursor') --// -1 (The cursor is closed) deallocate @mycursor select CURSOR_STATUS('variable','@mycursor') --// -2 (Not applicable) select CURSOR_STATUS('variable','@nocursor') --// -3 (A cursor with the specified name does not exist)
41. How many non-clustered indexes can you have in a table?
Upto 249 non-clustered indexes can be created in a table.
42. What all indexes can you have in a table?
One Clustered Index, one or more than one non-clustered index, unique index, filtered, spatial, xml, etc.
MS BOL: http://msdn.microsoft.com/en-us/library/ms175049.aspx
43. How will you know what indexes a particular table is using?
44. What is the benefit of cross joins? How would you use a where clause with Cross Joins?
The common example is when company wants to combine each product with a pricing table to analyze each product at each price.
45. Difference between VARCHAR & VARCHAR2?
VARCHAR2 is specific to Oracle. MS SQL Server has VARCHAR & VARCHAR(MAX) data types.
46. What is de-normalization?
De-normalization is the process of attempting to optimize the performance of a database by adding redundant data. It is sometimes necessary because current DBMSs implement the relational model poorly. A true relational DBMS would allow for a fully normalized database at the logical level, while providing physical storage of data that is tuned for high performance. De-normalization is a technique to move from higher to lower normal forms of database modeling in order to speed up database access. http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/8c54d1d2-5fbd-4b62-a07f-16c34a863668
47. How would you get error & row number at the same time?
If @@Rowcount is checked after Error checking statement then it will have 0 as the value of @@Recordcount as it would have been reset.
And if @@Recordcount is checked before the error-checking statement then @@Error would get reset. To get @@error and @@rowcount at the same time do both in same statement and store them in local variable. SELECT @RC = @@ROWCOUNT, @ER = @@ERROR
48. What is Collation?
MS BOL link: http://msdn.microsoft.com/en-us/library/aa174903(v=sql.80).aspx
My Blog link: https://sqlwithmanoj.wordpress.com/page/2/?s=collation
49. Types of Replication? Difference between Merge & Transactional Replication.
MS BOL link: http://msdn.microsoft.com/en-us/library/ms165713(v=sql.90).aspx
50. What can you do with COLASCE function?
MS BOL link: http://msdn.microsoft.com/en-us/library/ms190349.aspx
… more questions on next post [Part-3].
These are the following common question that I faced in various TSQL interviews.
… I’ll be updating this post with more questions.
1. Difference between SQL Server 2000 & SQL Server 2005 features, or new features of 2005 vs 2000.
- Ranking functions (ROW_NUMBER, RANK, DENSE_RANK, NTILE)
- Exception handling (TRY-CATCH block)
- CTE (Common Table Expressions)
- PIVOT, UNPOVIT
- CUBE, ROLUP & GROUPING SET
2. What tools do you use for performance tuning?
Query Analyzer, Profiler, Index Wizard, Performance Monitor
3. What is SQL Profiler? What it does? What template do you use?
More Info: http://www.extremeexperts.com/SQL/Articles/TraceTemplate.aspx
4. How can you execute an SQL query from command prompt?
OSQL & SQLCMD
More Info: http://msdn.microsoft.com/en-us/library/ms162773.aspx
5. Difference between DELETE & TRUNCATE statement? Which statement can be Rollbacked?
- With DELETE we can provide conditional WHERE clause to remove/delete specific rows, which is not possible with TRUNCATE.
- TRUNCATE is faster than DELETE as Delete keeps log of each row it deletes in transaction logs, but truncate keeps log of only de-allocated pages in transaction logs.
- Both statements can be rolled backed if provided in a transaction (BEGIN TRANS). If not then none of them can be rollbacked.
- DELETE is DML just like INSERT, UPDATE, but TRANCATE is DDL, just like CREATE, ALTER, DROP
Link: Complete differences on in Delete & Truncate.
6. What are extended stored procedures? Can you create your own extended stored-proc?
More Info: http://msdn.microsoft.com/en-us/library/ms175200.aspx
7. How can you execute a DOS command from SQL or through SQL query by using xp_cmdshell?
exec xp_cmdshell 'dir c:\*.exe'
8. How will you insert result set of the above proc in a table?
insert into exec xp_cmdshell 'dir c:\*.exe'
9. What are Cursors and their types? What type do you use most and which one is fast?
FORWARD-ONLY, FAST-FORWARD or READ-ONLY cursors.
Fastest to slowest: Dynamic, Static, and Keyset.
More Info: http://msdn.microsoft.com/en-us/library/ms180169.aspx
10. Why you should not use a cursor? What are its alternatives?
Alternatives: while loops with temp tables, derived tables, correlated sub-queries, CASE stmt
More Info: http://www.sql-server-performance.com/tips/cursors_p1.aspx
11. Difference between LEFT JOIN with WHERE clause & LEFT JOIN with no WHERE clause.
OUTER LEFT/RIGHT JOIN with WHERE clause can act like an INNER JOIN if not used wisely or logically.
12. How will you migrate an SSIS package from Development to Production environment?
Do not include db connections and file paths in your workflow, instead create configuration files. This will help in deploying the pkg created in DEV server to Testing and finally to the PROD environment.
More Info: http://msdn.microsoft.com/en-us/library/cc966389.aspx
13. Multiple ways to execute a dynamic query.
EXEC sp_executesql, EXECUTE()
More Info: https://sqlwithmanoj.wordpress.com/2011/03/22/execute-or-exec-vs-sp_executesql/
14. Difference between COALESCE() & ISNULL()
More Info: https://sqlwithmanoj.wordpress.com/2010/12/23/isnull-vs-coalesce/
15. Which of the following has higher performance:
a. OR, AND
b. =, <>, >
c. IN, NOT IN, EXISTS
d. UNION, UNION ALL
16. What should be the ideal combination with IN & UNION (ALL) in terms of performance?
a. SELECT *FROM
IN (SELECT… UNION SELECT…)
b. SELECT * FROM
IN (SELECT… UNION ALL SELECT…)
17. What is an IDENTITY column and its usage in INSERT statements?
IDENTITY column can be used with a tables column to make it auto incremental, or a surrogate key.
MS BOL link: http://msdn.microsoft.com/en-us/library/ms174639(v=SQL.90).aspx
18. Can you create a Primary key without clustered index?
Creation of PK automatically creates a clustered index upon the column(s).
More Info: http://vadivel.blogspot.com/2006/03/primary-keys-without-clustered-index.html
19. There are two tables one Master and another Feed table, both with 2 columns: ID & Price. Feed table gets truncated and re-populated every day.
Master Table Feed Table ID, Price ID, Price 1 100 1 200 3 200 2 250 5 300 4 500 6 400 6 750 7 500 7 800
Create a job with an optimal script that will update the Master table by the Feed table.
20. What are CUBE & ROLLUP sets?
CUBE & ROLLUP are the grouping sets used with GROUP BY clause and are very helpful in creating reports.
More Info: https://sqlwithmanoj.wordpress.com/2010/11/12/cube-rollup-compute-compute-by-grouping-sets/
21. What new indexes are introduced in SQL Server 2005 in comparison to 2000?
More Info: http://msdn.microsoft.com/en-us/library/ms175049.aspx
22. What are XML indexes, what is their use?
More Info: http://msdn.microsoft.com/en-us/library/ms345121%28SQL.90%29.aspx
23. How many types of functions (UDF) are there in SQL Server? What are inline functions?
- Scalar functions
- Inline Table-valued functions
- Multi-statement Table-valued functions
More Info: https://sqlwithmanoj.wordpress.com/2010/12/11/udf-user-defined-functions/
24. How will you handle exceptions in SQL Server programming?
By using TRY-CATCH constructs, putting our SQL statements/scripts inside the TRY block and error handling in the CATCH block, link.
More Info: http://msdn.microsoft.com/en-us/library/ms179296%28v=SQL.90%29.aspx
25. How would you send an e-mail form SQL Server?
Configure Database mail here.
More Info: http://msdn.microsoft.com/en-us/library/ms175887%28v=SQL.90%29.aspx
… more questions on next post [Part-2].