Monday, November 10, 2014

Querying Microsoft SQL Server 2012_Realworld_Examtips

Real World Float Trouble
We remember a case where a customer used FLOAT to represent barcode numbers of
products, and was then surprised by not getting the right product when scanning the
products’ barcodes. Also, recently, we got a query about conversion of a FLOAT value to
NUMERIC, resulting in a different value than what was entered. Here’s the case.
DECLARE @f AS FLOAT = '29545428.022495';
SELECT CAST(@f AS NUMERIC(28, 14)) AS value;
Can you guess what the output of this code is? Here it is.
Value
---------------------------------------
29545428.02249500200000
Real world Anticipating Errors
When you handle errors in a CATCH block, the number of errors that can occur is quite large, so it is difficult to anticipate all of them. Also, the types of transactions or procedures involved might be specialized. Some T-SQL developers prefer to just return the values of the error functions as in the previous SELECT statement. This can be most useful for utility stored procedures. In other contexts, some T-SQL developers use a stored procedure that can be called from the CATCH block and that will provide a common response for certain commonly encountered errors.
THROW vs. RAISERROR in TRY/CATCH
In the TRY block, you can use either RAISERROR or THROW (with parameters) to generate an error condition and transfer control to the CATCH block. A RAISERROR in the TRY block must have a severity level from 11 to 19 to transfer control to the CATCH block. Whether you use RAISERROR or THROW in the TRY block, SQL Server will not send an error message to the client.
In the CATCH block, you have three options: RAISERROR, THROW with parameters, or THROW without parameters.
You can use a RAISERROR in the CATCH block to report the original error back to the client, or to raise an additional error that you want to report. The original error number cannot be re-raised. It must be a custom error message number or, in this case, the default error number 50000. To return the error number, you could add it to the @error_message string. Execution of the CATCH block continues after the RAISERROR statement.You can use a THROW statement with parameters, like RAISERROR, to re-raise the error in the CATCH block. However, THROW with parameters always raises errors with a custom error number and a severity level of 16, so you don't get the exact information. THROW with parameters terminates the batch, so commands following it are not executed.
A THROW without parameters can be used to re-raise the original error message and send it back to the client. This is by far the best method for reporting the error back to the caller.
Now you get the original message sent back to the client, and under your control, though it does terminate the batch immediately.
Exam Tip
You must take care that the THROW with or without parameters is the last statement you want executed in the CATCH block, because it terminates the batch and does not execute any remaining commands in the CATCH block.
Exam Tip
1.Understanding the built-in tools T-SQL provides for generating surrogate keys like the sequence object, identity column property, and the NEWID and NEWSEQUENTIALID functions, and their impact on performance, is an important skill for the exam.
2. COALESCE and ISNULL can impact performance when you are combining sets; for example,
with joins or when you are filtering data. Consider an example where you have two tables T1 and T2 and you need to join them based on a match between T1.col1 and T2.col1. The attributes do allow NULLs. Normally, a comparison between two NULLs yields unknown,and this causes the row to be discarded. You want to treat two NULLs as equal. What some do in such a case is use COALESCE or ISNULL to substitute a NULL with a value that they know cannot appear in the data. For example, if the attributes are integers, and you know that you have only positive integers in your data (you can even have constraints that ensure this), you might try to use the predicate COALESCE(T1.col1, -1) = COALESCE(T2.
col1, -1), or ISNULL(T1.col1, -1) = ISNULL(T2.col1, -1). The problem with this form is that,because you apply manipulation to the attributes you’re comparing, SQL Server will not rely on index ordering. This can result in not using available indexes efficiently. Instead, it is recommended to use the longer form: T1.col1 = T2.col1 OR (T1.col1 IS NULL AND T2.col1 IS NULL), which SQL Server understands as just a comparison that considers NULLs as equal. With this form, SQL Server can efficiently use indexing.
3. Understanding the impact of using COALESCE and ISNULL on performance is an important skill for the exam.
4. Often, when joining tables, you join them based on a foreign key–unique key relationship.
For example, there’s a foreign key defined on the supplierid column in the Production .Products table (the referencing table), referencing the primary key column supplierid in the Production.Suppliers table (the referenced table). It’s also important to note that when you define a primary key or unique constraint, SQL Server creates a unique index on the constraint columns to enforce the constraint’s uniqueness property. But when you define a foreign key, SQL Server doesn’t create any indexes on the foreign key columns. Such indexes could improve the performance of joins based on those relationships. Because SQL Server doesn’t create such indexes automatically, it’s your responsibility to identify the cases where they can be useful and create them. So when working on index tuning, one  interesting area to examine is foreign key columns, and evaluating the benefits of creating indexes on those.
5. As explained in the discussion of window aggregate functions, window functions are allowed only in the SELECT and ORDER BY clauses of the query. If you need to refer to those in other clauses—for example, in the WHERE clause—you need to use a table expression such as a CTE. You invoke the window function in the inner query’s SELECT clause, assigning the expression with a column alias. Then you refer to that column alias in the outer query’s WHERE clause. You have a chance to practice this technique in this lesson’s exercises.
6 Although full-text search is not on the list of the exam objectives, an indirect question about it could appear. Remember that full text predicates can also be a part of the WHERE clause of a query.
7. The FREETEXT predicate is less selective than the CONTAINS predicate, and thus it usually returns more rows than the CONTAINS predicate.
8. Semantic search is available through the table-valued functions only; it does not support any specific predicates for the WHERE clause of a query.
9. The FOR XML clause comes after the ORDER BY clause in a query.
10. Navigation through XML can be quite tricky; make sure you understand the complete path.
11. You can move a table from one schema to another by using the ALTER SCHEMA TRANSFER statement. Assuming there is no object named Categories in the Sales database schema, the following statement moves the  Production.Categories table to the Sales database schema.
ALTER SCHEMA Sales TRANSFER Production.Categories;
To move the table back, issue the following.
ALTER SCHEMA Production TRANSFER Sales.Categories;
12. The unique constraint does not require the column to be NOT NULL. You can allow NULL in
a column and still have a unique constraint, but only one row can be NULL.
13. Because joins often occur on foreign keys, it can help query performance to create a nonclustered index on the foreign key in the referencing table. There is already a unique index on the corresponding column in the referenced table, but if the referencing table,like Production.Products, has a lot of rows, it may help SQL Server resolve the join faster if it can use an index on the big table.
14. Results of a view are never ordered. You must add your own ORDER BY when you SELECT from the view. You can include an ORDER BY in a view only by adding the TOP operator or the OFFSET FETCH clause to the SELECT clause. Even then, the results of the view will not be ordered. Therefore, an ORDER BY in a view, even when you can enter it, is useless.
15. Synonyms cannot refer to other synonyms. They can only refer to database objects such as
tables, views, stored procedures, and functions. In other words, synonym chaining is not allowed.
16. Make sure you understand how modification statements are affected by constraints defined in the target table.
17. An important technique in multiple choice questions in the exam is to first eliminate answers that are obviously incorrect. For example, suppose you get a question and a few possible answers that contain code samples. And suppose one of the answers contains code defining a table that has two columns with an IDENTITY property or two PRIMARY KEY constraints. You can quickly eliminate such answers from consideration. This way, you can spend more time on fewer answers.
18. Note that transactions can span batches. This includes both implicit transactions and explicit transactions—that is, GO statements. However, it is often a best practice to make sure that each transaction takes place in one batch.
19. An inner COMMIT statement has no real effect on the transaction, only decrementing @@TRANCOUNT by 1. Just the outermost COMMIT statement, the one executed when @@TRANCOUNT = 1, actually commits the transaction.
20. Note that it doesn't matter at what level you issue the ROLLBACK command. A transaction can contain only one ROLLBACK command, and it will roll back the entire transaction and reset the @@TRANCOUNT counter to 0.
21. Isolation levels are set per session. If you do not set a different isolation level in your session, all your transactions will execute using the default isolation level, READ COMMITTED. 
For on-premise SQL Server instances, this is READ COMMITTED. In Windows Azure SQL
Database, the default isolation level is READ COMMITTED SNAP SHOT.
22. The statement before the THROW statement must be terminated by a semicolon (;). This reinforces the best practice to terminate all T-SQL statements with a semicolon.
23. You must take care that the THROW with or without parameters is the last statement you want executed in the CATCH block, because it terminates the batch and does not execute any remaining commands in the CATCH block.
24. You should leave QUOTED_IDENTIFIER set to ON because that is the `ANSI standard and the SQL Server default.
25. The ability to parameterize means that sp_excutesql avoids simple concatenations like those used in the EXEC statement. As a result, it can be used to help prevent SQL injection.
26. You should use SQL Server Extended Events instead of SQL Trace and SQL Server Profiler because Extended Events is more lightweight and SQL Trace and SQL Server Profiler are deprecated in future versions of SQL Server.
27 The NOCOUNT setting of ON or OFF stays with the stored procedure when it is created. Placing a SET NOCOUNT ON at the beginning of every stored procedure prevents the procedure from returning that message to the client. In addition, SET NOCOUNT ON can improve the performance of frequently executed stored procedures because there is less network communication required when the "rows(s) affected" message is not returned to the client.
28. Always include the EXEC command when calling a stored procedure. That will avoid getting unexpected and confusing errors. If the statement is no longer the first statement in the batch, it will still run.
29. It is a best practice to name the parameters when you call stored procedures. Although passing parameter values by position may be more compact, it is also more error prone. If you pass parameters by name and the parameter order changes in the stored procedure, your call of the procedure will still work.
30. When you code a WHILE loop, it is critical to ensure that something happens in the loop that will eventually make the WHILE condition evaluate to false so that the WHILE loop will terminate. Always check the body of the WHILE loop and make sure that a counter is incremented  or a value changes so that the loop will always terminate under all conditions.
31. Even though a BEGIN/END block is optional in a WHILE loop if you only have one statement,it is a best practice to include it. The BEGIN/END block helps you organize your code, makes it easier to read, and makes it easier to modify in the future. Any statement block in a WHILE loop with more than one statement requires the BEGIN/END construct.
32. When an UPDATE or DELETE occurs and no rows are affected, there is no point in proceeding with the trigger. You can improve the performance of the trigger by testing whether @@ROWCOUNT is 0 in the very first line of the trigger. It must be the first line because @@ROWCOUNT will be set back to 0 by any additional statement. When the AFTER trigger begins, @@ROWCOUNT will contain the number of rows affected by the outer INSERT,UPDATE, or DELETE statement.
33. It is not a good practice to return result sets from triggers. In SQL Server 2012 and earlier versions, returning a rowset from a trigger is allowed, but it cannot be relied on. You can also disable it with the sp_configure option called Disallow Results From Triggers. In addition,the ability to return result sets from a trigger is deprecated and will be dropped in the next version of SQL Server after SQL Server 2012.

34. Only a nested loops join algorithm supports non-equijoins.

Microsoft.Press.Training.Kit.Exam.70-461.Nov.2012

Microsoft.Press.Training.Kit.Exam.70-461.Nov.2012

1. What are the mathematical branches that the relational model is based on?
2. What is the difference between T-SQL and SQL?
 Answer
1. Set theory and predicate logic.
2. SQL is standard; T-SQL is the dialect of and extension to SQL that Microsoft implements in its RDBMS—SQL Server.

1. Name two aspects in which T-SQL deviates from the relational model.
2. Explain how you can address the two items in question 1 and use T-SQL in a relational way.
 Answer
1. A relation has a body with a distinct set of tuples. A table doesn’t have to have a key. T-SQL allows referring to ordinal positions of columns in the ORDER BY clause.
2. Define a key in every table. Refer to attribute names—not their ordinal positions—in the ORDER BY clause.

1. Why are the terms “field” and “record” incorrect when referring to column and row?
2. Why is the term “NULL value” incorrect?
 Answer
1. Because “field” and “record” describe physical things, whereas columns and rows are logical elements of a table.
2. Because NULL isn’t a value; rather, it’s a mark for a missing value.

■■ What is the difference between the WHERE and HAVING clauses?
 Answer
■■ The WHERE clause is evaluated before rows are grouped, and therefore is evaluated per row. The HAVING clause is evaluated after rows are grouped, and therefore is evaluated per group.

1. Why are you not allowed to refer to a column alias defined by the SELECT clause in the WHERE clause?
2. Why are you not allowed to refer to a column alias defined by the SELECT clause in the same SELECT clause?
 Answer
1. Because the WHERE clause is logically evaluated in a phase earlier to the one that evaluates the SELECT clause.
2. Because all expressions that appear in the same logical query processing phase are evaluated conceptually at the same point in time.

1. What are the forms of aliasing an attribute in T-SQL?
2. What is an irregular identifier?
 Answer
1. The forms are <expression> AS <alias>, <expression> <alias>, and
<alias> = <expression>.
2. An identifier that does not follow the rules for formatting identifiers; for
example, it starts with a digit, has an embedded space, or is a reserved T-SQL keyword.

1. Would you use the type FLOAT to represent a product unit price?
2. What is the difference between NEWID and NEWSEQUENTIALID?
3. Which function returns the current date and time value as a DATETIME2 type?
4. When concatenating character strings, what is the difference between the plus
(+) operator and the CONCAT function?
 Answer
1. No, because FLOAT is an approximate data type and cannot represent all values precisely.
2. The NEWID function generates GUID values in random order, whereas the NEWSEQUENTIAL ID function generates GUIDs that increase in a sequential order.
3. The SYSDATETIME function.
4. The + operator by default yields a NULL result on NULL input, whereas the
CONCAT function treats NULLs as empty strings.

1. What are the performance benefits in using the WHERE filter?
2. What is the form of a filter predicate that can rely on index ordering called?
 Answer
1. You reduce network traffic by filtering in the database server instead of in
the client, and you can potentially use indexes to avoid full scans of the tables
involved.
2. A search argument, or SARG, for short.


1. How do you guarantee the order of the rows in the result of a query?
2. What is the difference between the result of a query with and one without an
ORDER BY clause?
 Answer
1. The only way to do so is by adding an ORDER BY clause.
2. Without an ORDER BY clause, the result is relational (from an ordering perspective);
with an ORDER BY clause, the result is conceptually what the standard
calls a cursor.

1. How do you guarantee deterministic results with TOP?
2. What are the benefits of using OFFSET-FETCH over TOP?
 Answer
1. By either returning all ties by using the WITH TIES option or by defining unique
ordering to break ties.
2. OFFSET-FETCH is standard and TOP isn’t; also, OFFSET-FETCH supports a skipping
capability that TOP doesn’t.

1. What is the difference between the old and new syntax for cross joins?
2. What are the different types of outer joins?
 Answer
1. The new syntax has the CROSS JOIN keywords between the table names and
the old syntax has a comma.
2. Left, right, and full.

1. What is the difference between self-contained and correlated subqueries?
2. What is the difference between the APPLY and JOIN operators?
 Answer
1. Self-contained subqueries are independent of the outer query, whereas correlated
subqueries have a reference to an element from the table in the outer
query.
2. With a JOIN operator, both inputs represent static relations. With APPLY, the
left side is a static relation, but the right side can be a table expression with
correlations to elements from the left table.

1. Which set operators does T-SQL support?
2. Name two requirements for the queries involved in a set operator.
 Answer
1. The UNION, INTERSECT, and EXCEPT set operators, as well as the UNION ALL
multiset operator.
2. The number of columns in the two queries needs to be the same, and corresponding
columns need to have compatible types.


1. What makes a query a grouped query?
2. What are the clauses that you can use to define multiple grouping sets in the
same query?
 Answer
1. When you use an aggregate function, a GROUP BY clause, or both.
2. GROUPING SETS, CUBE, and ROLLUP.

1. What is the difference between PIVOT and UNPIVOT?
2. What type of language constructs are PIVOT and UNPIVOT implemented as?
 Answer
1. PIVOT rotates data from a state of rows to a state of columns; UNPIVOT rotates
the data from columns to rows.
2. PIVOT and UNPIVOT are implemented as table operators.

1. What are the clauses that the different types of window functions support?
2. What do the delimiters UNBOUNDED PRECEDING and UNBOUNDED FOLLOWING
represent?
 Answer
1. Partitioning, ordering, and framing clauses.
2. The beginning and end of the partition, respectively.

■■ Can you store indexes from the same full-text catalog to different filegroups?
 Answer
■■ Yes. A full-text catalog is a virtual object only; full-text indexes are physical objects.
You can store each full-text index from the same catalog to a different file
group.

1. How do you search for synonyms of a word with the CONTAINS predicate?
2. Which is a more specific predicate, CONTAINS or FREETEXT?
 Answers
1. You have to use the CONTAINS(FTcolumn, ‘FORMSOF(THESAURUS,
SearchWord1)’) syntax.
2. You use the CONTAINS predicate for more specific searches.

■■ How many full-text search and how many semantic search functions are supported
by SQL Server?
 Answer
■■ SQL Server supports two full-text search and three semantic search functions.

■■ How can you get an XSD schema together with an XML document from your
SELECT statement?
 Answer
■■ You should use the XMLSCHEMA directive in the FOR XML clause.

1. What do you do in the return clause of the FLWOR expressions?
2. What would be the result of the expression (12, 4, 7) != 7?
 Answers
1. In the return clause, you format the resulting XML of a query.
2. The result would be true.

■■ Which XML data type method would you use to retrieve scalar values from an XML
instance?
 Answer
■■ The value() XML data type method retrieves scalar values from an XML instance.

1. Can a table or column name contain spaces, apostrophes, and other nonstandard
characters?
2. What types of table compression are available?
 Answer
1. Yes, table and column names can be delimited identifiers that contain nonstandard
characters.
2. You can use either page or row compression on a table. Page compression includes row compression.

1. How does SQL Server enforce uniqueness in both primary key and unique
constraints?
2. Can a primary key on one table have the same name as the primary key in
another table in the same database?
 Answer
1. SQL Server uses unique indexes to enforce uniqueness for both primary key
and unique constraints.
2. No, all table constraints must have unique names in a database.

1. Must a view consist of only one SELECT statement?
2. What types of views are available in T-SQL?
 Answer
1. Technically, yes, but a workaround to this is that you can unite (using the
UNION statement) multiple SELECT statements that together produce one
result set.
2. You can create regular views, which are just stored SELECT statements, or
indexed views, which actually materialize the data, in addition to partitioned
views.

1. What type of data does an inline function return?
2. What type of view can an inline function simulate?
 Answer
1. Inline functions return tables, and accordingly, are often referred to as inline
table-valued functions.
2. An inline table-valued function can simulate a parameterized view—that is, a
view that takes parameters.

1. Does a synonym store T-SQL or any data?
2. Can synonyms be altered?
 Answer
1. No, a synonym is just a name. All that is stored with a synonym is the object it
refers to.
2. No, to change a synonym, you must drop and recreate it.

1. Why is it recommended to specify the target column names in INSERT
statements?
2. What is the difference between SELECT INTO and INSERT SELECT?
 Answer
1. Because then you don’t care about the order in which the columns are defined
in the table. Also, you won’t be affected if the column order is rearranged due
to future definition changes, in addition to when columns that get their values
automatically are added.
2. SELECT INTO creates the target table and inserts into it the result of the query.
INSERT SELECT inserts the result of the query into an already existing table.

1. Which table rows are updated in an UPDATE statement without a WHERE
clause?
2. Can you update rows in more than one table in one UPDATE statement?
 Answer
1. All table rows.
2. No, you can use columns from multiple tables as the source, but update only
one table at a time.


1. Which rows from the target table get deleted by a DELETE statement without a
WHERE clause?
2. What is the alternative to a DELETE statement without a WHERE clause?
 Answer
1. All target table rows.
2. The TRUNCATE statement. But there are a few differences between the two
that need to be considered.

1. How many columns with an IDENTITY property are supported in one table?
2. How do you obtain a new value from a sequence?
 Answer
1. One.
2. With the NEXT VALUE FOR function.

1. What is the purpose of the ON clause in the MERGE statement?
2. What are the possible actions in the WHEN MATCHED clause?
3. How many WHEN MATCHED clauses can a single MERGE statement have?
 Answer
1. The ON clause determines whether a source row is matched by a target row,
and whether a target row is matched by a source row. Based on the result of
the predicate, the MERGE statement knows which WHEN clause to activate and
as a result, which action to take against the target.
2. UPDATE and DELETE.
3. Two—one with an UPDATE action and one with a DELETE action.

1. How many OUTPUT clauses can a single statement have?
2. How do you determine which action affected the OUTPUT row in a MERGE
statement?
 Answer
1. Two—one with INTO and one without INTO.
2. Use the $action function.

1. Why is it important for SQL Server to maintain the ACID quality of
transactions?
2. How does SQL Server implement transaction durability?
 Answer
1. To ensure that the integrity of database data will not be compromised.
2. By first writing all changes to the database transaction log before making
changes to the database data.

1. How many ROLLBACKs must be executed in a nested transaction to roll it back?
2. How many COMMITs must be executed in a nested transaction to ensure that
the entire transaction is committed?
 Answer
1. Only one ROLLBACK. A ROLLBACK always rolls back the entire transaction, no
matter how many levels the transaction has.
2. One COMMIT for each level of the nested transaction. Only the last COMMIT
actually commits the entire transaction.

1. Can readers block readers?
2. Can readers block writers?
 Answer
1. No, because shared locks are compatible with other shared locks.
2. Yes, even if only momentarily, because any exclusive lock request has to wait
until the shared lock is released.

1. If two transactions never block each other, can a deadlock between them
result?
2. Can a SELECT statement be involved in a deadlock?
 Answer
1. No. In order to deadlock, each transaction must already have locked a resource
the other transaction wants, resulting in mutual blocking.
2. Yes. If the SELECT statement locks some resource that keeps a second transaction
from finishing, and the SELECT cannot finish because it is blocked by the
same transaction, the deadlock cycle results.

1. If your session is in the READ COMMITTED isolation level, is it possible for one
of your queries to read uncommitted data?
2. Is there a way to prevent readers from blocking writers and still ensure that
readers only see committed data?
 Answer
1. Yes, if the query uses the WITH (NOLOCK) or WITH (READUNCOMMITTED)
table hint. The session value for the isolation level does not change, just the
characteristics for reading that table.
2. Yes, that is the purpose of the READ COMMITTED SNAPSHOT option within the
READ COMMITTED isolation level. Readers see earlier versions of data changes
for current transactions, not the currently uncommitted data.

1. How can you add custom error messages?
2. What is severity level 0 used for?
 Answer
1. You can use the system stored procedure sp_addmessage to add your own
custom error messages.
2. When you issue a RAISERROR with severity level 0, only an informational message
is sent. If you add WITH NOWAIT, the message will be sent without waiting
in the output buffer.

1. What are the main advantages of using a TRY/CATCH block over the traditional
trapping for @@ERROR?
2. Can a TRY/CATCH block span batches?
 Answer
1. The main advantage is that you have one place in your code that errors will be
trapped, so you only need to put error handling in one place.
2. No, you must have one set of TRY/CATCH blocks for each batch of code.

1. Can you generate and execute dynamic SQL in a different database than the
one your code is in?
2. What are some objects that cannot be referenced in T-SQL by using variables?
 Answer
1. Yes, because the USE <database> command can be inserted into a dynamic
SQL batch.
2. Objects that you cannot use variables for in T-SQL commands include the
database name in a USE statement, the table name in a FROM clause, column
names in the SELECT and WHERE clauses, and lists of literal values in the IN()
and PIVOT() functions.

1. How can a hacker detect that SQL injection may be possible?
2. Where is the injected code inserted?
 Answer
1. By inserting a single quotation mark and observing an error message.
2. Between an initial single quotation mark, which terminates the data input
string, and a final comment mark, which disables the internal terminating
single quotation mark.

1. How can you pass information from sp_executesql to the caller?
2. How does sp_executesql help stop SQL injection?
 Answer
1. Use one or more OUTPUT parameters. You can also persist the data in a permanent
or temporary table, but the most direct method is through the OUTPUT
parameter.
2. You can use sp_executesql to parameterize user input, which can prevent any
injected code from being executed.

■■ What is the result of the parsing phase of query execution?
 Answer
■■ The result of this phase, if the query passed the syntax check, is a tree of logical
operators known as a parse tree.

1. How would you quickly measure the amount of disk IO a query is performing?
2. How can you get an estimated execution plan in XML format for further analysis?
 Answers
1. You should use the SET STATISTICS IO command.
2. You can use the SET SHOWPLAN_XML command.

■■ Which DMO gives you detailed text of queries executed?
 Answer
■■ You can retrieve the text of batches and queries executed from the
sys.dm_exec_sql_text DMO.

1. What are the two types of parameters for a T-SQL stored procedure?
2. Can a stored procedure span multiple batches of T-SQL code?
 Answer
1. A T-SQL stored procedure can have input and output parameters.
2. No, a stored procedure can only contain one batch of T-SQL code.

1. What are the two types of DML triggers that can be created?
2. If an AFTER trigger discovers an error, how does it prevent the DML command
from completing?
 Answer
1. You can create AFTER and INSTEAD OF DML-type triggers.
2. An AFTER trigger issues a THROW or RAISERROR command to cause the transaction
of the DML command to roll back.

1. What are the two types of table-valued UDFS?
2. What type of UDF returns only a single value?
 Answer
1. You can create inline or multistatement table-valued UDFs.
2. A scalar UDF returns only a single value.

■■ What kind of clustering key would you select for an OLTP environment?
 Answer
■■ For an OLTP environment, a short, unique, and sequential clustering key might be
the best choice.

■■ Which clauses of a query should you consider supporting with an index?
 Answer
■■ The list of the clauses you should consider supporting with an index includes, but
is not limited to, the WHERE, JOIN, GROUP BY, and ORDER BY clauses.

■■ How would you quickly update statistics for the whole database after an upgrade?
 Answer
■■ You should use the sys.sp_updatestats system procedure.

1. What are the commands that are required to work with a cursor?
2. When using the FAST_FORWARD option in the cursor declaration command,
what does it mean regarding the cursor properties?
 Answer
1. DECLARE, OPEN, FETCH in a loop, CLOSE, and DEALLOCATE.
2. That the cursor is read-only, forward-only.

1. How do you create a local temporary table, and how do you create a global
one?
2. Can you name constraints in local temporary tables and in table variables?
 Answer
1. You name a local temporary table by using a single number sign as a prefix and
a global one with two number signs as a prefix.
2. You can name constraints in local temporary tables, although it’s not recommended
because it can generate name conflicts. You cannot name constraints
in table variables.

■■ How would you determine whether SQL Server used the batch processing mode
for a specific iterator?
 Answer
■■ You can check the iterator’s Actual Execution Mode property.

■■ Why might you prefer using plan guides instead of optimizer hints?
 Answer
■■ With plan guides, you do not need to change the query text.



SQL Server Difference FAQs-1

SQL Server Difference FAQs-1

  1. What are the Differences between TRUNCATE and Delete?
S.NoTruncateDelete
1Truncate is fasterDelete is comparatively slower
2Removes all rows from a tableCan remove specific rows with Where clause
3Is DDL CommandIs DML Command
4Resets identity of the tableDoes not reset identity of the table
5Removes the data by deallocating the data pages and logs the deallocation.Removes one row at a time and records an entry in the transaction log for each deleted row.
6Cannot be rolled backCan be rolled back
Remarks:TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes, and so on remain. To remove the table definition in addition to its data, use the DROP TABLE statement.

  1. What are the differences between Primary key and Unique key?
S.NoPrimary KeyUnique Key
1Creates Clustered indexCreates Non-Clustered index
2Null values are not allowed.Allows only one null value.
3We can have only one Primary key in a table. We can have more than one unique key in a table. 
4Primary key can be made foreign key into another table. Unique key cannot be made foreign key into another table. 

  1. What are the Differences between Clustered Indexes and Non-Clustered Indexes?

S.NoClustered IndexesNon-Clustered Indexes
1It reorders the physical storage of records in the tableIt sorts and maintain a separate storage
2There can be only one Clustered index per tableWe can have 249 non-clustered indexes in a table
3The leaf nodes contain dataThe leaf node contains pointer to data
4
To create clustered index Sql server required more memory because the leaf pages in the tree structure will maintain actual data .
To create non-clustered index Sql server requires less memory because the leaf pages will contain pointers to actual data
5
By using clustered index retrieving data is more faster,when we compare with non-clustered index.
By using non-clustered index retrieving data is slower than clustered index.

  1. What are the differences between Stored Procedures and User Defined Functions?
S.NoStored ProceduresUser Defined Functions
1Stored Procedure cannot be used in a Select statementUser Defined Function can be used in a Select statement
2Stored procedure supports Deferred Name ResolutionUser Defined Function does not support Deferred Name Resolution
3Stored Procedures are generally used for performing Business LogicUser Defined Functions are generally used for Computations
4Stored Procedure need not return a valueUser Defined Functions should return a value
5Stored Procedures can return any datatypeUser Defined Functions cannot return Image
6Stored Procedures can accept more number of input parameters than User Defined Functions. Stored Procedures can have upto 21000 input parametersUser Defined Functions accept lesser number of input parameters than Stored Procedures. UDF can have upto 1023 input parameters
7Stored Procedures can use Temporary TablesTemporary Tables cannot be used in a User Defined Function
8Stored Procedures can execute Dynamic SQLUser Defined Functions cannot execute Dynamic SQL
9Stored Procedure supports error handlingUser Defined Function does not support error handling. RAISEERROR or @@ERROR are not allowed in UDFs
10Non-deterministic functions can be used in Stored Procedures.Non-deterministic functions cannot be used in User Defined Functions (UDFs). For example, GETDATE() cannot be used in User Defined Functions(UDFs)

Basic Difference

  1. Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).
  2. Functions can have only input parameters for it whereas Procedures can have input/output parameters .
  3. Functions can be called from Procedure whereas Procedures cannot be called from Function.

Advance Difference

  1. Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.
  2. Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.
  3. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.
  4. The most important feature of stored procedures over function is to retention and reuse the execution plan while in case of function it will be compiled every time.
  5. Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.
  6. Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
  7. Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.
  8. We can go for Transaction Management in Procedure whereas we can't go in Function.
  1. What are the differences between Where and Having clauses?
S.NoWhere clauseHaving clause
1It applies to individual rowsIt applies to a group as a whole
2It selects rows before groupingIt selects rows after grouping
3It cannot contain aggregate functionsIt can contain aggregate functions
4It can be used in select, delete ,insert etc.It is used only in select clause
The WHERE clause is evaluated before rows are grouped, and therefore is evaluated per row. The HAVING clause is evaluated after rows are grouped, and therefore is evaluated per group.
  1. What are the differences between Union and UnionAll?
S.NoUnionUnionAll
1This is used to eliminate duplicate rowsIt will not eliminate duplicate rows
2This selects only distinct rowsIt selects all the values
3It can be used to combine any number of queriesIt can be used to combine maximum of 2 queries
4It cannot contain aggregate functionsIt can contain aggregate functions
5Union is slower than UnionAllUnionAll is faster than Union
6
Output is in sorted order

Example :
SELECT Col
FROM @Table1
UNION
SELECT Col
FROM @Table2

Result:
1
2
3
5
Output is not in sorted order

Example :
SELECT Col
FROM @Table1
UNION ALL
SELECT Col
FROM @Table2

Result:
1
2
3
2
5

  1. What is the difference between normal Select statement and a Cursor?
S.NoSelect statementCursor
1Select statements are used for table-level processingCursors are used for row-level processing

8) Difference between Primary Key and Foreign Key
S.NoPrimary KeyForeign Key
1Primary key uniquely identify a record in the table. Foreign key is a field in the table that is primary key in another table. 
2Primary Key cannot accept null values. Foreign key can accept multiple null values. 
3By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index. While Foreign key is non-clustered index. 
4We can have only one Primary key in a table. We can have more than one foreign key in a table. 

SQL SERVER Basics

1. FROM
2. ON
3. OUTER
4. WHERE
5. GROUP BY
6. CUBE | ROLLUP
7. HAVING
8. SELECT
9. DISTINCT
10 ORDER BY
11. TOP
As OUTER join is applied subsequent to ON clause, all rows eliminated by the ON clause will still be included by the OUTER join as described in the article SQL SERVER – Interesting Observation of ON Clause on LEFT JOIN – How ON Clause Effects Resultset in LEFT JOIN.

Tip:

When I want to filter records in a query, I usually put the condition in the WHERE clause. When I make an inner join, I can put the condition in the ON clause instead, giving the same result. But with left joins this is not the case. Here is a quote from the SQL Server documentation:
Although the placement of such predicates does not make a difference for INNER joins, they might cause a different result when OUTER joins are involved. This is because the predicates in the ON clause are applied to the table before the join, whereas the WHERE clause is semantically applied to the result of the join.


Views:Views are virtual tables that are compiled at run time. The data associated with views are not physically stored in the view, but it is stored in the base tables of the view.
 A view can be made over one or more database tables. Generally we put those columns in view that we need to retrieve/query again and again. Once you have created the view, you can query view like as table. We can make index, trigger on view.

Types of Views

In Sql Server we have two types of views.

01.System Defined Views

02.User Defined Views-->a)single table b)complex view(on multiple table)

system defined views:

01.Information Schema View
02.Catalog View
03.Dynamic Management View
01.Server-scoped Dynamic Management View(dmv)
These are stored only in the Master database.

02.Database-scoped Dynamic Management View(dmv)
These are stored in each database.


Deep on views:

•SQL SERVER – ORDER BY Does Not Work – Limitation of the View 1
•SQL SERVER – Adding Column is Expensive by Joining Table Outside View – Limitation of the View 2
•SQL SERVER – Index Created on View not Used Often – Limitation of the View 3
•SQL SERVER – SELECT * and Adding Column Issue in View – Limitation of the View 4
•SQL SERVER – COUNT(*) Not Allowed but COUNT_BIG(*) Allowed – Limitation of the View 5
•SQL SERVER – UNION Not Allowed but OR Allowed in Index View – Limitation of the View 6
•SQL SERVER – Cross Database Queries Not Allowed in Indexed View – Limitation of the View 7
•SQL SERVER – Outer Join Not Allowed in Indexed Views – Limitation of the View 8
•SQL SERVER – SELF JOIN Not Allowed in Indexed View – Limitation of the View 9
•SQL SERVER – Keywords View Definition Must Not Contain for Indexed View – Limitation of the View 10
•SQL SERVER – View Over the View Not Possible with Index View – Limitations of the View 11


Stored procedure:stored procedure is a precompiled set of one or more SQL statements that is stored on Sql Server.
 Benifit of Stored Procedures is that they are executed on the server side and perform a set of actions, before returning the results to the client side.
This allows a set of actions to be executed with minimum time and also reduce the network traffic. Hence stored procedure improve performance to execute sql statements.

Types of Stored Procedure
01.System Defined Stored Procedure
02.Extended Procedure
03.User Defined Stored Procedure
04.CLR Stored Procedure

1.System Defined Stored Procedure:These stored procedure are already defined in Sql Server.
These are physically stored in hidden Sql Server Resource Database and logically appear in the sys schema of each user defined and system defined database.

2.Extended procedures provide an interface to external programs for various maintenance activities.
These extended procedures starts with the xp_ prefix and stored in Master database. Basically these are used to call programs that reside on the server automatically from a stored procedure or a trigger run by the server.

3.User Defined Stored Procedure:These procedures are created by user for own actions. These can be created in all system databases except the Resource database or in a user-defined database.

Note
1.We can nest stored procedures and managed code references in Sql Server up to 32 levels only. This is also applicable for function, trigger and view.

2.The current nesting level of a stored procedures execution is stored in the @@NESTLEVEL function.

3.In Sql Server stored procedure nesting limit is up to 32 levels, but there is no limit on the number of stored procedures that can be invoked with in a stored procedure




Function:It is a database object in Sql Server. Basically it is a set of sql statements that accepts only input parameters, perform actions and return the result.
Function can return only single value or a table. We can’t use function to Insert, Update, Delete records in the database table(s).

Types of Function
01.System Defined Function
02.User Defined Function

02.User Defined Function:These functions are created by user in system database or in user defined database. We three types of user defined functions.

01.Scalar Function
02.Inline Table-Valued Function
03.Multi-Statement Table-Valued Function

Scalar function:User defined scalar function also returns single value as a result of actions perform by function. We return any datatype value from function

2.Inline table-valued function:User defined inline table-valued function returns a table variable as a result of actions perform by function.
 The value of table variable should be derived from a single SELECT statement.

3.03.Multi-Statement Table-Valued Function
User defined multi-statement table-valued function returns a table variable as a result of actions perform by function. In this a table variable must be explicitly declared and defined whose value can be derived from a multiple sql statements


Cursor:
As we know, the cursors are required when we need to update records in a database table in singleton fashion means row by row.
You should avoid the use of cursor. In this article, I am explaining how
you can use cursor alternatives :
like as WHILE loop, Temporary tables and Table variables. We should use cursor in that case when there is no option except cursor.

Cursor:
A Cursor impacts the performance of the SQL Server since it uses the SQL Server instances' memory, reduce concurrency, decrease network bandwidth
and lock resources. Hence it is mandatory to understand the cursor types and its functions so that you can use suitable cursor according to your needs.

Types of Cursors

01.Static Cursors
2.Dynamic cursors
3.forword only cursor
4.keyset driven cursosr


Triggers: Triggers are special stored procedures that an RDBMS executes, or fires, automatically.
You can use Data Modifi cation Language (DML) triggers to enforce data modifi cation rules and
Data Definition Language (DDL) triggers to enforce schema modification rules.
Triggers can fire before or after the statement that is modifying the state of a database.
  1. After Triggers (For Triggers)
  2. Instead Of Triggers

SQL Server Difference FAQs-2

SQL Server Difference FAQs-2

  1. What are the differences between Instead of Triggers and After Triggers?

S.NoInstead of TriggersAfter Triggers
1Each table or view can have one INSTEAD OF trigger for each triggering action (UPDATE, DELETE, and INSERT)A table can have several AFTER triggers for each triggering action.
2INSTEAD OF triggers fire in place of the triggering action and before constraints are processed.AFTER triggers fire after the triggering action (INSERT, UPDATE, or DELETE) and after any constraints are processed.
  1. What are the differences between Views and User-Defined Functions?

S.NoViewsUser-Defined Functions
1Views cannot accept parameters.User-Defined Functions can accept parameters.
2Output of the Views cannot be directly used in the SELECT clause.Output of the User-Defined Functions can be directly used in the SELECT clause.
  1. What are the differences between Triggers and Stored Procedures?

S.NoTriggersStored Procedures
1Triggers cannot return a valueStored Procedures may return a value
2We cannot pass parameters in TriggersWe can pass parameter in Stored Procedures
3We can write a Stored procedure within a TriggerWe cannot write a Trigger within a Stored Procedure
4Triggers are implicitly fired whenever insert, update or delete operations take place on tableStored Procedures need to be explicitly called by the programmer
5Triggers can only be implemented on Tables or ViewsStored procedures can be written for the Database
6
We cannot schedule a trigger.
Stored procedures can be scheduled through a job to execute on a predefined time
7
We cannot use the print command inside a trigger.
We can use the Print commands inside the stored procedure for debugging purpose
8
We cannot call a trigger from these files.
We can call a stored procedure from front end (.asp files, .aspx files, .ascx files etc.)