Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

SQL SERVER DBA QUEs

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

What purpose does the model database serve?

The model database, as its name implies, serves as the model (or template)
for all databases created on the same instance. If the model database is
modified, all subsequent databases created on that instance will pick up
those changes, but earlier created databases will not. Note that TEMPDB is
also created from the model every time SQL Server starts up.

How do you trace the traffic hitting a SQL Server?

SQL profiler is the SQL Server utility you can use to trace the traffic on the
SQL Server instance. Traces can be filtered to narrow down the transactions
that are captured and reducing the overhead incurred for the trace. The trace
files can be searched, saved off, and even replayed to facilitate
troubleshooting.

What are the recovery models for a database?

There are 3 recovery models available for a database. Full, Bulk-Logged, and
Simple are the three recovery models available.

Recover deleted table from the database


You can restore the BACKUP with a different name in the same instance and
follow steps below.

1) restore the database ( right click on databases > Restore ( it can be in the
same instance )) with a differente name.
2) In this new database ( The restored one ) , open tables , search the table
you've deleted, right button, Script table as > CREATE TO. This will crate a Script.
Execute it on the old database ( the one you have deleted the table). It will
create the structure of that table.
3) Now you can do something like this:

USE [Old Database]


GO
SELECT * INTO [the blank table you've created in the new database]
FROM [the table on the backup, that has Data]
This will copy the data from the backup table, to the table you created.

Recover accidentally deleted rows from a table


If your database is in full recovery mode you can also try third party tools
such as ApexSQL Log or SQL Log Rescue.
These tools will attempt to read your transaction log and reconstruct
statements.
You can also try reading transaction log manually using fn_dblog function but
it’s going to be complex since this is not a well-documented function.

Why Does the Transaction Log Keep Growing or


Run Out of Space?

How to identify which query is filling up the


tempdb transaction log?
SELECT TSU.session_id,
TSU.alloc_pages * 1.0 / 128 AS [internal object MB space],
TSU.dealloc_pages * 1.0 / 128 AS [internal object dealloc MB space],
EST.text,
-- Extract statement from sql text
ISNULL(
NULLIF(
SUBSTRING(
EST.text,
ERQ.statement_start_offset / 2,
CASE WHEN ERQ.statement_end_offset < ERQ.statement_start_offset
THEN 0
ELSE( ERQ.statement_end_offset - ERQ.statement_start_offset ) / 2 END
), ''
), EST.text
) AS [statement text],
EQP.query_plan
FROM task_space_usage AS TSU
INNER JOIN sys.dm_exec_requests ERQ WITH (NOLOCK)
ON TSU.session_id = ERQ.session_id
AND TSU.request_id = ERQ.request_id
OUTER APPLY sys.dm_exec_sql_text(ERQ.sql_handle) AS EST
OUTER APPLY sys.dm_exec_query_plan(ERQ.plan_handle) AS EQP
WHERE EST.text IS NOT NULL OR EQP.query_plan IS NOT NULL
ORDER BY 3 DESC;

How do I shrink all files quickly for all databases?


SSMS and right click each and choose Tasks -> Shrink,

When you do "Tasks -> Shrink" from the GUI it actually issues a DBCC
SHRINKDATABASE command behind the scenes. Try it. When the dialog box
comes up, don't click the "OK" button. Instead, click the "Script" button. You'll
see the command in a query window. Combine that with a query on
sys.databases (leave out master and msdb), and you can make a script to
shrink all of the databases.
For example (taken from jcolebrand's comment):

SELECT
'USE [' + d.name + N']' + CHAR(13) + CHAR(10)
+ 'DBCC SHRINKFILE (N''' + mf.name + N''' , 0, TRUNCATEONLY)'
+ CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
FROM
sys.master_files mf
JOIN sys.databases d
ON mf.database_id = d.database_id
WHERE d.database_id > 4;

Difference between Hash, Merge and Loop join?


SQL Server employs three types of join operations:

 Nested loops joins


 Merge joins
 Hash joins
If one join input is small (fewer than 10 rows) and the other join input is fairly
large and indexed on its join columns, an index nested loops join is the
fastest join operation because they require the least I/O and the fewest
comparisons. For more information about nested loops, see Understanding
Nested Loops Joins.

If the two join inputs are not small but are sorted on their join column (for
example, if they were obtained by scanning sorted indexes), a merge join is
the fastest join operation. If both join inputs are large and the two inputs are
of similar sizes, a merge join with prior sorting and a hash join offer similar
performance. However, hash join operations are often much faster if the two
input sizes differ significantly from each other. For more information, see
Understanding Merge Joins.

Hash joins can efficiently process large, unsorted, non indexed inputs.

What types of replication are supported in SQL Server?

SQL Server has three types of replication: Snapshot, Merge, and Transaction.
Snapshot replication creates a snapshot of the data (point-in-time picture of
the data) to deliver to the subscribers. This is a good type to use when
the data changes infrequently, there is a small amount of data to
replicate, or large changes occur over a small period of time.

Merge replication uses a snapshot to seed the replication. Changes on both


sides of the publication are tracked so the subscriber can synchronize with
the publisher when connected. A typical use for this type of replication is in a
client and server scenario. A server would act as a central repository and
multiple clients would independently update their copies of the data until
connected. At which time, they would all send up their modifications to the
central store.

Transaction replication also begins with a snapshot only this time changes
are tracked as transactions (as the name implies). Changes are replicated
from publisher to subscriber the same as they occurred on the publisher, in
the same order as they occurred, and in near real-time. This type of
replication is useful when the subscriber needs to know every change that
occurred to the data (not point-in-time), when the change volume is high, and
when the subscriber needs near real-time access to the changes.

What is DBCC?

DBCC statements are Database Console Commands and come in four flavors:

1. Maintenance

2. Informational

3. Validation

4. Miscellaneous

Maintenance commands are those commands that allow the DBA to perform
maintenance activities on the database such as shrinking a file.

Informational commands provide feedback regarding the database such as


providing information about the procedure cache. Validation commands
include commands that validate the database such as the ever-popular
CHECKDB. Finally, miscellaneous commands are those that obviously don’t fit
in the other three categories. This includes statements like DBCC HELP, which
provides the syntax for a given DBCC command.

What is the difference between Clustered and Non-


Clustered Index?

In a clustered index, the leaf level pages are the actual data pages of the
table. When a clustered index is created on a table, the data pages are
arranged accordingly based on the clustered index key. There can only be
one Clustered index on a table.

In a Non-Clustered index, the leaf level pages do not contain data pages
instead it contains pointers to the data pages. There can multiple non-
clustered indexes on a single table.

 should my PK be clustered?
 which column(s) will be the best key for my clustered index?
PK and Clustered index are 2 differences things:

 PK is a constraint. PK is used to uniquely identify rows, but there is


no notion of storage. However by default (in SSMS), it is enforced
by a unique clustered index if a clustered index is not yet present.
 Clustered indexes is a special type of index which store row data at
the leaf level, meaning it is always covering. All columns whether
they are part of the key or not, are stored at the leaf level. It does
not have to be unique, in which case a uniquifier (4 bytes) is added
to the clustered key.
Now we end up with 2 questions:

 How do I want to uniquely identify rows in my table (PK)


 How do I want to store it at the leaf level of an index (Clustered
Index)

Which types of backups are supported by SQL Write Service?

Ans:

SQL Writer supports:

 Full database backup and restore including full-text catalogs


 Differential backup and restore
 Restore with move
 Copy-only backup
 Auto-recovery of database snapshot

What is Fill Factor?

Fill Factor is a setting that is applicable to Indexes in SQL Server. The fill
factor value determines how much data is written to an index page when it is
created/rebuilt.

Where do you find the default Index fill factor and how to
change it?

The easiest way to find and change the default fill factor value is from
Management Studio, right-click the SQL Server, and choose properties. In the
Server Properties, choose Database Settings, you should see the default fill
factor value in the top section.

You can change to the desired value there and click OK to save the changes.
The other option for viewing and changing this value is using.

What are the different types of Replication and why are


they used?

There are basically 3 types of replication: Snapshot, Transactional and Merge


Replication. The type of Replication you choose depends on the requirements
and/or the goals one is trying to achieve. For example, Snapshot Replication
is useful only when the data inside the tables does not change frequently and
the amount of data is not too large, such as a monthly summary table or a
product list table, etc.

Transactional Replication would useful when maintaining a copy of a


transactional table such as sales order tables etc. Merge Replication is more
useful in the case of remote / distributed systems where the data flow can be
from multiple sites, for example, sales done at a promotional event that
might not be connected to the central servers always.

CTEs...

 Are unindexable (but can use existing indexes on referenced


objects)
 Cannot have constraints
 Are essentially disposable VIEWs
 Persist only until the next query is run
 Can be recursive
 Do not have dedicated stats (rely on stats on the underlying
objects)
#Temp Tables...

 Are real materialized tables that exist in tempdb


 Can be indexed
 Can have constraints
 Persist for the life of the current CONNECTION
 Can be referenced by other queries or subprocedures
 Have dedicated stats generated by the engine

I have a database and want to move the .mdf and .ldf files to another
location. But I do not want to stop the MSSQLSERVER service, and I do
not want to export to another server.

MDF and LDF files are protected and cannot be moved while the database is
online.

If you don't mind stop the database from working, then you can DETACH it,
move the files and then ATTACH it.

 Right click on the name of the database


 Select Properties
 Go to the Files tab
 Make a note of the Path and FileName of MDF and LDF files.
This step is important in case you don't want to end up searching
for missing files...
 Right click on the database name
 Select Tasks -> Detach
 Move the files where you want
 Right click on the Databases node of your server
 Select Attach
 Click on the Add button
 Point to the new location
 Click OK

 Set the database offline


 (I use WITH ROLLBACK IMMEDIATE to kick everyone out and rollback all
currently open transactions)
 ALTER DATABASE foo SET OFFLINE WITH ROLLBACK IMMEDIATE;

SQL server databases stuck in restoring state


We had an issue with our backup tool and now some of my databases are
stuck in restoring state!

This is likely caused by the restore script adding the WITH


NORECOVERY parameter, to make the database ready for a transaction log
apply after the restore.
The database is now waiting for the latest transaction log file.

You can either:

1. Apply the latest transaction log, using RESTORE LOG database_name


FROM backup_device WITH RECOVERY; ... or
2. Restore the database again, but this time using ... WITH
RECOVERY; ... or
3. Force the database out of restoring mode by executing: RESTORE
DATABASE YourDb WITH RECOVERY;
Before you do this, please make sure you understand the implications of
these options. You may cause data loss if you are not careful.

This will list all "most recent" restores for each database on your server:

WITH LastRestores AS
(
SELECT
DatabaseName = [d].[name] ,
[d].[create_date] ,
[d].[compatibility_level] ,
[d].[collation_name] ,
r.*,
RowNum = ROW_NUMBER() OVER (PARTITION BY d.Name ORDER BY r.[restore_date]
DESC)
FROM master.sys.databases d
LEFT OUTER JOIN msdb.dbo.[restorehistory] r ON r.[destination_database_name] =
d.Name
)
SELECT *
FROM [LastRestores]
WHERE [RowNum] = 1

SQL Server Cannot drop database <dbname>


because it is currently in use... but no sessions
displayed
When I try to drop a database I get the error "Cannot drop database
"dbname" because it is currently in use". However, when I run sp_who2, there
are definitely no sessions connected to this database. I've also set the
database to single_user mode with rollback immediate.

Make sure you don't have dependencies like database snapshots on the db
you want to remove. Though, the error message would look otherwise. Are
you sure that there is no hidden process that is connecting to your database?
A good approach would be to run a script which kills all sessions and
immediately after rename the database to another name and then drop
database.

Find out the database ID from sysdatabases.

Then execute - sp_lock that will show all the locks on the instance along with
spid and dbid.
Kill the spids with the dbid that you are trying to offline or drop.

You have been receiving alerts indicating that the disk space used by one of
your critical database servers is running out of space. How would you go
about identifying which databases and files are using the most disk space,
and what steps would you take to free up space without affecting the server
and databases operations?

 You have been tasked to troubleshoot a performance issue on one


of your databases. Users are complaining that their queries are
taking longer than usual to complete. How would you go about
identifying the root cause of the issue, and what steps would you
take to improve the database's queries performance?
 Your database server is experiencing heavy traffic and high CPU
usage, which is causing bottlenecks and slow queries. How would
you analyze the performance metrics, and what steps would you
take to optimize the server's CPU and memory usage to improve
query response time?

 Performance Monitor: This is a Windows system monitoring tool that


displays metrics with regard to key system components such as CPU,
memory, disks, and networking.
 Execution Plan: This is a useful SQL server tool, as query execution plans
can be used to establish processes that need to be fine-tuned in order for a
query to run faster.
 SQL Profiler: This tool helps you trace and troubleshoot problems in SQL
server, by, for instance, tracing and evaluating database queries.
 DMV and DMF Queries: Dynamic Management Views and Functions are
system views and functions that allow administrators to monitor the
performance of the SQL server instance, in this way diagnosing issues.
 SP_WHO2: This is a defined stored procedure that will give you information
on current users, sessions and processes in a SQL server instance.

 One of your developers has unintentionally deleted an essential


table in the database, which leads to data loss. How would you
recover the data, restore the table, and ensure the integrity and
consistency of the database after the recovery?
 You need to design and implement a database backup and recovery
plan for a mission-critical database that must be available 24/7. Can
you give an example of a situation where you had to recover a SQL
Server database after a failure?

- What was your task in the recovery process?

- What actions did you take to recover the database?

- What were the results of your actions?

1.what are the data guard protection modes?

2.components of data guard?

3.difference between logical sync and physical sync?


3.switchover methods?

4.goldengate components?

5.optach auto in rac?

6.grid upgrade in rac?

7startup sequence of rac?

8.tuning in rac?

9.what is difference between btree and bitmap?.

10.optimizer statistics?

Execution Description Progress reporting


phase granularity
DBCC TABLE The logical and physical consistency of the objects Progress reported at the
CHECK
in the database is checked during this phase. database page level.

The progress reporting


value is updated for eac
1000 database pages
that are checked.
DBCC TABLE Database repairs are performed during this phase Progress reported at the
REPAIR
if REPAIR_FAST, REPAIR_REBUILD, or REPAIR_ALLOW_DATA_LOSS is individual repair level.
specified, and there are object errors that must be
repaired. The counter is updated
for each repair that is
completed.
DBCC ALLOC Allocation structures in the database are checked Progress isn't reported
CHECK
during this phase.

Note: DBCC CHECKALLOC performs the same checks.


DBCC ALLOC Database repairs are performed during this phase Progress isn't reported.
REPAIR
if REPAIR_FAST, REPAIR_REBUILD, or REPAIR_ALLOW_DATA_LOSS is
specified, and there are allocation errors that must
be repaired.
DBCC SYS Database system tables are checked during this Progress reported at the
CHECK
phase. database page level.

The progress reporting


value is updated for
every 1000 database
Execution Description Progress reporting
phase granularity
pages that are checked
DBCC SYS Database repairs are performed during this phase Progress reported at the
REPAIR
if REPAIR_FAST, REPAIR_REBUILD, or REPAIR_ALLOW_DATA_LOSS is individual repair level.
specified, and there are system table errors that
must be repaired. The counter is updated
for each repair that is
completed.
DBCC SSB SQL Server Service Broker objects are checked Progress isn't reported.
CHECK
during this phase.

Note: This phase isn't executed when DBCC


CHECKTABLE is executed.
DBCC The consistency of database catalogs is checked Progress isn't reported.
CHECKCATALOG
during this phase.

Note: This phase isn't executed when DBCC


CHECKTABLE is executed.
DBCC IVIEW The logical consistency of any indexed views Progress reported at the
CHECK
present in the database is checked during this level of the individual
phase. database view that is
being checked.

You might also like