SQL Server Flashcards

1
Q

What connections does Microsoft SQL Server support?

A

Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the System Database in Sql server 2005?

A
  1. Master - Stores system level information such as user accounts, configuration settings, and info on all other databases.
  2. Model - database is used as a template for all other databases that are created
  3. Msdb - Used by the SQL Server Agent for configuring alerts and scheduled jobs etc
  4. Tempdb - Holds all temporary tables, temporary stored procedures, and any other temporary storage requirements generated by SQL Server.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between TRUNCATE and DELETE commands?

A
  1. TRUNCATE is a DDL command whereas DELETE is a DML command.
  2. TRUNCATE is much faster than DELETE.

Reason:When you type DELETE.all the data get copied into the Rollback Tablespace first.then delete operation get performed.Thatswhy when you type ROLLBACK after deleting a table ,you can get back the data(The system get it for you from the Rollback Tablespace).All this process take time.But when you type TRUNCATE,it removes data directly without copying it into the Rollback Tablespace.Thatswhy TRUNCATE is faster.Once you Truncate you cann’t get back the data.

  1. You cann’t rollback in TRUNCATE but in DELETE you can rollback.TRUNCATE removes the record permanently.
  2. In case of TRUNCATE ,Trigger doesn’t get fired.But in DML commands like DELETE .Trigger get fired.
  3. You cann’t use conditions(WHERE clause) in TRUNCATE.But in DELETE you can write conditions using WHERE clause.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is denormalization and when would you go for it?

A

The process of adding redundant data to get rid of complex join, in order to optimize database performance. This is done to speed up database access by moving from higher to lower form of normalization.

In other words, we can define De-Nomalization as :-

De-normalization is the process of attempting to optimize the performance of a database by adding redundant data. It’s used To introduce redundancy into a table in order to incorporate data from a related table. The related table can then be eliminated. De-normalization can improve efficiency and performance by reducing complexity in a data warehouse schema.

De-normalization is an application tool in SQL server model. There are three methods for de-normalization:.
• Entity inheritance
• Role expansion
• Lookup entities.

Entity Inheritance
This method for the de-normalization should be implemented when one entity is named as another entity. This will do with the help of inheritance. Inheritance means parent child relations of entity. This will be do with making the foreign key and candidate key. This is also in notice that creation of model creates a band of relationship and if you select the inheritance this property should be automatically deleted.

Role Expansion
This type of de-normalization should be created when it is surety that one entity has the relationship to another entity or it is a part of another entity. In this storage reason is removed. It is used with the help of Expand inline function. It use the shared schema is used in from of table.

Lookup Entities
This type of de-normalization is used when entity depend on the lookup table. It is work with the help of Is Look up property. This property applies on the entity. These three will give authority to user to create a genuine and tempting report model .This model is navigation experience for the customer.

The Reason for Denormalization
Only one valid reason exists for denormalizing a relational design - to enhance performance. However, there are several indicators which will help to identify systems and tables which are potential denormalization candidates.

These are:

  • Many critical queries and reports exist which rely upon data from more than one table. Often times these requests need to be processed in an on-line environment.
  • Repeating groups exist which need to be processed in a group instead of individually.
  • Many calculations need to be applied to one or many columns before queries can be successfully answered.
  • Tables need to be accessed in different ways by different users during the same timeframe.
  • Many large primary keys exist which are clumsy to query and consume a large amount of disk space when carried as foreign key columns in related tables.
  • Certain columns are queried a large percentage of the time causing very complex or inefficient SQL to be used.

Be aware that each new RDBMS release usually brings enhanced performance and improved access options that may reduce the need for denormalization. However, most of the popular RDBMS products on occasion will require denormalized data structures. There are many different types of denormalized tables which can resolve the performance problems caused when accessing fully normalized data. The following topics will detail the different types and give advice on when to implement each of the denormalization types.

Types of Denormalization

  • *Pre-Joined Tables** used when the cost of joining is prohibitive
  • *Report Tables** used when specialized critical reports are needed
  • *Mirror Tables** used when tables are required concurrently by two different types of environments
  • *Split Tables** used when distinct groups use different parts of a table
  • *Combined Tables** used when one-to-one relationships exist
  • *Redundant Data** used to reduce the number of table joins required
  • *Repeating Groups** used to reduce I/O and (possibly) storage usage
  • *Derivable Data** used to eliminate calculations and algorithms
  • *Speed Tables** used to support hierarchies
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?

A

One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table. It will be a good idea to read up a database designing fundamentals text book.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are user defined datatypes and when you should go for them?

A

User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format to the database.

Take for example, in your database, there is a column called Flight_Num which appears in many tables. In all these tables it should be varchar(8). In this case you could create a user defined datatype called Flight_num_type of varchar(8) and use it across all your tables.

See sp_addtype, sp_droptype in books online.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is bit datatype and what’s the information that can be stored inside a bit column?

A

Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

CREATE INDEX myIndex ON myTable(myColumn)What type of Index will get created after executing the above statement?

A

Non-clustered index. Important thing to note: By default a clustered index gets created on the primary key, unless specified otherwise.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is lock escalation? What is its purpose?

A

Lock escalation: In SQL Server, if one acquires a lock at higher level, it can lock more resources than what we may consume. This kind of locking has an overhead with lower concurrency. E.g.: If we select all the rows of a table and we acquire a lock on the table, we would not need to lock rows themselves but then it will block any concurrent update transactions. Based on estimates during query compilation, SQL Server recommends the locking granularity appropriately and during query execution, based on the concurrent work load, the appropriate locking granularity is applied. While locking granularity is chosen at the beginning of query execution, during the execution SQL Server may choose to escalate the lock to higher level of granularity depending on the number of locks acquired and the availability of memory at runtime. SQL Server supports escalating the locks to the table level .i.e. the locks can only be escalated from rows to table level. Locks are never escalated from rows to the parent page.

Lock escalation is when the system combines multiple locks into a higher level one. This is done to recover resources taken by the other finer granular locks. The system automatically does this. The threshold for this escalation is determined dynamically by the server.

Purpose:

  • To reduce system over head by recovering locks
  • Maximize the efficiency of queries
  • Helps to minimize the required memory to keep track of locks.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the steps you will take to improve performance of a poor performing query?

A

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. Download the white paper on performance tuning SQL Server from Microsoft web site. Don’t forget to check out sql-server-performance.com

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is a deadlock and what is a live lock? How will you go about resolving deadlocks?

A

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.

Also check out the article Q169960 from Microsoft knowledge base.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is blocking and how would you troubleshoot it?

A

Blocking happens when one connection from an application holds a lock and a second connection requires a conflicting lock type. This forces the second connection to wait, blocked on the first. Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding efficient transactions. Explain CREATE DATABASE syntax Many of us are used to creating databases from the Enterprise Manager or by just issuing the command: CREATE DATABAE MyDB.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are statistics, under what circumstances they go out of date, how do you update them?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are the different ways of moving data/databases between servers and databases in SQL Server?

A

There are lots of options available, you have to choose your option depending upon your requirements.

Some of the options you have are:

  • BACKUP/RESTORE
  • dettaching and attaching databases
  • replication
  • DTS
  • BCP
  • Logshipping
  • INSERT…SELECT, SELECT…INTO
  • Creating INSERT scripts to generate data.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How to determine the service pack currently installed on SQL Server?

A

The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine the service pack installed.

To know more about this process visit SQL Server service packs and versions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is a join and explain different types of joins.

A

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.

  • Types of joins:
  • INNER JOIN
  • OUTER JOIN
  • CROSS JOIN
  • OUTER JOINs are further classified as LEFT OUTER JOINS
  • RIGHT OUTER JOINS and FULL OUTER JOINS.

For more information see pages from books online titled: “Join Fundamentals” and “Using Joins”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Can you have a nested transaction?

A

Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the system function to get the current user’s user id?

A
  • USER_ID().
  • USER_NAME()
  • SYSTEM_USER
  • SESSION_USER
  • CURRENT_USER
  • USER
  • SUSER_SID()
  • HOST_NAME().
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q
  • What is the difference between lock, block and deadlock?
A

Lock: DB engine locks the rows/page/table to access the data which is worked upon according to the query.

Block: When one process blocks the resources of another process then blocking happens.

Blocking can be identified by using

  • SELECT * FROM sys.dm_exec_requests where blocked <> 0
  • SELECT * FROM master..sysprocesses where blocked <> 0

Deadlock: When something happens as follows: Error 1205 is reported by SQL Server for deadlock.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Explain different isolation levels

A

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):

  1. Read Uncommitted
  2. Read Committed
  3. Repeatable Read
  4. Serializable.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is lock escalation?

A

Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards it’s dynamically managed by SQL Server.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are constraints? Explain different types of constraints.

A

Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults.

Types of constraints:

  1. NOT NULL
  2. CHECK
  3. UNIQUE
  4. PRIMARY KEY
  5. FOREIGN KEY

For an explanation of these constraints see books online for the pages titled: “Constraints” and “CREATE TABLE”, “ALTER TABLE”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Whar is an index? What are the types of indexes? How many clustered indexes can be created on a table? I create a separate index on each column of a table. what are the advantages and disadvantages of this approach?

A

Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes. When you craete a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered index per table. Non-clustered indexes have their own storage separate from the table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes having the index key and it’s row locater. The row located could be the RID or the Clustered index key, depending up on the absence or presence of clustered index on the table.

If you create an index on each column of a table, it improves the query performance, as the query optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the same t ime, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as every time data changes in the table, all the indexes need to be updated.

Another disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What are the steps you will take, if you are tasked with securing an SQL Server?

A

Again this is another open ended question. Here are some things you could talk about: Preferring NT authentication, using server, databse and application roles to control access to the data, securing the physical database files using NTFS permissions, using an unguessable SA password, restricting physical access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls, isolating SQL Server from the web server etc.

Read the white paper on SQL Server security from Microsoft website. Also check out My SQL Server security best practices

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is a deadlock and what is a live lock? How will you go about resolving deadlocks?

A

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. Also check out the article Q169960 from Microsoft knowledge base.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is blocking and how would you troubleshoot it?

A

Blocking happens when one connection from an application holds a lock and a second connection requires a conflicting lock type. This forces the second connection to wait, blocked on the first.

Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding efficient transactions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Explain CREATE DATABASE syntax

A

Many of us are used to craeting databases from the Enterprise Manager or by just issuing the command: CREATE DATABAE MyDB. But what if you have to create a database with two filegroups, one on drive C and the other on drive D with log on drive E with an initial size of 600 MB and with a growth factor of 15%? That’s why being a DBA you should be familiar with the CREATE DATABASE syntax.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

As a part of your job, what are the DBCC commands that you commonly use for database maintenance?

A
  • DBCC CHECKDB
  • DBCC CHECKTABLE
  • DBCC CHECKCATALOG
  • DBCC CHECKALLOC
  • DBCC SHOWCONTIG
  • DBCC SHRINKDATABASE
  • DBCC SHRINKFILE etc.

But there are a whole load of DBCC commands which are very useful for DBAs. Check out SQL Server books online for more information.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What are statistics, under what circumstances they go out of date, how do you update them?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What are the different ways of moving data/databases between servers and databases in SQL Server?

A

There are lots of options available, you have to choose your option depending upon your requirements.

Some of the options you have are:

  • BACKUP/RESTORE
  • Dettaching and attaching databases
  • Rreplication
  • DTS
  • BCP
  • Logshipping
  • INSERT…SELECT, SELECT…INTO
  • Creating INSERT scripts to generate data.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What is database replicaion? What are the different types of replication you can set up in SQL Server?

A

Replication is the process of copying/moving data between databases on the same or different servers. SQL Server supports the following types of replication scenarios:

  • Snapshot replication
  • Transactional replication (with immediate updating subscribers, with queued updating subscribers)
  • Merge replication

See SQL Server books online for indepth coverage on replication. Be prepared to explain how different replication agents function, what are the main system tables used in replication etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?

A

Cursors allow row-by-row prcessing of the resultsets.

Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors. Here is an example:

If you have to give a flat hike to your employees using the following criteria:

Salary between 30000 and 40000 – 5000 hike
Salary between 40000 and 55000 – 7000 hike
Salary between 55000 and 65000 – 9000 hike

In this situation many developers tend to use a cursor, determine each employee’s salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below:

UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END

Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a particular row meets certain condition. You don’t have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using WHILE loop for row by row processing, check out the ‘My code library’ section of my site or search for WHILE.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Write down the general syntax for a SELECT statements covering all the options.

A

Here’s the basic syntax: (Also checkout SELECT in books online for advanced syntax).

SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

(Pre 2005) What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?

A

An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored procedures using the EXEC statement. See books online to learn how to create extended stored procedures and how to add them to SQL Server.

Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty, sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-SQL, see ‘My code library’ section of this site.

But can use CLR now in 2005+

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Can you explain your skill set?

A

◦Employers look for the following:

■DBA (Maintenance, Security, Upgrades, Performance Tuning, etc.)
■Database developer (T-SQL, SSIS, Analysis Services, Reporting Services, Crystal Reports, Service Broker, etc.)
■Communication skills (oral and written)

◦DBA’s opportunity

■This is your 30 second elevator pitch outlining your technical expertise and how you can benefit the organization

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Can you explain the environments you have worked in related to the following items:

A
  • SQL Server versions
  • SQL Server technologies
    • Relational engine, Reporting Services, Analysis Services, Integration Services
  • Number of SQL Servers
  • Number of instances
  • Number of databases
  • Range of size of databases
  • Number of DBAs
  • Number of Developers
  • Hardware specs (CPU’s, memory, 64 bit, SANs)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What are the tasks that you perform on a daily basis and how have you automated them?

A

◦For example, daily checks could include:

  • ■Check for failed processes
  • ■Research errors
  • ■Validate disk space is not low
  • ■Validate none of the databases are offline or corrupt
  • ■Perform database maintenance as available to do so

◦For example, automation could include:

  • ■Setup custom scripts to query for particular issues and email the team
  • ■Write error messages centrally in the application and review that data
  • ■Setup Operators and Alerts on SQL Server Agent Jobs for automated job notification
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

How do you re-architect a process?

A

◦Review the current process to understand what is occurring
◦Backup the current code for rollback purposes
◦Determine what the business and technical problems are with the process
◦Document the requirements for the new process
◦Research options to address the overall business and technology needs

■For example, these could include:

■Views
■Synonyms
■Service Broker
■SSIS
■Migrate to a new platform
■Upgrade in place

◦Design and develop a new solution
◦Conduct testing (functional, load, regression, unit, etc.)
◦Run the systems in parallel
◦Sunset the existing system
◦Promote the new system
◦Additional information - Checklist to Re-Architect a SQL Server Database

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What is your experience with third party applications and why would you use them?

A

◦Experience

■Backup tools
■Performance tools
■Code or data synchronization
■Disaster recovery\high availability

◦Why

■Need to improve upon the functionality that SQL Server offers natively
■Save time, save money, better information or notification

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

How do you identify and correct a SQL Server performance issue?

A

◦Identification - Use native tools like Profiler, Perfmon, system stored procedures, dynamic management views, custom stored procedures or third party tools

◦Analysis - Analyze the data to determine the core problems

◦Testing - Test the various options to ensure they perform better and do not cause worse performance in other portions of the application

◦Knowledge sharing - Share your experience with the team to ensure they understand the problem and solution, so the issue does not occur again

◦Additional information - MSSQLTips.com Category: Performance Tuning and Query Optimization

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

What are the dynamic management views and what value do they offer?

A

◦The DMV’s are a set of system views new to SQL Server 2005 and beyond to gain insights into particular portions of the engine

◦Here are some of the DMV’s and the associated value:

  • sys.dm_exec_query_stats and sys.dm_exec_sql_text - Buffered code in SQL Server
    • Additional Information: Identifying the input buffer in SQL Server 2000 vs SQL Server 2005
  • sys.dm_os_buffer_descriptors
    • Additional Information: Buffer Pool Space in SQL Server 2005
  • sys.dm_tran_locks - Locking and blocking
    • Additional Information: Locking and Blocking Scripts in SQL Server 2000 vs SQL Server 2005
  • sys.dm_os_wait_stats - Wait stats
    • Additional Information: Waitstats performance metrics in SQL Server 2000 vs SQL Server 2005
  • sys.dm_exec_requests and sys.dm_exec_sessions - Percentage complete for a process
    • Additional Information: Finding a SQL Server process percentage complete with dynamic management views
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What is the process to upgrade from DTS to SSIS packages?

A
  • ◦You can follow the steps of the migration wizard but you may need to manually upgrade portions of the package that were not upgraded by the wizard
  • Additional Information: Upgrade SQL Server DTS Packages to Integration Services Packages

◦For script related tasks, these should be upgraded to new native components or VB.NET code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What are some of the features of SQL Server 2012 that you are looking into and why are they of interest?

A

◦AlwaysON
◦Contained Databases
◦User Defined Server Roles
◦New date and time functions
◦New FORMAT and CONCAT functions
◦New IIF and CHOOSE functions
◦New paging features with OFFSET and FETCH
◦NOTE - Many more new features do exist, this is an abbreviated list. ■Additional Information: SQL Server 2012 Denali

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What are the system databases and what are their functions?

A

System database are used to store system information. There are five system databases each one having its own functionality.

  1. Master DB
  2. MSDB
  3. Model
  4. Resource
  5. Temp

Master Database: it stores all the system related information for an instance of SQL Server. It stores the metadata for the database which created in SQL Server Instances.

MSDB Database: it informs the information and activities related to SQL server agent.

Model Database: It is the template to create a new database in SQL server instance .if you have created some object in it will reflect in all database which were created after this until you won’t remove these objects from model database.

Resource Database: Resource database all the system objects views and procedures.

Temp Database: It is used to store temporary objects which create during the execution of query. SQL Server creates a free copy of temp dB whenever server starts. Backup operation is not allowed for the temp DB.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

What are the files in SQL Server?

SQL Server stores the data in data files on hard disk.
What are different types of database files in SQL Server?

A

SQL has three types of database files:

Primary files: Stores the information of the database related to start-up, data and other files details. A database can have one primarily data base file and the file extension for this is .mdf.

Secondary files: Stores the user data. A database can have multiple secondary files which can help user data to spread across the different hard disk.

Transaction logs files: Transaction log files used to store the transactional log.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What is Dirty Read?

A

A dirty read occurs when two operations, say, read and write occur together giving the incorrect or unedited data. Suppose, A changed a row but did not committed the changes. B reads the uncommitted data but his view of the data may be wrong so that is Dirty Read.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

Why can’t I use Outer Join in an Indexed View?

A

Rows can logically disappear from an indexed view based on OUTER JOIN when you insert data into a base table. This makes incrementally updating OUTER JOIN views relatively complex to implement, and the performance of the implementation would be slower than for views based on standard (INNER) JOIN.(Read More Here)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

What is the Correct Order of the Logical Query Processing Phases?

A

The correct order of the Logical Query Processing Phases is as follows:

  1. FROM
  2. ON
  3. OUTER
  4. WHERE
  5. GROUP BY
  6. CUBE | ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. TOP
  11. ORDER BY
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

What are Different Types of Locks?

A

Shared Locks: Used for operations that do not change or update data (read-only operations), such as a SELECT statement.

Update Locks: Used on resources that can be updated. It prevents a common form of deadlock that occurs when multiple sessions are reading, locking, and potentially updating resources later.

Exclusive Locks: Used for data-modification operations, such as INSERT, UPDATE, or DELETE. It ensures that multiple updates cannot be made to the same resource at the same time.

Intent Locks: Used to establish a lock hierarchy. The types of intent locks are as follows: intent shared (IS), intent exclusive (IX), and shared with intent exclusive (SIX).

Schema Locks: Used when an operation dependent on the schema of a table is executing. The types of schema locks are schema modification (Sch-M) and schema stability (Sch-S).

Bulk Update Locks: Used when bulk-copying data into a table and the TABLOCK hint is specified.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

What are Pessimistic Lock and Optimistic Lock?

A

Optimistic Locking is a strategy where you read a record, take note of a version number and check that the version hasn’t changed before you write the record back. If the record is dirty (i.e. different version to yours), then you abort the transaction and the user can re-start it.

Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

When is the use of UPDATE_STATISTICS command?

A

This command is basically used when a large amount of data is processed. If a large amount of deletions, modifications or Bulk Copy into the tables has occurred, it has to update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

What is Connection Pooling and why it is Used?

A

To minimize the cost of opening and closing connections, ADO.NET uses an optimization technique called connection pooling.

The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

Types of Sub-query

A
  1. Single-row sub-query, where the sub-query returns only one row.
  2. Multiple-row sub-query, where the sub-query returns multiple rows, and
  3. Multiple column sub-query, where the sub-query returns multiple columns
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

Which Command using Query Analyzer will give you the Version of SQL Server and Operating System?

A

SELECT SERVERPROPERTY(‘Edition’) AS Edition,
SERVERPROPERTY(‘ProductLevel’) AS ProductLevel,
SERVERPROPERTY(‘ProductVersion’) AS ProductVersion
GO

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

Can a Stored Procedure call itself or a Recursive Stored Procedure? How many levels of SP nesting is possible?

A

Yes. As T-SQL supports recursion, you can write stored procedures that call themselves. Recursion can be defined as a method of problem solving wherein the solution is arrived at by repetitively applying it to subsets of the problem. A common application of recursive logic is to perform numeric computations that lend themselves to repetitive evaluation by the same processing steps.

Stored procedures are nested when one stored procedure calls another or executes managed code by referencing a CLR routine, type, or aggregate. You can nest stored procedures up to 32 levels.

Any reference to managed code from a Transact-SQL stored procedure counts as one level against the 32-level nesting limit. Methods invoked from within managed code do not count against this limit. (Read more here) (Courtesy: Vinod Kumar)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

What is Log Shipping?

A

Log shipping is the process of automating the backup of database and transaction log files on a production SQL server and then restoring them onto a standby server. All Editions (except Express Edition) supports log shipping. In log shipping, the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same db and can be used this as the Disaster Recovery plan. The key feature of log shipping is that it will automatically backup transaction logs throughout the day and automatically restore them on the standby server at defined intervals. (Courtney: Rhys)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

Name 3 ways to get an Accurate Count of the Number of Records in a Table?

A
  1. SELECT * FROM table1
  2. SELECT COUNT(*) FROM table1
  3. SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

What does it mean to have QUOTED_IDENTIFIER ON? What are the Implications of having it OFF?

A

When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation marks, and literals must be delimited by single quotation marks.

When SET QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all T-SQL rules for identifiers. (Read more here)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

What is the STUFF Function and How Does it Differ from the REPLACE Function?

A

STUFF function is used to overwrite existing characters using this syntax: STUFF (string_expression, start, length, replacement_characters), where string_expression is the string that will have characters substituted, start is the starting position, length is the number of characters in the string that are substituted, and replacement_characters are the new characters interjected into the string.

REPLACE function is used to replace existing characters of all occurrences. Using the syntax REPLACE (string_expression, search_string, replacement_string), every incidence of search_string found in the string_expression will be replaced with replacement_string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

What is B-Tree?

A

The database server uses a B-tree structure to organize index information. B-Tree generally has following types of index pages or nodes:

  • Root node: A root node contains node pointers to only one branch node.
  • Branch nodes: A branch node contains pointers to leaf nodes or other branch nodes, which can be two or more.
  • Leaf nodes: A leaf node contains index items and horizontal pointers to other leaf nodes, which can be many.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

How to get @@ERROR and @@ROWCOUNT at the Same Time?

A

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, include both in same statement and store them in a local variable.

SELECT @RC = @@ROWCOUNT, @ER = @@ERROR

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

What are the Advantages of Using Stored Procedures?

A
  • Stored procedure can reduced network traffic and latency, boosting application performance.
  • Stored procedure execution plans can be reused; they staying cached in SQL Server’s memory, reducing server overhead.
  • Stored procedures help promote code reuse.
  • Stored procedures can encapsulate logic. You can change stored procedure code without affecting clients.
  • Stored procedures provide better security to your data.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

What is a Table Called, if it has neither Cluster nor Non-cluster Index? What is it Used for?

A

Unindexed table or Heap. Microsoft Press Books and Book on Line (BOL) refers it as Heap.

A heap is a table that does not have a clustered index and therefore, the pages are not linked by pointers. The IAM pages are the only structures that link the pages in a table together.

Unindexed tables are good for fast storing of data. Many times, it is better to drop all the indexes from table and then do bulk of INSERTs and restore those indexes after that.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

What Command do we Use to Rename a db, a Table and a Column?

A

To Rename db

sp_renamedb ‘oldname’ , ‘newname

If someone is using db it will not accept sp_renmaedb. In that case, first bring db to single user mode using sp_dboptions. Use sp_renamedb to rename the database. Use sp_dboptions to bring the database to multi-user mode.

e.g.

USE MASTER;
GO
EXEC sp_dboption AdventureWorks, ‘Single User’, True
GO
EXEC sp_renamedb ‘AdventureWorks’, ‘AdventureWorks_New’
GO
EXEC sp_dboption AdventureWorks, ‘Single User’, False
GO

To Rename Table

We can change the table name using sp_rename as follows:

sp_rename ‘oldTableName’ ‘newTableName’

e.g.

sp_RENAME ‘Table_First’, ‘Table_Last’
GO

To rename Column

The script for renaming any column is as follows:

sp_rename ‘TableName.[OldcolumnName]’, ‘NewColumnName’, ‘Column’

e.g.
sp_RENAME ‘Table_First.Name’, ‘NameChange’ , ‘COLUMN’
GO

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

What are sp_configure Commands and SET Commands?

A

Use sp_configure to display or change server-level settings. To change the database-level settings, use ALTER DATABASE. To change settings that affect only the current user session, use the SET statement.

e.g.

sp_CONFIGURE ‘show advanced’, 0
GO
RECONFIGURE
GO
sp_CONFIGURE
GO

You can run the following command and check the advanced global configuration settings.
sp_CONFIGURE ‘show advanced’, 1
GO
RECONFIGURE
GO
sp_CONFIGURE
GO

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

What is Difference between Commit and Rollback when Used in Transactions?

A

The usual structure of the TRANSACTION is as follows:

BEGIN TRANSACTION

Operations

COMMIT TRANSACTION or ROLLBACK TRANSACTION

When Commit is executed, every statement between BEGIN and COMMIT becomes persistent to database. When Rollback is executed, every statement between BEGIN and ROLLBACK are reverted to the state when BEGIN was executed.

67
Q

What is Difference between Table Aliases and Column Aliases? Do they Affect Performance?

A

Usually, when the name of the table or column is very long or complicated to write, aliases are used to refer them.

e.g.

SELECT VeryLongColumnName col1
FROM VeryLongTableName tab1

In the above example, col1 and tab1 are the column alias and table alias, respectively. They do not affect the performance at all.

68
Q

What is the difference between CHAR and VARCHAR Datatypes?

A

VARCHARS are variable length strings with a specified maximum length. If a string is less than the maximum length, then it is stored verbatim without any extra characters, e.g. names and emails.

CHARS are fixed-length strings with a specified set length. If a string is less than the set length, then it is padded with extra characters, e.g. phone number and zip codes. For instance, for a column which is declared as VARCHAR(30) and populated with the word ‘SQL Server,’ only 10 bytes will be stored in it. However, if we have declared the column as CHAR(30) and populated with the word ‘SQL Server,’ it will still occupy 30 bytes in database.

69
Q

What is the Difference between VARCHAR and VARCHAR(MAX) Datatypes?

A

VARCHAR stores variable-length character data whose range varies up to 8000 bytes; varchar(MAX) stores variable-length character data whose range may vary beyond 8000 bytes and till 2 GB.

TEXT datatype is going to be deprecated in future versions, and the usage of VARCHAR(MAX) is strongly recommended instead of TEXT datatypes.

70
Q

What is the Difference between VARCHAR and NVARCHAR datatypes?

A

In principle, they are the same and are handled in the same way by your application.

The only difference is that NVARCHAR can handle unicode characters, allowing you to use multiple languages in the database (Arabian, Chinese, etc.). NVARCHAR takes twice as much space when compared to VARCHAR. Use NVARCHAR only if you are using foreign languages.

71
Q

Which are the Important Points to Note when Multilanguage Data is Stored in a Table?

A

There are two things to keep in mind while storing unicode data. First, the column must be of unicode data type (nchar, nvarchar, ntext). Second, the value must be prefixed with N while insertion. For example,

INSERT INTO table (Hindi_col) values (N’hindi data’)

72
Q

How to Optimize Stored Procedure Optimization?

A
  1. Include SET NOCOUNT ON statement.
  2. Use schema name with object name.
  3. Do not use the prefix “sp_” in the stored procedure name.
  4. Use IF EXISTS (SELECT 1) instead of (SELECT *).
  5. Use the sp_executesql stored procedure instead of the EXECUTE statement.
  6. Try to avoid using SQL Server cursors whenever possible.
  7. Keep the Transaction as short as possible.
  8. Use TRY-Catch for error handling.
73
Q

What is SQL Injection? How to Protect Against SQL Injection Attack?

A

SQL injection is an attack in which malicious code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution. Any procedure that constructs SQL statements should be reviewed for injection vulnerabilities because SQL Server will execute all syntactically valid queries that it receives. Even parameterized data can be manipulated by a skilled and determined attacker.

Here are few methods which can be used to protect again SQL Injection attack:

  • Use Type-Safe SQL Parameters
  • Use Parameterized Input with Stored Procedures
  • Use the Parameters Collection with Dynamic SQL
  • Filtering Input parameters
  • Use the escape character in LIKE clause
  • Wrapping Parameters with QUOTENAME() and REPLACE()
74
Q

How to Find Out the List Schema Name and Table Name for the Database?

A

We can use following script:

SELECT ‘[‘+SCHEMA_NAME(schema_id)+’].[‘+name+’]’ AS SchemaTable
FROM sys.tables

75
Q

What is CHECKPOINT Process in the SQL Server?

A

CHECKPOINT process writes all dirty pages for the current database to disk. Dirty pages are data pages that have been entered into the buffer cache and modified, but not yet written to disk.

76
Q

How does Using a Separate Hard Drive for Several Database Objects Improves Performance Right Away?

A

A non-clustered index and tempdb can be created on a separate disk to improve performance.

77
Q

How to Find the List of Fixed Hard Drive and Free Space on Server?

A

We can use the following Stored Procedure to figure out the number of fixed drives (hard drive) a system has along with free space on each of those drives.

EXEC master..xp_fixeddrives

78
Q

Why can there be only one Clustered Index and not more than one?

A

Cluster Index physically stores data, or arranges data in one order (depends on which column(s) you have defined Clustered index and in which order).

As a fact, we all know that a set of data can be only stored in only one order; that is why only one clustered index is possible.(Read more here)

79
Q

What is Difference between Line Feed (\n) and Carriage Return (\r)?

A

Line Feed – LF – \n – 0x0a – 10 (decimal)

Carriage Return – CR – \r – 0x0D – 13 (decimal)

DECLARE @NewLineChar AS CHAR(2) = CHAR(13) + CHAR(10)
PRINT (‘SELECT FirstLine AS FL ‘ +@NewLineChar + ‘SELECT SecondLine AS SL’ )

80
Q

Is It Possible to have Clustered Index on Separate Drive From Original Table Location?

A

No! It is not possible. (Read more here)

81
Q

What is a Hint?

A

Hints are options and strong suggestions specified for enforcement by the SQL Server query processor on DML statements. The hints override any execution plan the query optimizer might select for a query.(Read more here)

There are three different types of hints. Let us understand the basics of each of them separately.

Join Hint

This hint is used when more than one table is used in a query. Two or more tables can be joined using different types of joins. This hint forces the type of join algorithm that is used. Joins can be used in SELECT, UPDATE and DELETE statements.

Query Hint

This hint is used when certain kind of logic has to be applied to a whole query. Any hint used in the query is applied to the complete query as opposed to a part of it. There is no way to specify that only a certain part of a query should be used with the hint. After any query, the OPTION clause is specified to apply the logic to this query. A query always has any of the following statements: SELECT, UPDATE, DELETE, INSERT or MERGE (SQL 2K8); and this hint can be applied to all of them.

Table Hint

This hint is used when certain kind of locking mechanism of tables has to be controlled. SQL Server query optimizer always puts the appropriate kind of lock on tables, when any of the Transact SQL operations SELECT, UPDATE, DELETE, INSERT or MERGE is used. There are certain cases when the developer knows when and where to override the default behavior of the locking algorithm, and these hints are useful in those scenarios. (Read more here)

82
Q

How to Delete Duplicate Rows?

A
WITH CTE (COl1,Col2, DuplicateCount) AS (
         SELECT         COl1        ,Col2
   ,ROW\_NUMBER() OVER(PARTITION BY COl1,Col2 ORDER BY Col1) AS DuplicateCount
    FROM DuplicateRcordTable
  )  DELETE  FROM CTE  WHERE DuplicateCount \>1
83
Q

Why the Trigger Fires Multiple Times in Single Login?

A

It happens because multiple SQL Server services are running and also as intellisense is turned on. (Read more here)

84
Q

What is Aggregate Functions?

A

Aggregate functions perform a calculation on a set of values and return a single value. Aggregate functions ignore NULL values except COUNT function. HAVING clause is used, along with GROUP BY for filtering query using aggregate values.

The following functions are aggregate functions.

  • AVG
  • MIN
  • CHECKSUM_AGG
  • SUM
  • COUNT
  • STDEV
  • COUNT_BIG
  • STDEVP
  • GROUPING
  • VAR
  • MAX
  • VARP
85
Q

What is Use of @@ SPID in SQL Server?

A

A SPID is the returns sessions ID of the current user process. And using that session ID, we can find out that the last query was executed. (Read more here)

86
Q

What is the Difference between Index Seek vs. Index Scan?

A

An index scan means that SQL Server reads all the rows in a table, and then returns only those rows that satisfy the search criteria. When an index scan is performed, all the rows in the leaf level of the index are scanned. This essentially means that all the rows of the index are examined instead of the table directly. This is sometimes compared to a table scan, in which all the table data is read directly. However, there is usually little difference between an index scan and a table scan.

An index seek, on the other hand, means that the Query Optimizer relies entirely on the index leaf data to locate rows satisfying the query condition. An index seek will be most beneficial in cases where a small percentage of rows will be returned. An index seek will only affect the rows that satisfy a query condition and the pages that contain these qualifying rows; in terms of performance, this is highly beneficial when a table has a very large number of rows. (Read more here)

87
Q

What is the Maximum Size per Database for SQL Server Express?

A

SQL Server Express supports a maximum size of 4 GB per database, which excludes all the log files. 4 GB is not a very large size; however, if the database is properly designed and the tables are properly arranged in a separate database, this limitation can be resolved to a certain extent.

88
Q

How do We Know if Any Query is Retrieving a Large Amount of Data or very little data?

A

In one way, it is quite easy to figure this out by just looking at the result set; however, this method cannot be relied upon every time as it is difficult to reach a conclusion when there are many columns and many rows.

It is easy to measure how much data is retrieved from server to client side. The SQL Server Management Studio has feature that can measure client statistics. (Read more here)

89
Q

What is the Difference between GRANT and WITH GRANT while Giving Permissions to the User?

A

In case of only GRANT, the username cannot grant the same permission to other users. On the other hand, with the option WITH GRANT, the username will be able to give the permission after receiving requests from other users. (Read more here)

90
Q

How to Create Primary Key with Specific Name while Creating a Table?

A

CREATE TABLE [dbo].TestTable
GO

91
Q

What is T-SQL Script to Take Database Offline – Take Database Online?

A

– Take the Database Offline
ALTER DATABASE [myDB] SET OFFLINE WITH
ROLLBACK IMMEDIATE
GO
– Take the Database Online
ALTER DATABASE [myDB] SET ONLINE
GO

92
Q

How to Enable/Disable Indexes?

A

–Disable Index
ALTER INDEX [IndexName] ON TableName DISABLE
GO
–Enable Index
ALTER INDEX [IndexName] ON TableName REBUILD
GO

93
Q

Can we Insert Data if Clustered Index is Disabled?

A

No, we cannot insert data if Clustered Index is disabled because Clustered Indexes are in fact original tables which are physically ordered according to one or more keys (Columns).

(Read more here)

94
Q

How to Recompile Stored Procedure at Run Time?

A

We can Recompile Stored Procedure in two ways.

Option 1:

CREATE PROCEDURE dbo.PersonAge(@MinAge INT, @MaxAge INT)
WITH RECOMPILE
AS
SELECT*
FROM dbo.tblPerson
WHERE Age <= @MinAge AND Age >= @MaxAge
GO

Option 2:

EXEC dbo.PersonAge65, 70 WITHRECOMPILE

We can use RECOMPILE hint with a query and recompile only that particular query. However, if the parameters are used in many statements in the stored procedure and we want to recompile all the statements, then instead of using the RECOMPILE option with all the queries, we have one better option that uses WITH RECOMPILE during stored procedure creation or execution.

This method is not recommended for large stored procedures because the recompilation of so many statements may outweigh the benefit of a better execution plan. (Read more here)

95
Q

Is there any Performance Difference between IF EXISTS (Select null from table) and IF EXISTS (Select 1 from table)?

A

There is no performance difference between IF EXISTS (Select null from table) and IF EXISTS (Select 1 from table). (Read more here)

96
Q

What is Difference in Performance between INSERT TOP (N) INTO Table and Using Top with INSERT?

A

INSERT TOP (N) INTO Table is faster than Using Top with INSERT but when we use INSERT TOP (N) INTO Table, the ORDER BY clause is totally ignored. (Read more here)

97
Q

Does the Order of Columns in UPDATE statements Matter?

A

No, the order of columns in UPDATE statement does not matter for results updated.

Both the below options produce the same results.

Option 1:

UPDATE TableName
SET Col1 =’Value’, Col2 =’Value2’

Option 2:

UPDATE TableName
SET Col2 =’Value2’, Col1 =’Value’

98
Q

What are the basic functions for master, msdb, model, tempdb and resource databases? 2008

A

The master database holds information for all the databases located on the SQL Server instance, and it is the glue that holds the engine together. Because SQL Server cannot start without a functioning master database, you must administer this database with care.

The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping.

The tempdb holds temporary objects such as global and local temporary tables and stored procedures.

The model is essentially a template database used in the creation of any new user database created in the instance.

The resource Database is a read-only database that contains all the system objects that are included in the SQL Server. SQL Server system objects such as sys.objects are physically persisted in the Resource database, but they logically appear in the sys schema of every database. The Resource database does not contain user data or user metadata.

99
Q

What is the Maximum Number of Index per Table?

A

For SQL Server 2005:

1 Clustered Index + 249 Nonclustered Index = 250 Index.

For SQL Server 2008:

1 Clustered Index + 999 Nonclustered Index = 1000 Index. (Read more here)

100
Q
A

SQL Server 2008 Microsoft has upgraded SSMS with many new features as well as added tons of new functionalities requested by DBAs for long time.

  • A few of the important new features are as follows:
  • IntelliSense for Query Editing
  • Multi Server Query
  • Query Editor Regions
  • Object Explorer Enhancements
  • Activity Monitors
101
Q

Explain IntelliSense for Query Editing:

A

After implementing IntelliSense, we will not have to remember all the syntax or browse online references. IntelliSense offers a few additional features besides just completing the keyword.

102
Q

Explain MultiServer Query:

A

SSMS 2008 has a feature to run a query on different servers from one query editor window. First of all, make sure that you registered all the servers under your registered server. Once they are registered, right click on server group name and click New Query.

e.g. for server version information,

SELECT
SERVERPROPERTY(‘Edition’) AS Edition,
SERVERPROPERTY(‘ProductLevel’) AS ProductLevel,
SERVERPROPERTY(‘ProductVersion’) AS ProductVersion

103
Q

Explain Query Editor Regions:

A

When the T-SQL code is more than hundreds of lines, after a while, it becomes more and more confusing.

The regions are defined by the following hierarchy:

From first GO command to the next GO command.

Statements between BEGIN – END, BEGIN TRY – END TRY, BEGIN CATCH – END CATCH

104
Q

Explain Object Explorer Enhancements:

A

In Object Explorer Detail, the new feature is Object Search. Enter any object name in the object search box and the searched result will be displayed in the same window as Object Explorer Detail.

Additionally, there are new wizards which help you perform several tasks, from policy management to disk monitoring. One cool thing is that everything displayed in the object explorer details screen can be right away copied and pasted to Excel without any formatting issue.

105
Q

Explain Activity Monitors:

A

There are four graphs

  1. percent; Processor Time,
  2. Waiting Tasks,
  3. Database I/O,
  4. Batch Requests/Sec

All the four tabs provide very important information; however, the one which I refer most is “Recent Expensive Queries.” Whenever I find my server running slow or having any performance-related issues, my first reaction is to open this tab and see which query is running slow. I usually look at the query with the highest number for Average Duration. The Recent Expensive Queries monitors only show queries which are in the SQL Server cache at that moment. (Read more here)

106
Q

What is Service Broker?

A

Service Broker is a message-queuing technology in SQL Server that allows developers to integrate SQL Server fully into distributed applications. Service Broker is a feature which provides facility to SQL Server to send an asynchronous, transactional message. It allows a database to send a message to another database without waiting for the response; so the application will continue to function if the remote database is temporarily unavailable. (Read more here)

107
Q

Where are SQL server Usernames and Passwords Stored in the SQL server?

A

They get stored in System Catalog Views, sys.server_principals and sys.sql_logins. However, you will not find password stored in plain text.

108
Q

What is Policy Management?

A

Policy Management in SQL SERVER 2008 allows you to define and enforce policies for configuring and managing SQL Server across the enterprise. Policy-Based Management is configured in SQL Server Management Studio (SSMS). Navigate to the Object Explorer and expand the Management node and the Policy Management node; you will see the Policies, Conditions, and Facets nodes. (Read More Here)

109
Q

What is Database Mirroring?

A

Database mirroring can be used with replication to provide availability for the publication database. Database mirroring involves two copies of a single database that typically reside on different computers. At any given time, only one copy of the database is currently available to clients, which is known as the principal database. Updates made by the clients to the principal database are applied to the other copy of the database, known as the mirror database. Mirroring involves applying the transaction log from every insertion, update, or deletion made on the principal database onto the mirror database.

110
Q

What are Sparse Columns?

A

A sparse column is another tool used to reduce the amount of physical storage used in a database. They are the ordinary columns that have an optimized storage for null values. Sparse columns reduce the space requirements for null values at the cost of more overhead to retrieve non-null values. (Read more here)

111
Q

What does TOP Operator Do?

A

The TOP operator is used to specify the number of rows to be returned by a query. The TOP operator has new addition in SQL SERVER 2008 that it accepts variables as well as literal values and can be used with INSERT, UPDATE, and DELETE statements.

112
Q

What is CTE?

A

CTE is the abbreviation for Common Table Expression. A CTE is an expression that can be thought of as a temporary result set which is defined within the execution of a single SQL statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. (Read more here)

113
Q
A

MERGE is a new feature that provides an efficient way to perform multiple DML operations. In previous versions of SQL Server, we had to write separate statements to INSERT, UPDATE, or DELETE data based on certain conditions, but now, using MERGE statement, we can include the logic of such data modifications in one statement that even checks when the data is matched, then just update it, and when unmatched, insert it. One of the most important advantages of MERGE statement is all the data is read and processed only once. (Read more here)

114
Q
A

Filtered Index is used to index a portion of rows in a table that means it applies filter on INDEX which improves query performance, reduces index maintenance costs, and reduces index storage costs when compared with full-table indexes. When we see an Index created with a WHERE clause, then that is actually a FILTERED INDEX.

115
Q

Which are the New Data Types Introduced in SQL SERVER 2008?

A

The GEOMETRY Type: The GEOMETRY datatype is a system .NET common language runtime (CLR) datatype in SQL Server. This type represents data in a two-dimensional Euclidean coordinate system.

The GEOGRAPHY Type: The GEOGRAPHY datatype’s functions are the same as with GEOMETRY. The difference between the two is that when you specify GEOGRAPHY, you are usually specifying points in terms of latitude and longitude.

New Date and Time Data types: SQL Server 2008 introduces four new data types related to date and time: DATE, TIME, DATETIMEOFFSET, and DATETIME2.

  • DATE: The new DATE data type just stores the date itself. It is based on the Gregorian calendar and handles years from 1 to 9999.
  • TIME: The new TIME (n) type stores time with a range of 00:00:00.0000000 through 23:59:59.9999999. The precision is allowed with this type. TIME supports seconds down to 100 nanoseconds. The n in TIME(n) defines this level of fractional second precision from 0 to 7 digits of precision.
  • The DATETIMEOFFSET Type: DATETIMEOFFSET (n) is the time-zone-aware version of a datetime datatype. The name will appear less odd when you consider what it really is: a date + time + time-zone offset. The offset is based on how far behind or ahead you are from Coordinated Universal Time (UTC) time.
  • The DATETIME2 Type: It is an extension of the datetime type in earlier versions of SQL Server. This new datatype has a date range covering dates from January 1 of year 1 through December 31 of year 9999. This is a definite improvement over the lower boundary of 1753 of the datetime datatype. DATETIME2 not only includes the larger date range, but also has a timestamp and the same fractional precision that TIME type provides.
116
Q

What are the Advantages of Using CTE?

A
  • Using CTE improves the readability and enables easy maintenance of complex queries.
  • The query can be divided into separate, simple, and logical building blocks, which can be then used to build more complex CTEs until the final result set is generated.
  • CTE can be defined in functions, stored procedures, triggers or even views.
  • After a CTE is defined, it can be used as a Table or a View and can SELECT, INSERT, UPDATE or DELETE Data.
117
Q

How can we Rewrite Sub-Queries into Simple Select Statements or with Joins?

A

Yes. We can rewrite sub-queries using the Common Table Expression (CTE). A Common Table Expression (CTE) is an expression that can be thought of as a temporary result set which is defined within the execution of a single SQL statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query.

e.g.
USE AdventureWorks
GO
WITH EmployeeDepartment_CTE AS (
SELECT EmployeeID,DepartmentID,ShiftID
FROM HumanResources.EmployeeDepartmentHistory
)
SELECT ecte.EmployeeId,ed.DepartmentID, ed.Name,ecte.ShiftID
FROM HumanResources.Department ed
INNER JOIN EmployeeDepartment_CTE ecte ON ecte.DepartmentID = ed.DepartmentID
GO

118
Q

What is CLR?

A

In SQL Server 2008, SQL Server objects such as user-defined functions can be created using such CLR languages. This CLR language support extends not only to user-defined functions, but also to stored procedures and triggers. You can develop such CLR add-ons to SQL Server using Visual Studio 2008. (Read more here)

119
Q
A

Synonyms give you the ability to provide alternate names for database objects. You can alias object names; for example, using the Employee table as Emp. You can also shorten names. This is especially useful when dealing with three and four part names; for example, shortening server.database.owner.object to object. (Read more here)

120
Q

What is LINQ?

A
Language Integrated Query (LINQ) adds the ability to query objects using .NET languages. The LINQ to SQL object/relational mapping (O/RM) framework provides the following basic features:
 Tools to create classes (usually called entities) mapped to database tables
 Compatibility with LINQ’s standard query operations
 The DataContext class with features such as entity record monitoring, automatic SQL statement generation, record concurrency detection, and much more
121
Q

What are Isolation Levels?

A

Transactions specify an isolation level that defines the degree to which one transaction must be isolated from resource or data modifications made by other transactions. Isolation levels are described in terms of which concurrency side-effects, such as dirty reads or phantom reads, are allowed.

Transaction isolation levels control the following:

  • Whether locks are taken when data is read, and what type of locks are requested.
  • How long the read locks are held.
  • Whether a read operation referencing rows modified by another transaction
    • blocks until the exclusive lock on the row is freed,
    • retrieves the committed version of the row that existed at the time the statement or transaction started, and
    • reads the uncommitted data modification.(Read more here)
122
Q

What is Use of EXCEPT Clause?

A

EXCEPT clause is similar to MINUS operation in Oracle. The EXCEPT query and MINUS query return all rows in the first query that are not returned in the second query. Each SQL statement within the EXCEPT query and MINUS query must have the same number of fields in the result sets with similar data types. (Read more here)

123
Q

What is XPath?

A

XPath uses a set of expressions to select nodes to be processed. The most common expression that you’ll use is the location path expression, which returns back a set of nodes called a node set. XPath can use both an unabbreviated and abbreviated syntax. The following is the unabbreviated syntax for a location path:

/axisName::nodeTest[predicate]/axisName::nodeTest[predicate]

124
Q

What is NOLOCK?

A

Using the NOLOCK query optimizer hint is generally considered a good practice in order to improve concurrency on a busy system. When the NOLOCK hint is included in a SELECT statement, no locks are taken on data when data is read. The result is a Dirty Read, which means that another process could be updating the data at the exact time you are reading it. There are no guarantees that your query will retrieve the most recent data. The advantage to performance is that your reading of data will not block updates from taking place, and updates will not block your reading of data. SELECT statements take Shared (Read) locks. This means that multiple SELECT statements are allowed simultaneous access, but other processes are blocked from modifying the data. The updates will queue until all the reads have completed, and reads requested after the update will wait for the updates to complete. The result to your system is delay (blocking). (Read more here)

125
Q

What is the Difference between Update Lock and Exclusive Lock?

A

When Exclusive Lock is on any process, no other lock can be placed on that row or table. Every other process have to wait till Exclusive Lock completes its tasks.

Update Lock is a type of Exclusive Lock, except that it can be placed on the row which already has Shared Lock on it. Update Lock reads the data of the row which has the Shared Lock as soon as the Update Lock is ready to change the data it converts itself to the Exclusive Lock. (Read more here)

126
Q

How will you Handle Error in SQL SERVER 2008?

A

SQL Server now supports the use of TRY…CATCH constructs for providing rich error handling. TRY…CATCH lets us build error handling at the level we need, in the way we need to by setting a region where if any error occurs, it will break out of the region and head to an error handler. The basic structure is as follows:
BEGIN TRY
` END TRY BEGIN CATCH END CATCH So if any error occurs in the TRY block, then execution is diverted to the CATCH block, and the error can be resolved. `

127
Q

What is RAISEERROR?

A

RaiseError generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY…CATCH construct. (Read more here)

128
Q

How to Rebuild the Master Database?

A

Master database is system database and it contains information about running server’s configuration. When SQL Server 2005 is installed, it usually creates master, model, msdb, tempdb, resourcedb and the distribution system database by default. Only the Master database is the one which is absolutely a must-have database. Without the Master database, the SQL Server cannot be started. This is the reason why it is extremely important to backup the Master database.

To rebuild the Master database, run Setup.exe, verify, and repair a SQL Server instance, and rebuild the system databases. This procedure is most often used to rebuild the master database for a corrupted installation of SQL Server. (Read more here)

129
Q

What is the XML Datatype?

A

The xml data type lets you store XML documents and fragments in a SQL Server database. An XML fragment is an XML instance that has a missing single top-level element. You can create columns and variables of the xml type and store XML instances in them. The xml data type and associated methods help integrate XML into the relational framework of SQL Server.

130
Q

What is Data Compression?

A

In SQL SERVE 2008, Data Compression comes in two flavors:
Row Compression
Page Compression

Row Compression

Row compression changes the format of physical storage of data. It minimize the metadata (column information, length, offsets etc) associated with each record. Numeric data types and fixed-length strings are stored in variable-length storage format, just like Varchar. (Read more here)

Page Compression

Page compression allows common data to be shared between rows for a given page. It uses the following techniques to compress data:
Row compression.
Prefix Compression. For every column in a page, duplicate prefixes are identified. These prefixes are saved in compression information headers which resides after the page header. A reference number is assigned to these prefixes and that reference number is replaced where ever those prefixes are being used.

Dictionary Compression

Dictionary compression searches for duplicate values throughout the page and stores them in CI. The main difference between prefix and dictionary compression is that the former is only restricted to one column while the latter is applicable to the complete page.

131
Q

What is Use of DBCC Commands?

A

The Transact-SQL programming language provides DBCC statements that act as Database Console Commands for SQL Server. DBCC commands are used to perform the following tasks.
Maintenance tasks on database, index, or filegroup.
Tasks that gather and display various types of information.
Validation operations on a database, table, index, catalog, filegroup, or allocation of database pages.
Miscellaneous tasks such as enabling trace flags or removing a DLL from memory. (Read more here)

132
Q

How to Copy the Tables, Schema and Views from one SQL Server to Another?

A

There are multiple ways to do this.

  1. “Detach Database” from one server and “Attach Database” to another server.
  2. Manually script all the objects using SSMS and run the script on a new server.
  3. Use Wizard of SSMS. (Read more here)
133
Q

How to Find Tables without Indexes?

A

USE <database_name>;<br></br> GO<br></br> SELECT SCHEMA_NAME(schema_id) AS schema_name<br></br> ,name AS table_name<br></br> FROM sys.tables<br></br> WHERE OBJECTPROPERTY(OBJECT_ID,'IsIndexed') = 0<br></br> ORDER BY schema_name, table_name;<br></br> GO</database_name>

134
Q

How to Copy Data from One Table to Another Table?

A

There are multiple ways to do this.

1) INSERT INTO SELECT

This method is used when table is already created in the database earlier and data have to be inserted into this table from another table. If columns listed in the INSERT clause and SELECT clause are same, listing them is not required.

2) SELECT INTO

This method is used when table is not created earlier and it needs to be created when data from one table must be inserted into a newly created table from another table. The new table is created using the same data types as those in selected columns. (Read more here)

135
Q

What is Catalog Views?

A

Catalog views return information that is used by the SQL Server Database Engine. Catalog Views are the most general interface to the catalog metadata and provide the most efficient way to obtain, transform, and present customized forms of this information. All user-available catalog metadata is exposed through catalog views.

136
Q

What is PIVOT and UNPIVOT?

A

A Pivot Table can automatically sort, count, and total the data stored in one table or spreadsheet and create a second table displaying the summarized data. The PIVOT operator turns the values of a specified column into column names, effectively rotating a table.

In simpler word UNPIVOT table is reverse of PIVOT Table, however it is not exactly true. UNPIVOTING is for sure reverse operation to PIVOTING but if during PIVOTING process data aggregated the UNPIVOT table does not return to original table. (Read more here)

137
Q

What is a Filestream?

A

Filestream allows you to store large objects in the file system and have these files integrated within the database. It enables SQL Server-based applications to store unstructured data such as documents, images, audios and videos in the file system. FILESTREAM basically integrates the SQL Server Database Engine with New Technology File System (NTFS); it basically stores the data in varbinary (max) data type. Using this data type, the unstructured data is stored in the NTFS file system, and the SQL Server Database Engine manages the link between the Filestream column and the actual file located in the NTFS. Using Transact-SQL statements users can insert, update, delete and select the data stored in FILESTREAM-enabled tables.

138
Q

What are Ranking Functions?

A

Ranking functions return a ranking value for each row in a partition. All the ranking functions are non-deterministic. The different Ranking functions are as follows:

ROW_NUMBER () OVER ([<partition_by_clause>] <order_by_clause>)<br></br> Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.<br></br> <br></br> RANK () OVER ([<partition_by_clause>] <order_by_clause>)<br></br> Returns the rank of each row within the partition of a result set.<br></br> <br></br> DENSE_RANK () OVER ([<partition_by_clause>] <order_by_clause>)<br></br> Returns the rank of rows within the partition of a result set, without any gaps in the ranking. (Read more here )<br></br> </order_by_clause></partition_by_clause></order_by_clause></partition_by_clause></order_by_clause></partition_by_clause>

139
Q

What is Change Data Capture (CDC) in SQL Server 2008?

A

Change Data Capture (CDC) records INSERTs, UPDATEs, and DELETEs applied to SQL Server tables and makes a record available of what changed, where, and when, in simple relational ‘change tables’ rather than in an esoteric chopped salad of XML. These change tables contain columns that reflect the column structure of the source table you have chosen to track along with the metadata needed to understand the changes that have been made.

140
Q

How can I Track the Changes or Identify the Latest Insert-Update-Delete from a Table?

A

In SQL Server 2005 and earlier versions, there is no inbuilt functionality to know which row was recently changed and what the changes were. However, in SQL Server 2008, a new feature known as Change Data Capture (CDC) has been introduced to capture the changed data. (Read more here)

141
Q

What is the CPU Pressure?

A

CPU pressure is a state wherein the CPU is fully occupied with currently assigned tasks and there are more tasks in the queue that have not yet started. (Read more here)

142
Q

How can I Get Data from a Database on Another Server?

A

If you want to import data only through T-SQL query, then use OPENDATASOURCE function. To repeatedly get data from another server, create a linked server and then use the OPENQUERY function or use 4-part naming. If you are not adhered with T-SQL, then it is better to use import/export wizard, and you can save it as a SSIS package for future use. (Read more here)

143
Q

What is the Bookmark Lookup and RID Lookup?

A

When a small number of rows are requested by a query, the SQL Server optimizer will try to use a non-clustered index on the column or columns contained in the WHERE clause to retrieve the data requested by the query. If the query requests data from columns not present in the non-clustered index, then the SQL Server must go back to the data pages to get the data in those columns. Even if the table has a clustered index or not, the query will still have to return to the table or clustered index to retrieve the data.

In the above scenario, if table has clustered index, it is called bookmark lookup (or key lookup); if the table does not have clustered index, but a non-clustered index, it is called RID lookup. (Read more here)

144
Q

What is Difference between ROLLBACK IMMEDIATE and WITH NO_WAIT during ALTER DATABASE?

A

ROLLBACK AFTER integer [SECONDS] | ROLLBACK IMMEDIATE:

Specifies whether to roll back after a specified number of seconds or immediately if transaction is not complete.

NO_WAIT:

Specifies that if the requested database state or option change cannot complete immediately without waiting for transactions to commit or roll back on their own, then the request will fail.(Read more here)

145
Q

What is Difference between GETDATE and SYSDATETIME in SQL Server 2008?

A

In case of GETDATE, the precision is till milliseconds, and in case of SYSDATETIME, the precision is till nanoseconds.(Read More Here)

146
Q

How can I Check that whether Automatic Statistic Update is Enabled or not?

A

The following query can be used to know if Automatic Statistic Update:

SELECT is_auto_create_stats_on,is_auto_update_stats_on
FROM sys.databases
WHERE name =‘YOUR DATABASE NAME

147
Q

How to Find Index Size for Each Index on Table?

A

SELECT *
FROM sys.indexes
WHERE OBJECT_ID=OBJECT_ID(‘HumanResources.Shift’)

148
Q

What is the Difference between Seek Predicate and Predicate?

A

Seek Predicate is the operation that describes the b-tree portion of the Seek. Predicate is the operation that describes the additional filter using non-key columns. Based on the description, it is very clear that Seek Predicate is better than Predicate as it searches indexes, whereas in Predicate, the search is on non-key a column – which implies that the search is on the data in page, files itself.

149
Q

What are Basics of Policy Management?

A

SQL server 2008 has introduced a policy management framework, which is the latest technique for SQL server database engine. SQL policy administrator uses SQL Server Management Studio to create policies that can handle entities on the server side like the SQL Server objects and the instance of SQL Server databases. It consists of three components: policy administrators (who create policies), policy management, and explicit administration. Policy-based management in SQL Server assists the database administrators in defining and enforcing policies that tie to database objects and instances. These policies allow the administrator to configure and manage SQL server across the enterprise. (Read more here)

150
Q

What are the Advantages of Policy Management?

A

The following advantages can be achieved by appropriate administration of policy management system.

  • It interacts with various policies for successful system configuration.
  • It handles the changes in the systems that are the result of configuration against authoring policies.
  • It reduces the cost of ownership with simple elaboration of administration tasks.
  • It detects various compliance issues in SQL Server Management Studio.
151
Q

What are Policy Management Terms?

A

To have a better grip on the concept of Policy-based management, there are some key terms you need to understand.

Target – A type of entity that is appropriately managed by Policy-based management. For example, a table, database and index, to name a few.

Facet -A property that can be managed in policy-based management. A clear example of facet is the name of Trigger or the Auto Shrink Property of database.

Conditions – Criteria that specifies the state of facet to true or false. For example, you can adjust the state of a facet that gives you clear specifications of all stored procedures in the Schema ‘Banking’.

Policy – A set of rules specified for the server objects or the properties of database.

152
Q

What is the ‘FILLFACTOR’?

A

A “FILLFACTOR” is one of the important arguments that can be used while creating an index.

According to MSDN, FILLFACTOR specifies a percentage that indicates how much the Database Engine should fill each index page during index creation or rebuild. Fill-factor is always an integer valued from 1 to 100. The fill-factor option is designed for improving index performance and data storage. By setting the fill-factor value, you specify the percentage of space on each page to be filled with data, reserving free space on each page for future table growth.

Specifying a fill-factor value of 70 would imply that 30 percent of each page will be left empty, providing space for index expansion as data is added to the underlying table. The fill-factor setting applies only when the index is created or rebuilt. (Read more here)

153
Q

Where in MS SQL Server is ’100’ equal to ‘0’?

A

Fill-factor settings of 0 and 100 are equal! (Read more here)

154
Q

Fill-factor settings of 0 and 100 are equal! (Read more here)

A
  1. If fill-factor is set to 100 or 0, the Database Engine fills pages to their capacity while creating indexes.
  2. The server-wide default FILLFACTOR is set to 0.
  3. To modify the server-wide default value, use the sp_configure system stored procedure.
  4. To view the fill-factor value of one or more indexes, use sys.indexes.
  5. To modify or set the fill-factor value for individual indexes, use CREATE INDEX or ALTER INDEX statements.
  6. Creating a clustered index with a FILLFACTOR < 100 may significantly increase the amount of space the data occupies because the Database Engine physically reallocates the data while building the clustered index. (Read more here)
155
Q

What is a ROLLUP Clause?

A

ROLLUP clause is used to do aggregate operation on multiple levels in hierarchy. If we want sum on different levels without adding any new column, then we can do it easily using ROLLUP. We have to just add the WITH ROLLUP Clause in group by clause. (Read more here)

156
Q

What are Various Limitations of the Views?

A
  • ORDER BY clause does not work in View.
  • Regular queries or Stored Procedures give us flexibility when we need another column; we can add a column to regular queries right away. If we want to do the same with Views, then we will have to modify them first.
  • Index created on view not used often.
  • Once the view is created and if the basic table has any column added or removed, it is not usually reflected in the view till it is refreshed.
  • One of the most prominent limitations of the View it is that it does not support COUNT (*); however, it can support COUNT_BIG (*).
  • UNION Operation is now allowed in Indexed View.
  • We cannot create an Index on a nested View situation means we cannot create index on a view which is built from another view.
  • SELF JOIN Not Allowed in Indexed View.
  • Outer Join Not Allowed in Indexed Views.
  • Cross Database Queries Not Allowed in Indexed View.
157
Q

What is a Covered index?

A

It is an index that can satisfy a query just by its index keys without having needed to touch the data pages.

It means that when a query is fired, SQL Server doesn’t need to go to the table to retrieve the rows, but can produce the results directly from the index as the index covers all the columns used in query.

158
Q

When I Delete any Data from a Table, does the SQL Server reduce the size of that table?

A

When data are deleted from any table, the SQL Server does not reduce the size of the table right away; however, it marks those pages as free pages, showing that they belong to the table. When new data are inserted, they are put into those pages first. Once those pages are filled up, SQL Server will allocate new pages. If you wait for sometime, the background process de-allocates the pages, finally reducing the page size. (Read more here)

159
Q

What are Wait Types?

A

There are three types of wait types, namely,

Resource Waits. Resource waits occur when a worker requests access to a resource that is not available because that resource is either currently used by another worker or it’s not yet available.

Queue Waits. Queue waits occur when a worker is idle, waiting for work to be assigned.

External Waits. External waits occur when an SQL Server worker is waiting for an external event. (Read more here)

160
Q

How to Stop Log File Growing too Big?

A

If your Transaction Log file was growing too big and you wanted to manage its size, then instead of truncating transaction log file, you should choose one of the options mentioned below.

1) Convert the Recovery Model to Simple Recovery

If you change your recovery model to Simple Recovery Model, then you will not encounter the extraordinary growth of your log file. However, please note if you have one long running transaction it will for sure grow your log file till the transaction is complete.

2) Start Taking Transaction Log Backup

In this Full Recovery Model, your transaction log will grow until you take a backup of it. You need to take the T-Log Backup at a regular interval. This way, your log would not grow beyond some limits.

161
Q

If any Stored Procedure is Encrypted, then can we see its definition in Activity Monitor?

A

No, we can’t see definition of encrypted stored procedure in Activity Monitor.(Read More Here)

162
Q

What is SQL Azure?

A

SQL Azure is a cloud based relational database as a Service offered by Microsoft. Conceptually it is SQL server in the cloud.

163
Q

What are the system databases and what are their functions?

A

System database are used to store system information. There are five system databases each one having its own functionality.

  1. Master DB
  2. MSDB
  3. Model
  4. Resource
  5. Temp

Master Database: it stores all the system related information for an instance of SQL Server. It stores the metadata for the database which created in SQL Server Instances.

MSDB Database: it informs the information and activities related to SQL server agent.

Model Database: It is the template to create a new database in SQL server instance .if you have created some object in it will reflect in all database which were created after this until you won’t remove these objects from model database.

Resource Database: Resource database all the system objects views and procedures.
Temp Database: It is used to store temporary objects which create during the execution of query. SQL Server creates a free copy of temp dB whenever server starts. Backup operation is not allowed for the temp DB.