SQL Server Notes

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

Microsoft – SQL Server Database Administration

Information:

If we talk about particular object facts, then it is called as information.

Data:

Data is the collection of valid information/valid records.

Ex:

 Customer’s info in a bank


 Employee information in any organization
 Student information in a school/college
 Patients info in hospital

In simple words information means details/particulars of a person or object or entity


and the information pertaining to a group is called as “Data”.

Database:

A media which is used to store the data is called “Database”.

Various types of Database Management Systems:

DBMS – Database Management System

1. HDBMS – Hierarchical Database Management system


2. NDBMS – Network Database Management system Failure Products
3. RDBMS- Relational Database management system
A. SQL Server – Microsoft, Incensed
B. Oracle- Oracle Corporation, Licensed
C. Sybase – SAP, Licensed
D. MySQL – Oracle, Open source (Doesn’t require any license)
E. PostgreSQL – EDB, Open source
F. DB2 – IBM, Licensed
G. Maria DB – Open Source
H. Green plum - Open source
I. Aurora – Amazon, Licensed
4. NoSQL (Not only SQL)
 Mongo DB
 Cassandra
 Hadoop Big Data

History of SQL Server:

SQL Server was originally developed by Sybase Corporation. ANSI did not authorize this
product.

Versions:

SQL Server 1.0, SQL Server 2.0, SQL Server 3.0, SQL Server 4.0, SQL Server 5.0, SQL Server 6.0,

MS SQL Server 6.5, MS SQL Server 7.0, MS SQL Server 2000, MS SQL Server 2005,

MS SQL Server 2008, MS SQL Server 2008 R2, MS SQL Server 2012, MS SQL Server 2014,

MS SQL Server 2016, MS SQL Server 2017, MS SQL Server 2019

Service Pack Releases:

Release RTM (no SP) Latest CU


SQL Server 2019 15.0.2000.5 CU10 (15.0.4123.1, April 2021)
SQL Server latest version
SQL Server 15
codename Seattle
Support end date: 2025-01-07
Ext. end date: 2030-01-08

SQL Server 2017 14.0.1000.169 CU23 (14.0.3381.3, February 2021)


SQL Server 14
codename vNext
Support end date: 2022-10-11
Ext. end date: 2027-10-12

Starting from SQL Server 2017 Service Packs will no longer be released
SP1 SP2 SP3 SP4
SQL Server 2016 13.0.1601.5 13.0.4001.0 13.0.5026.0
SQL Server 13 or 13.1.4001.0 or 13.2.5026.0
Support end date: 2021-07-13
+ CU9 + CU15 + CU17
Ext. end date: 2026-07-14

SQL Server 2014 12.0.2000.8 12.0.4100.1 12.0.5000.0 12.0.6024.0


SQL Server 12 or 12.1.4100.1 or 12.2.5000.0 or 12.3.6024.0
Support end date: 2019-07-09
+ CU14 + CU13 + CU18 + CU4
Ext. end date: 2024-07-09

SQL Server 2012 11.0.2100.60 11.0.3000.0 11.0.5058.0 11.0.6020.0 11.0.7001.0


SQL Server 11 or 11.1.3000.0 or 11.2.5058.0 or 11.3.6020.0 or 11.4.7001.0
codename Denali
+ CU11 + CU16 + CU16 + CU10
Support end date: 2017-07-11
Ext. end date: 2022-07-12

Obsolete versions – out of support


SQL Server 2008 R2 10.50.1600.1 10.50.2500.0 10.50.4000.0 10.50.6000.34
SQL Server 10.5 or 10.51.2500.0 or 10.52.4000.0 or 10.53.6000.34
codename Kilimanjaro
Support end date: 2014-07-08
Ext. end date: 2019-07-09

SQL Server 2008 10.0.1600.22 10.0.2531.0 10.0.4000.0 10.0.5500.0 10.0.6000.29


SQL Server 10 or 10.1.2531.0 or 10.2.4000.0 or 10.3.5500.0 or 10.4.6000.29
codename Katmai
Support end date: 2014-07-08
Ext. end date: 2019-07-09

SQL Server 2005 9.0.1399.06 9.0.2047 9.0.3042 9.0.4035 9.0.5000


SQL Server 9
codename Yukon
Support end date: 2011-04-12
Ext. end date: 2016-04-12

SQL Server 2000 8.0.194 8.0.384 8.0.532 8.0.760 8.0.2039


SQL Server 8
codename Sh .+++++++iloh
Support end date: 2008-04-08
Ext. end date: 2013-04-09

SQL Server 7.0 7.0.623 7.0.699 7.0.842 7.0.961 7.0.1063


SQL Server 7
codename Sphinx
Support end date: 2005-12-31
Ext. end date: 2011-01-11

SQL Server 6.5 6.50.201 6.50.213 6.50.240 6.50.258 SP4 6.50.281


SQL Server 6.50 SP5 6.50.416
codename Hydra
Support end date: 2002-01-01

SQL Server 6.0 6.00.121 6.00.124 6.00.139 6.00.15


SQL Server 6
codename SQL95
Support end date: 1999-03-31

CTP Community Technology Preview (beta release)


RC Release Candidate
RTM Released To Manufacturing; It is the original, released build version of the product,
i.e. what you get on the DVD or when you download the ISO file from MSDN.
CU Cumulative Update; Cumulative updates contain the bug fixes and enhancements–
up to that point in time–that have been added since the previous Service Pack
release and will be contained in the next service pack release. Installation of the
Cumulative Update is similar to the installation of a Service Pack. Cumulative
Updates are not fully regression tested.
* Since January 27, 2016: Microsoft recommends ongoing, proactive installation of
SQL Server CUs as they become available. SQL Server CUs are certified to the
same levels as Service Packs, and should be installed with the same level of
confidence.
SP Service Pack; much larger collection of hotfixes that have been fully regression
tested. In some cases delivers product enhancements. All SQLServer service
packs are cumulative, meaning that each new service pack contains all the fixes
that are included with previous service packs and any new fixes.
* Service Packs are discontinued starting from SQL Server 2017. Only Cumulative
Updates (CUs) will be provided.
GDR General Distribution Release; GDR fixes should not contain any of the CU updates.
QFE Quick Fix Engineering; QFE updates include CU fixes.
CVE Common Vulnerabilities and Exposures; publicly known information-security
vulnerabilities.
OD On-Demand hotfix. An OD is released per customer request for specific problem
scenarios to that customer. OD hotfixes may or may not be released to the general
public.
COD Critical On-Demand hotfix. A COD hotfix is defined as critical because security is
impacted a severe stability or functionality is detected.

 Starting from SQL Server 2017 Service Packs will no longer be released
 In real time it is recommended to practice n-1 version, i.e., 1 version earlier to the latest
version.
 15.0.2000.5 is called as ‘build number’.
 RTM (Release to Manufacturing) is the actual base version released into the market
which we can use.
 Before RTM is released, Beta versions/Community Technology Preview (CTP) are
released into the market which shows what update is done in this release when
compared to the previous version.
 In between the Beta release and the RTM we have a Release Candidate (RC) which
means the version is ready and can be released into the market anytime.
 Cumulative Updates (CU) contains the bug fixes and enhancements upto that point of
time. CU’s are not fully regression tested. Cu’s are released in between 1 service pack to
another service pack.
 Service Pack (SP) contains larger collection of bug fixes and is released over a longer
period of time (say once in 6 months or 9 months or a year). SP’s are fully regression
tested. SP’s are discontinued starting from SQL Server 2017.

SQL Server Editions: (For each version)

Enterprise:

Top edition with all the enterprise feature of SQL server. It has to be purchased. Can be
used for production use.

Standard:

The cut down edition. We may not have some enterprise features. It has to be
purchased. Cost is much less compared to Enterprise edition. Can be used for the production
use.

Developer:
It is a fully functional enterprise edition of SQL Server licensed for use as development
and test database in non-production environment. Can be downloaded. In simple we can say
this is for learning process.

Express:

Basic edition of SQL server. Can be used for production with limitations. Can be
downloaded.

Free editions

Express Express edition is a free lightweight/lite edition of SQL Server with some limitations,
that can be used in production environment.
Main limitations:
• Limited to lesser of 1 physical CPU or 4 cores.
• No single database (.MDF file) can be over 10 GB.

Developer Developer edition is a fully-functional Enterprise Edition of SQL Server, licensed for
use as a development and test database in a non-production environment. Download
SQL2019 Developer Edition Download SQL2017 Developer Edition

Evaluation Evaluation edition is a fully-functional trial Enterprise Edition of SQL Server but is
limited to 180 days, after which the tools will continue to run, but the server services
will stop.

Paid editions

Enterprise Enterprise edition is the top-end edition with a full feature set.

Standard Standard edition has less features than Enterprise, when there is no requirement of
advanced features.

Cost:

Editions Open no level price (US$)

Enterprise $13, 748[1]


Standard - per core $3,586[1]
Standard - server $899[1]
Standard - CAL $209
Developer Free
Web See your hosting partner for pricing
Express Free
Installation:
 To check the version that is installed – select @@version. This command shows the
build number.
 We have 2 types of instances. They are “Default instance” and “Named instance”.
 Instance is a SQL Server installation.
 In each installation we have only 1 Default instance and can have as many as 49 Named
instances across all the versions.
 When we select ‘Default’ instance then the SQL Server will select the windows machine
name itself as the SQL Server Default instance name.
 When we select ‘Named’ instance then we can give any name as per the business
requirements.
 We can check the entire information of the laptop using ‘msinfo32’ command.

Authentication Modes:

 At the time of installation after selecting the instance type, need to set the
authentication mode.
 We have 2 types of authentication modes. They are “Windows” and “Mixed mode”.
 Mixed authentication mode consists of both ‘Windows’ and ‘SQL’ mode.
 If we configure the SQL Server in ‘Windows’ authentication then we can grant access
only to the windows user accounts.
 If we configure the SQL Server in ‘Mixed’ authentication mode then we can grant access
to windows and non-windows user accounts/SQL accounts as well.
 If we configure the SQL Server in ‘Mixed’ authentication mode then by default SQL
admin account is created by name “sa” for which we need to set the password.
 If the installation is done is “Windows” mode and want to change to “Mixed” mode
post installation then we do have an option to do the same.
 We can change only the authentication modes after installation but not the Default or
Named instances.

Login Options:

 SQL Server Management Studio (SSMS) is the tool used to connect the SQL Server after
installation and helps to perform any database administration and development
activities.
 SQL Server Configuration Manager (SSCM) is the tool used to find out the list of SQL
servers services installed on a particular machine/server along with the status.
 SSCM can be opened through command prompt by using the command
“sqlservermanager15.msc”.
 In SSCM the default SQL Server instance will be shown by the name “MSSQLSERVER”
and the named SQL Server instance will be shown by the instance name.
Windows Authentication Mode:

 To login into SQL Server using windows authentication mode we can give the server
name as “machine name” or “.” or “local”.
 We can login into any SQL Server instance installed on the machine by giving the server
name as the machine name along with the server instance name or “.instance name” or
“local instance name”.

SQL Server Authentication Mode:

 To login into SQL Server using SQL Server authentication mode we can give the server
name as “machine name” and login as “sa” and the password as the one that we set at
the time of installation.
 We can login into any SQL Server instance installed on the machine by giving the server
name as the machine name along with the server instance name and login as “sa” and
the password as the one that we set at the time of installation.

How to reset SA password:


 If we forgot the sa password for any named instance then it can be reset as given below.
 After logging into the instance from windows authentication mode, select the login tab
under security and select the sa account and reset the password.

Start/Stop/Restart SQL Server:

1. Configuration Manager:
 Run  sqlservermanager15.msc  SQL Server services  Right click on SQL Server
service  Start/Stop/Restart

2. Services.msc:

 Run  services.msc  Right click on SQL Server service  Start/Stop/Restart


3. SSMS:

 Right click on SQL Server service  Start/Stop/Restart


 Not a best practice.

4. Command Prompt:

 Open command prompt as administrator.


Default:

Cmd  NET START <Default Server Name>

Cmd  NET STOP <Default Server Name>

Named Instance:

Cmd  NET START MSSQL$<Named Instance Name>

Cmd  NET STOP MSSQL$<Named Instance Name>

5. Power Shell:

 Open power shell as administrator.


Default:

 Power Shell  start-service -Name <Default Server Name>


 Power Shell  stop-service -Name <Default Server Name>

Named Instance:

 Power Shell  start-service -Name ‘mssql $<Named Instance Name>’


 Power Shell  stop-service -Name ‘mssql $<Named Instance Name>’

Changing the Authentication Mode:


Option 1: From SSMS
 Right click on SQL Server instance  Properties  Security  Server Authentication 
Change Authentication  Click Ok

 Whenever any changes are made to SQL Server configuration, to apply and incorporate
those changes the SQL Server has to be restarted.
Option 2: From System Registry

 Run  Regedit  Local Machine  Sotware  Change Authentication  Click Ok


Login Mode:

1 - Windows Authentication Mode

2 - Mixed Authentication Mode

 If the value is changed from 1 to 2 it becomes Mixed authentication and from 2 to 1 it


becomes Windows authentication.
 Restart the SQL Server.

Install Latest CU for SQL Server 2019:

 To check the version that is installed – select @@version. This command shows the
build number.
 To check the server – select @@servername.

 To check the server – select @@servername for Named Instance.

 Run the setup file.


 Select the required MS SQL Server version for which the CU is to be installed from the
list of all the versions available on the machine and then proceed.

Database:

 There are 2 types of databases. They are “System database” and “User database”.
 System database again have 4 types of databases by names “Master DB”, “Model DB”,
“Msdb DB”, “Temp DB”.
 System database gets created at the time of installation of SQL Server.
 User database is created as per the business requirements.
 Any database consist of 2 files namely “Data file” and “Log file”.
 The extension of data file is “mdf/ndf” and log file is “ldf”.

How to change the default location of the Databases:

Right Click on the instance name  Properties  Database Settings  Change it to new path
 Restart SQL Service
Development Basics:

SQL:

 SQL Server is a RDBMS product with which we can store, retrieve, manipulate and
delete the data.
 To perform these activities we need a language which is SQL (Structured Query
Language).

What Can SQL do?

 SQL can execute queries against a database


 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

Data Types:

 The data type of a column defines what value the column can hold.
 Each column in a database table is required to have a name and a data type.
 Various data types are as follows: INT, Char, Varchar, Money, Date, Datetime, binary,
Float etc.,

Constraints:

 SQL constraints are used to specify rules for data in a table.


 Constraints can be specified when the table is created with the CREATE TABLE statement,
or after the table is created with the ALTER TABLE statement.
 In simple constraint is a condition provided to use the table as per our requirements.

Ex: CREATE TABLE table_name (column1 datatype constraint, column2 datatype


constraint, column3 datatype constraint, …….)
 Various constraints that we have are as follows:

 NOT NULL: Ensures that a column cannot have a NULL value.


 UNIQUE: Ensures that all values in a column are different. It doesn’t allow
duplicate values. It accepts 1 null value.
 PRIMARY KEY: A combination of a NOT NULL and UNIQUE. We can have only 1
primary key in a table.
 FOREIGN KEY: Prevents actions that would destroy links between tables. It is a
field or collection of fields in one table, that refers to Primary key in another
table.
 CHECK: Ensures that the value in a column satisfies a specific condition or exists
within a particular range.
 DEFAULT: Sets a default value for a column if no value is specified.
 CREATE INDEX: Used to create and retrieve data from the database very quickly.
 IDENTITY: When we have an integer column with fixed incremental values.

SQL Languages:

 Divided into 5 categories as follows:


 DDL – Data Definition Language
 CREATE
 ALTER
 DROP
 TRUNCATE
 DML – Data Manipulation Language
 INSERT
 UPDATE
 DELETE
 MERGE
 DQL – Data Query Language
 SELECT
 DCL – Data Control Language
 GRANT
 REVOKE
 WITH GRANT
 TCL – Transaction Control Language
 COMMIT
 ROLLBACK

Delete Truncate Drop


Deletes the data conditionally
No option to delete the data
selectively
Deletes the data, but table Deletes the data, but table Deletes the data along with
remains same remains same the table
DML operation DDL operation DDL operation
Delete is logged operation Truncate is non-logged
operation
Deleted data can be Truncated data cannot be
rollbacked rollbacked

Creation of Database:

Using GUI:

Databases  Right Click  New Database  Database Name  OK

Using Query:

CREATE DATABASE DATABASE_NAME

Note: Whenever the database name includes “_”, “-“, “ “, then place the database name in
square brackets ([]).

To Add another Datafile:

ALTER DATABASE DATABASE_NAME

ADD FILE

(NAME=’FILE NAME’, FILENAME=’LOCATION:\FILE NAME.NDF’)

To Delete a Datafile:

ALTER DATABASE DATABASE_NAME

REMOVE FILE [FILE NAME]

To Drop a Database:

DROP DATABASE DATABASE_NAME

Creating a Table:

Using GUI:

Tables  Right Click  New  Table  Column Name  Data Type Save  Table Name

Using Query:

CREATE TABLE TABLE_NAME (COL NAME1 DATATYPE, COL NAME1 DATATYPE……)


To Drop a Table:

DROP TABLE TABLE_NAME

To Add a Column to a Table:

ALTER TABLE TABLE_NAME

ADD COL NAME1 DATATYPE, COL NAME2 DATATYPE

To Drop a Column from the Table:

ALTER TABLE TABLE_NAME

DROP COLUMN COL NAME

To Insert data into the Table:

INSERT INTO TABLE_NAME VALUES (‘AAA’, ‘BBB’, ‘CCC’, ‘DDD’,…….)

OR

INSERT INTO TABLE_NAME (COL1, COL2, COL3,…) VALUES (‘AAA’, ‘BBB’, ‘CCC’,…….)

To Check data inserted in the Table:

SELECT * FROM TABLE_NAME

Demo:
CREATE DATABASE [DEV-BASICS]
use [DEV-BASICS]
go
create table emp1
(ID int, name varchar(50))

CREATE TABLE [dbo].[emp2](


[ID] [int] NULL,
[name] [varchar](50) NULL
)
drop table [dbo].[emp2]
alter table [dbo].[EMP]
add loc varchar(50)
alter table [dbo].[EMP]
drop column loc

CREATE TABLE Persons (


PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
ALTER TABLE Persons
drop column DateOfBirth;

insert into Persons values


(1,'warner','david','aus','melbourne')

insert into Persons values


(2,'kane','williamon','NZ','wlgton'),
(3,'pat','cummins','Aus','sydney'),
(4,'andrew','Russel','WI','madison')

insert into Persons values


(1,'Steve','smith','NZ','wlgton'),
(1,'narine','sunil','wi','sydney'),
(1,'khan','rasheed','agf','madison')

insert into Persons values


(1,'Steve','smith','NZ')

insert into Persons


(PersonID,LastName,FirstName,Address)
values
(1,'Steve','smith','NZ')
drop table Persons1
CREATE TABLE Persons1 (
PersonID int primary key,
LastName varchar(255) not null,
FirstName varchar(255) not null,
Address varchar(255) not null,
City varchar(255) not null
);

insert into Persons1


(LastName,FirstName,Address,City)
values
('Steve','smith','NZ', 'mandid')

insert into Persons1


(PersonID,LastName,FirstName,Address,City)
values
(2,'Steve','smith','NZ', 'mandid')

select * from Persons1

CREATE TABLE Persons_all (


SNO int identity (1,1),
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255)not null,
Age int check (age>=18 and age <=35),
location varchar(50) default 'Hyderabad'
);
insert into Persons_all
(ID,LastName,FirstName,Age)
values
(1,'henson','mike',22),
(2,'kelway', 'greg',19),
(3,'coffey', 'Niel',25),
(4,'Chupkey', 'Denise',19),
(5,'Winter', 'Bob',35)

select * from Persons_all

select * from Persons_all


update Persons_all
set age=23 where id=2
delete from Persons_all
where id=5

truncate table Persons_all


delete from Persons_all
drop table Persons_all

Foreign Key Demo:

create table dept


(DeptID int primary key,
Dname varchar (50),
Dhead varchar(50))

insert into dept values


(101, 'IT', 'Mike'),
(102, 'ac', 'elizabeth'),
(103, 'finance', 'nancy'),
(104, 'hr', 'chris')

create table employee


(empid int primary key,
Ename varchar (50),
sal int,
location varchar(50) default 'hyderabad',
DeptID int FOREIGN KEY REFERENCES Dept(deptid) )

insert into employee


(empid,Ename,sal,DeptID)
values
(2,'cummin',10000,101),
(3,'jampa',10000,101),
(4,'curran',10000,102),
(5,'sam',10000,103)
select * from employee

How to import sample database:

Databases  Right Click  Restore Databases  Devices  Browse the file location  OK
*******backup table data

select * into
[dbo].[Persons_bkp030521]
from [dbo].[Persons]

truncate table [dbo].[Persons]

insert into [dbo].[Persons]


select * from
[dbo].[Persons_bkp030521]

SQL Dev practice:

select * from
[Sales].[SalesOrderDetail]

select SalesOrderID,OrderQty
from
[Sales].[SalesOrderDetail]

select * from
[Sales].[SalesOrderDetail]
where SalesOrderID=43659

select * from
[Sales].[SalesOrderDetail]
where SalesOrderID<>43659

select * from
[Sales].[SalesOrderDetail]
where SalesOrderID in
(43659,43660,43661)

select * from
[Sales].[SalesOrderDetail]
where SalesOrderID not in
(43659,43660,43661

select * from
[Sales].[SalesOrderDetail]
where SalesOrderID in
(43659,43660,43661) and OrderQty>5

select * from
[Sales].[SalesOrderDetail]
where SalesOrderID in
(43659,43660,43661) or OrderQty>5

select distinct SalesOrderID from


[Sales].[SalesOrderDetail]
select * from
[Sales].[SalesOrderDetail]
order by OrderQty desc

select * from
[Sales].[SalesOrderDetail]
order by OrderQty asc

select * from
[Sales].[SalesOrderDetail]
order by UnitPrice asc

select top 100 SalesOrderID from


[Sales].[SalesOrderDetail]
order by SalesOrderID asc

select SalesOrderID, min(orderqty) from


[Sales].[SalesOrderDetail]
group by SalesOrderID

select SalesOrderID, max(orderqty) from


[Sales].[SalesOrderDetail]
group by SalesOrderID

select SalesOrderID, sum(orderqty) from


[Sales].[SalesOrderDetail]
group by SalesOrderID

select SalesOrderID,
sum(orderqty)as totalqty
from
[Sales].[SalesOrderDetail]
group by SalesOrderID
having sum(orderqty) >30

select count(*) from


[Sales].[SalesOrderDetail]
--group by SalesOrderID

select * from
[HumanResources].[Department]
where name like '%ces'

select * from
[HumanResources].[Department]
where name like 's%'

select * from
[HumanResources].[Department]
where name like '%sa%'

select * from
[HumanResources].[Department]
where name like '_a%'
select * from
[Sales].[SalesOrderDetail]
where OrderQty between 5 and 10

SQL Server Connectivity:

Local Server:

1. Using SSMS
2. Using configuration Manager
3. Using SQLCMD

SQLCMD:

C:\WINDOWS\system32>hostname
DESKTOP-IA0FMAF

C:\WINDOWS\system32>SQLCMD -S DESKTOP-IA0FMAF
1> use
2> [dev-basics]
3> go
Changed database context to 'DEV-BASICS'.
1> select * from [dbo].[dept]
2> go
DeptID Dname
Dhead
-----------
-------------------------------------------------
-
-------------------------------------------------
-
101 IT
Mike
102 ac
elizabeth
103 finance
nancy
104 hr
chris

(4 rows affected)
1>
How to setup SQL Server connectivity from the application:

 The default port number for SQL Server is 1433.


 To set up the remote connectivity, TCP/IP must be in enabled state.
 The default port number can be checked as follows:
 Configuration manager  SQL Server Network Configurations  Select protocols for
SQL Server  instance name  right click and go to TCP/IP properties  IP Addresses
 TCP Port.
 For security reasons the default port number can be changed by going to the above
location and renaming the default port number.
 The range for setting up the port number is 49152-65535.
 For named instances we have TCP Dynamic port number which is assigned dynamically.
 The Dynamic port number assigned for named instances should be made static.
 To convert the dynamic port number to static remove the number in-front of the
dynamic port and assign the same number to TCP Port below it and remove all the
zero’s in-front of the TCP Dynamic ports.
Dedicated Administrator Connection (DAC) Port SQL Server:

 This is used to connect the SQL Server in admin mode to trouble shoot connectivity
issues.
 The default port for DAC is 1434.

To connect Dedicated Administrator Connection (DAC) using SQLCMD:

 To check the system ip use “ipconfig” in command prompt.



Ping:

C:\WINDOWS\system32>ping 192.168.100.9

Pinging 192.168.100.9 with 32 bytes of data:

Reply from 192.168.100.9: bytes=32 time<1ms TTL=128

Reply from 192.168.100.9: bytes=32 time<1ms TTL=128

Reply from 192.168.100.9: bytes=32 time<1ms TTL=128

Reply from 192.168.100.9: bytes=32 time<1ms TTL=128


Ping statistics for 192.168.100.9:

Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

Approximate round trip times in milli-seconds:

Minimum = 0ms, Maximum = 0ms, Average = 0ms

Telnet:

C:\WINDOWS\system32>telnet 191.168.100.9 1433

Connecting To 191.168.100.9...Could not open connection to the host, on port 1433:


Connect failed

The firewall Is blocking the connecting coming, we need open a firewall rule to allow the
inbound connection to the port : 1433

Telnet successful:

C:\WINDOWS\system32>telnet 192.168.100.9 1433

Connecting To 192.168.100.9...Could not open connection to the host, on port 1433:


Connect failed

C:\WINDOWS\system32>telnet 192.168.100.9,1433

Connecting To 192.168.100.9,1433...Could not open connection to the host, on port 23:


Connect failed
C:\WINDOWS\system32>telnet 192.168.100.9 1433

Connecting To 192.168.100.9...Could not open connection to the host, on port 1433:


Connect failed

UDL Test:

In a remote server from where we are connecting to the SQL Server:

1. Create a file with name UDLTest.txt


2. Rename the file by removing txt .. add UDL (UDLTest.UDL)
3. Double click on the UDL file name
Configurtion Changes:

sp_configure
go

name minimum maximum config_value run_value


allow polybase export 0 1 0 0
allow updates 0 1 0 0
backup checksum default 0 1 0 0
backup compression default 0 1 0 0
clr enabled 0 1 0 0
column encryption enclave type 0 2 0 0
contained database authentication 0 1 0 0
cross db ownership chaining 0 1 0 0
default language 0 9999 0 0
external scripts enabled 0 1 0 0
filestream access level 0 2 0 0
hadoop connectivity 0 7 0 0
max text repl size (B) -1 2147483647 65536 65536
nested triggers 0 1 1 1
polybase enabled 0 1 0 0
polybase network encryption 0 1 1 1
remote access 0 1 1 1
remote admin connections 0 1 1 1
remote data archive 0 1 0 0
remote login timeout (s) 0 2147483647 10 10
remote proc trans 0 1 0 0
remote query timeout (s) 0 2147483647 600 600
server trigger recursion 0 1 1 1
show advanced options 0 1 0 0
user options 0 32767 0 0

sp_configure 'show advanced options', 1


go
reconfigure
go
sp_configure
go

name minimum maximum config_value run_value


access check cache bucket count 0 65536 0 0
access check cache quota 0 2147483647 0 0
Ad Hoc Distributed Queries 0 1 0 0
ADR cleaner retry timeout (min) 0 32767 0 0
ADR Preallocation Factor 0 32767 0 0
affinity I/O mask -2147483648 2147483647 0 0
affinity mask -2147483648 2147483647 0 0
affinity64 I/O mask -2147483648 2147483647 0 0
affinity64 mask -2147483648 2147483647 0 0
Agent XPs 0 1 1 1
allow filesystem enumeration 0 1 1 1
allow polybase export 0 1 0 0
allow updates 0 1 0 0
automatic soft-NUMA disabled 0 1 0 0
backup checksum default 0 1 0 0
backup compression default 0 1 0 0
blocked process threshold (s) 0 86400 0 0
c2 audit mode 0 1 0 0
clr enabled 0 1 0 0
clr strict security 0 1 1 1
column encryption enclave type 0 2 0 0
common criteria compliance enabled 0 1 0 0
contained database authentication 0 1 0 0
cost threshold for parallelism 0 32767 5 5
cross db ownership chaining 0 1 0 0
cursor threshold -1 2147483647 -1 -1
Database Mail XPs 0 1 0 0
default full-text language 0 2147483647 1033 1033
default language 0 9999 0 0
default trace enabled 0 1 1 1
disallow results from triggers 0 1 0 0
EKM provider enabled 0 1 0 0
external scripts enabled 0 1 0 0
filestream access level 0 2 0 0
fill factor (%) 0 100 0 0
ft crawl bandwidth (max) 0 32767 100 100
ft crawl bandwidth (min) 0 32767 0 0
ft notify bandwidth (max) 0 32767 100 100
ft notify bandwidth (min) 0 32767 0 0
hadoop connectivity 0 7 0 0
index create memory (KB) 704 2147483647 0 0
in-doubt xact resolution 0 2 0 0
lightweight pooling 0 1 0 0
locks 5000 2147483647 0 0
max degree of parallelism 0 32767 4 4
max full-text crawl range 0 256 4 4
max server memory (MB) 128 2147483647 1024 1024
max text repl size (B) -1 2147483647 65536 65536
max worker threads 128 65535 0 0
media retention 0 365 0 0
min memory per query (KB) 512 2147483647 1024 1024
min server memory (MB) 0 2147483647 0 16
nested triggers 0 1 1 1
network packet size (B) 512 32767 4096 4096
Ole Automation Procedures 0 1 0 0
open objects 0 2147483647 0 0
optimize for ad hoc workloads 0 1 0 0
PH timeout (s) 1 3600 60 60
polybase enabled 0 1 0 0
polybase network encryption 0 1 1 1
precompute rank 0 1 0 0
priority boost 0 1 0 0
query governor cost limit 0 2147483647 0 0
query wait (s) -1 2147483647 -1 -1
recovery interval (min) 0 32767 0 0
remote access 0 1 1 1
remote admin connections 0 1 1 1
remote data archive 0 1 0 0
remote login timeout (s) 0 2147483647 10 10
remote proc trans 0 1 0 0
remote query timeout (s) 0 2147483647 600 600
Replication XPs 0 1 0 0
scan for startup procs 0 1 0 0
server trigger recursion 0 1 1 1
set working set size 0 1 0 0
show advanced options 0 1 1 1
SMO and DMO XPs 0 1 1 1
tempdb metadata memory-optimized 0 1 0 0
transform noise words 0 1 0 0
two digit year cutoff 1753 9999 2049 2049
user connections 0 32767 0 0
user options 0 32767 0 0
version high part of SQL Server -2147483648 2147483647 0 0
version low part of SQL Server -2147483648 2147483647 0 0
xp_cmdshell 0 1 0 0

sp_configure 'remote admin connections', 1;


go
reconfigure
go

--Turn off the advanced option

sp_configure 'show advanced options', 0


go
reconfigure
go

Databases:

There are 2 types of databases. They are

1. System Database
2. User Database

User Database:

 These are created as per the business requirements.


 Can create ‘n’ number of databases.
 These databases are created as per the request of the application team.
 Once the installation is completed the database admin shares the SQL Server details like
instance name, port number, credentials (with create database permission).
 When they run their application installation.. they will give the SQL server detail in the
connection parameter and application will connect to the SQL server and creates all the
corresponding databases required.
 Ex: SCOM Installation.
System Databases:

 These databases that gets created along with SQL server installation.
 System databases maintain all the system level information.
 These databases should not be used for storing user/business data.

Types of System Databases:

 Master
 Model
 Msdb
 Tempdb
 Resource
 Distribution
Master Database:

 This is the master of all the databases in SQL server.


 It maintains all the system level information such as logins, linked servers, end point,
and information about all other databases in that SQL server (metadata).
 Maintains all the SQL server sessions/connection information.
 Without Master Database the SQL Server doesn’t work.
 All the login’s information is stored in the master DB under master  Views  System
Views  Sys.syslogins.
 All the login information can be viewed by using the query as follows.
 SELECT * FROM [sys].[syslogins] (OR) SELECT NAME FROM [sys].[syslogins]

Linked Servers:

 To access the databases present in one instance/Server from other instances/Servers,


we need to create the link between the instances/servers.
 Server  Server Objects  Linked Servers  New Linked Server  name of the
instance to which we want to connect  Security tab  Be made using the login’s
current security context  OK.
 This connection is a readonly. We can only retrieve the data but cannot modify it.
 All the linked servers information can be viewed by using the query as follows.
 SELECT * FROM [sys].[sysservers]

Information About Other Databases:

 To check all the databases information the following query can be used.
 SELECT * FROM [sys].[databases]
 To know the information or data about the files (mdf/ndf/ldf) then the following query
can be used.
 SELECT * FROM [sys].[master_files]

 To know the information of all the databases and their data files at a time, we can use
the following query using joins.
 select
sd.name,
sd.create_date,
smf.name,
smf.physical_name
from sys.databases sd
join sys.master_files smf
on sd.database_id=smf.database_id
Open Sessions, Connections… etc.,:

 To check the information about the open sessions at that point of time.

select * from sys.dm_exec_requests

 The session id’s 1 to 50 are reserved for system processes and whenever we open a new
query tab that id will be reflected in the session id tab.
 To check the information about the connections at that point of time.

select * from sys.dm_exec_connections

 To check the information about the sessions.

select * from sys.dm_exec_sessions


Model Database:

 Model is a template database in SQL server.


 Whenever we create a new user database or tempdb, this will inherit all the properties
from model database and will assign it to the user database.
 For example if we set recovery model as ‘simple’ for model database then whatever the
new user databases that we create will get same ‘simple’ recovery model.
 Without model database the SQL Server will not work as it requires template for
creating tempdb at the time SQL Server start process.
 Whenever model database is not available, it will not be able to create a tempdb.

MSDB Database:

 MSDB is meant for SQL Server agent.


 It maintains all the SQL Server agent related information such as job, schedules, alerts,
operator and steps.
 It maintains backup and restore history.
 It maintains log shipping configuration details also.
 Without MSDB, SQL server will work but the agent will not work.

SQL Server agent Service:

 For every SQL Server database engine that we install, a corresponding agent service will
be installed.
Purpose of Agent:

 To automate any activities like maintenance, backups, or any application jobs SQL Server
agent service is used.
 By using the agent we can create jobs and automate them as per schedule.

TEMP Database:

 It is a temporary database in SQL server, which maintains intermittent results of the


transaction temporarily.

Table: dept
Insert into #tempdept
Select * from dept where deptname=’ac’
Loop through #tempdept, and update the salary and delete #tempdept

A=10
B=15
C=a+b=25
D=a+c=35
Total=a+b+c+d

 Local temp tables #: span Is limited to a particular session where it is created.


 Global Temp tables ##: span is global, can be accessible from other sessions also.
 Whenever we restart SQL server, a new tempdb will be created.
 Without TempDb, SQL server will work because whenever we start the SQL server, it will
delete exiting tempdb and recreates the new one.

Different ways to find the database locations:

1. GUI

 Right click on the database propertiesfiles


2. sp_help

3. Sys.master_files, Sys.sysaltfiles
Startup Parameters:

Configuration Manager  Right click on instance name  Properties  Startup Parameters


-d: master database data file (mdf) location

-d F:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\master.mdf

-e: error log location

-e F:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\Log\ERRORLOG

-l: master database log file (ldf) location

-l F:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\mastlog.ldf

SQL Server Restart Process:

 It reads the startup parameters and will go to the corresponding location and checks
whether the corresponding files are available or not.
 As master is maintaining locations of all other databases, it will bring all other databases
online one by one.

Error log:

 This is file where SQL server logs/writes all the messages like errors, warnings,
informational messages, etc.
 This is our first focus point to troubleshoot any SQL server related issues.
 The location of error logs can be found by ‘e’ value available in startup parameters.

Different ways to check error log:

SSMS:
Under SQL instancemanagement SQL server logs
 The default error log count is 1 current and 6 archives (old files).
 The default error log count can be changed in between 6 to 99.
 The default error log count can be changed as follows:
 Right click on the SQL Server logs configure  change the default error log count
 Once the error log count is changed, new error log archives are generated each time
when we restart the SQL Server.
Error Log Recycling Process:

 In order to generate the error logs automatically, we can execute the following stored
procedure.
 sp_cycle_errorlog

To Automate Error Log Recycling:

 Create a job and add above stored procedure.

2. SSMS- script:

 To check and read the data from the error log the following stored procedure can be
used.
 sp_readerrorlog
 To check and read the data from a particular error log the stored procedure can be used
along with 2 parameters as follows.
 1st parameter is file number
 2nd parameter is file type
 There are two types of error log file types. They are ‘SQL Server Error Logs’ and ‘SQL
Server Agent Error Logs’.
 The SQL Server Error Log file type is denoted by ‘1’ and the SQL Server Agent Error Log
by ‘2’.

 Hence to read a particular error log, the stored procedure can be used as follows.
 sp_readerrorlog 0,1
 ‘0’ represents current error log and ‘1’ represents SQL Server Error Logs.
 When we want to search or read an error log with a specific pattern then the above
stored procedure can be used as follows.
 sp_readerrorlog 0,1, ‘error’, ‘been’
 For the above stored procedure the result will be displayed with the sentences which
contain error and been words.
 The current version stored procedure accepts only 2 parameters whereas the previous
version used to accept 4 parameters as follows.
 Even though sp_readerrolog accepts only 4 parameters, the extended stored procedure
accepts at least 7 parameters.
 If this extended stored procedure is called directly the parameters are as follows:
 Value of error log file you want to read: 0 = current, 1 = Archive #1, 2 = Archive #2, etc...
 Log file type: 1 or NULL = error log, 2 = SQL Agent log
 Search string 1: String one you want to search for
 Search string 2: String two you want to search for to further refine the results
 Search from start time
 Search to end time
 Sort order for results: N'asc' = ascending, N'desc' = descending

EXEC master.dbo.xp_readerrorlog 0, 1, '2005', 'exec', NULL, NULL, N'desc'


EXEC master.dbo.xp_readerrorlog 0, 1, '2005', 'exec', NULL, NULL, N'asc'

3. Startup parameters (-e value):

 -e in startup parameters gives the physical location of error log


What Error Log Contains:

 SQL server information like version, edition, OS ..etc

 Time zone information, hardware information and authentication

 Logging path

 Reads the startup parameters


 No of cores, physical memory, port information

 Start the master database

 Ports information

Got an issue Saying SQL server is not accessible:

 As a DBA, we need to try connecting to the SQL server from “SSMS”.


 If it works, then there is no issue with the SQL server.
 Other reason may be their access related or network related issue.
 Even we are not able to connect SQL server
 Check the SQL server status (running/not)
 If it is not running, try starting the SQL server
 If it comes online, issue fixed
 If it is not starting, then
o Verify error log

Why do we need to move the system databases?

 When we install SQL server, the system databases will be created by default in C- Drive.
 The C-Drive is OS drive and is dedicated for OS.
 If we keep any of our databases (system/user) and if something goes wrong with
operating system, then we may lose our SQL server databases also.
 Considering that it is not a best practice to keep any of the application data in OS drive.

Moving System Databases:

Model:

--step1: identify the current location of model database

use model
go
sp_helpfile

--Step2: modify the system catalogue with new path


alter database model modify file
(name='modeldev', filename='F:\system_dbs\model.mdf')
alter database model modify file
(name='modellog', filename='F:\system_dbs\modellog.ldf')

--step3: stop the SQL Server

--Step4: copy the files from old to new location

--Step5: start SQL Server

--Step6: verify the new location

use model
go
sp_helpfile

MSDB:

--step1: identify the current location of msdb database

use msdb
go
sp_helpfile

--Step2: modify the system catalogue with new path

alter database msdb modify file


(name='MSDBData', filename='F:\system_dbs\MSDBData.mdf')
alter database msdb modify file
(name='MSDBLog', filename='F:\system_dbs\MSDBLog.ldf')

--step3: stop the SQL Server

--Step4: copy the files from old to new location

--Step5: start SQL Server

--Step6: verify the new location

use msdb
go
sp_helpfile

Tempdb:
--step1: identify the current location of tempdb database

use tempdb
go
sp_helpfile

--Step2: modify the system catalogue with new path

alter database tempdb modify file


(name='tempdev', filename='F:\system_dbs\tempdb.mdf')
alter database tempdb modify file
(name='templog', filename='F:\system_dbs\templog.ldf')
alter database tempdb modify file
(name='temp2', filename='F:\system_dbs\tempdb_mssql_2.ndf')
alter database tempdb modify file
(name='temp3', filename='F:\system_dbs\tempdb_mssql_3.ndf')
alter database tempdb modify file
(name='temp4', filename='F:\system_dbs\tempdb_mssql_4.ndf')

--step3: restart SQL Server

--Step4: copy the files from old to new location

--Step5: start SQL Server

--Step6: verify the new location

use tempdb
go
sp_helpfile

Master:

--step1: identify the current location of master database

use master
go
sp_helpfile

--Step2: modify the startup parameters with new path or we can


directly change the path using startup parameters as shown in the fig
below.

alter database master modify file


(name='master', filename='F:\system_dbs\master.mdf')
alter database master modify file
(name='mastlog', filename='F:\system_dbs\mastlog.ldf')

--step3: stop the SQL server

--Step4: copy the files from old to new location

--Step5: start SQL Server

--Step6: verify the new location

use master
go
sp_helpfile

Architectures:
 Here we discuss about the “Database Architecture” and “SQL Server Architecture”.
Database Architecture:
 Database consists of two files. They are “Data File” and “Log File”.
 Here we discuss about the architecture of both Data file and Log file.
Data File Architecture:

 At the time of creation of database, the data file will be created with defined initial size.
 Once the size is filled up, then it is not possible to insert the data into the data file.
 Hence in order to avoid that we have an option called “Auto growth” where we specify
some file size which will be added automatically to the data file once it gets filled up.
 Auto growth option can be provided with 2 storage values. Either we can fix “unlimited”
storage value/file size or we can limit the storage/size to a prescribed value.
 The unlimited storage value depends upon the storage value/size of the disk (D/E/F
Drive) in which the data is being stored.
 The data file is divided into number of small storage/data blocks.
 Each block is called a page.
 The size of each page is 8 kb.
 8 pages combines to form a group called as “Extent” and the size of the “Extent” is 64
kb.
 Extents can again be divided into 2 types. They are “Uniform Extent” and “Mixed
Extent”.
 In the uniform extent all the 8 pages contains the data from single table (Say T1).
 In the mixed extent the 8 pages contains data from a maximum of 8 tables/different
objects and a minimum of 2 tables.
 The pages are again divided into 2 types. They are GAM (Global allocation map) and
SGAM (Shared Global allocation map).
 GAM and SGAM tracks the status of uniform and mixed extents respectively.
 These pages are called as bit map pages as the data is stored in the form of 0’s and 1’s.
 If the bit map value is 1 in GAM, then it indicates that the uniform extent with all the 8
pages is full and already allocated.
 If the bit map value is 0 in GAM, then it indicates that the uniform extent with all the 8
pages is empty and available for use.
 If the bit map value is 1 in SGAM, then it indicates that the mixed extent with all the 8
pages is full and already allocated.
 If the bit map value is 0 in SGAM, then it indicates that the mixed extent with atleast 1
page is empty and is available for use.
 Every time when a table is created, it is assigned with mixed extent.
 Once the same table satisfies to fill all the 8 pages, then that particular table will be
allocated with uniform extent.
 Each GAM and SGAM tracks status of 4 Gb worth of uniform and mixed extents.

Log File Architecture:

 All the transaction that we make with the database except the “Select” statement gets
recorded in the log file first.
 Every transaction that is recorded into the log file will have a LSN (Log Sequence
Number).
 LSN is a hexadecimal number.
 Once the transaction gets committed in the log file then it will apply the corresponding
changes to the data file.
 Once the transaction is updated into the data file, the corresponding transactions in the
log file will get truncated periodically.
 The truncation of the log file occurs either when the check pointer occurs or the log
backup occurs.
 The log file is usually divided into number of small files called as VLF (Virtual Log Files).
 The VLF is of 3 types. They “Active”, “Recoverable”, “Reusable”.
 Initially all the VLF’s will be in Inactive state.
 Once the VLF’s are occupied with active transactions then that VLF is called as Active
VLF.
 Active VLF’s cannot be truncated.
 The VLF whose transaction is completed and waiting for backup to be performed are
called as “Recoverable VLF”.
 The VLF’s whose backup is completed are truncated and will be converted into
“Reusable VLF”.

SQL Server Architecture:

 The various layers of SQL Architecture are Client machine, Protocol Layer, Relational
Engine and Storage Engine.
 Any client machine has some network libraries which converts the given SQL query into
a TDS (Tabular Data Structure) packet.
 Whenever we want to transmit the data over a network it should be in the form of
network packets.
 Whatever the SQL query that we are executing, it will be converted into a TDS packet
and will be sent over the network to the database server.
 Once the protocol layer receives the TDS packets, it unwraps the TDS packet and
extracts the original SQL statement.
 SQL Server supports 3 different types of protocol layers. They are TCP/IP, Named Pipes
and Shared Memory.
 When a remote connection is to be made, we use TCP/IP.
 When we have 1 server and multiple clients/systems need to be connected to that
server, then we use Named Pipes.
 When the SQL Server is installed on a machine and we are trying to connect the SQL
Server from the same machine, then shared memory is used.
 The protocol layer converts the query written in English language into the machine
understandable binary language.
 The query converted into binary format is sent to the command parser in the relational
engine.
 Once the query is executed in the query executor in the relational engine, the result will
be sent in binary format to the protocol layer which converts it into the English
language.
 Relational engine has 3 main parts which are “CMD Parser”, “Optimizer”, and “Query
Executor”.
 The CMD parser receives the query from protocol layer and checks whether the query is
correct or not with regard to the syntax.
 If the syntax is wrong then the CMD Parser returns the query back to the protocol layer
which again sends it back to the user.
 The CMD Parser generates a query tree.
 Query tree is a bunch of plans with which the SQL query can be executed.
 The query tree gives a bunch of plans to the optimizer which selects an optimal plan to
execute the query.
 Once the optimal plan is selected by the optimizer it will be sent to the query executor
which executes the plan the control goes to storage engine where we have the data
related things.
 Storage engine contains Access methods which decides whether the query is a
transaction or not (Select operation or not).
 If it is select operation then the control comes to Buffer Manager directly.
 The select operation doesn’t goes to transaction log file.
 The role of buffer manager is to check the corresponding pages required for the select
query available or not in the buffer pool.
 Buffer pool is the RAM/Memory that we assigned to our SQL Server.
 If the required pages are available in the buffer pool, then it gives the response back to
buffer manager, then to access methods, then to query executor and then to the
protocol layer which converts the binary format into the user understandable language
and then to the TDS packet and then to the user in the form of result.
 If the corresponding/required pages are not available in the buffer pool, then the buffer
manager goes to data file.
 Data file is the place where we have our pages. The data file brings the corresponding
pages to the buffer pool.
 If the operation is other than select, then from access methods control goes to
transaction manager which makes the entry into the transaction log, once committed
gives the control back to transaction manager and then to access methods and then to
buffer pool and then so on.
 In order to avoid the buffer pool to be filled up, we have 2 internal processes running by
name “Check Pointer” and “Lazy Writer”.
 Check pointer is the process which runs at regular intervals and identifies all the dirty
pages in the buffer pool and sends them back to the data file.
 Dirty page is a page which is updated/modified and is residing in buffer pool.
 Lazy writer is a process which doesn’t have any fixed interval and runs randomly and
checks if there is any memory pressure in the buffer pool.
 If there is any memory pressure, then it identifies all the inactive pages and sends them
back to data file.
 Inactive page is the page which is in the buffer pool for some time and there is no
activity on that page.
 Lazy writer uses an algorithm called LRU (Least Recent Use) to find the inactive pages.

SQL Server Security:

 Security is usually based on 2 things. They are Authentication and Authorization.


 Authentication: This will allow you to login into the SQL server.
 Authorization: Once login in to the SQL Server, it requires authorization to access
particular database/databases.
 To provide the authorization we follow the following procedure.
 User Connection  Security  Specific login  Properties  User Mapping  Click on
the required databases.
 Login: Server level principle which will allow you to connect SQL server.
 User: When we map a login to a particular database, it becomes user for that particular
database.
Server Level Roles:
Fixed server-level role Description
Members of the sysadmin fixed server role can perform any
Sysadmin
activity in the server.
Members of the serveradmin fixed server role can change server-
Serveradmin
wide configuration options and shut down the server.
Members of the securityadmin fixed server role manage logins and
their properties. They can GRANT, DENY, and REVOKE server-level
permissions. They can also GRANT, DENY, and REVOKE database-
level permissions if they have access to a database. Additionally,
they can reset passwords for SQL Server logins.
securityadmin
IMPORTANT: The ability to grant access to the Database Engine
and to configure user permissions allows the security admin to
assign most server permissions. The securityadmin role should be
treated as equivalent to the sysadmin role.
Members of the processadmin fixed server role can end processes
processadmin
that are running in an instance of SQL Server.
Members of the setupadmin fixed server role can add and remove
linked servers by using Transact-SQL statements.
Setupadmin
(sysadmin membership is needed when using Management
Studio.)
Bulkadmin Members of the bulkadmin fixed server role can run the BULK
INSERT statement.
Diskadmin The diskadmin fixed server role is used for managing disk files.
Members of the dbcreator fixed server role can create, alter, drop,
Dbcreator
and restore any database.
Every SQL Server login belongs to the public server role. When a
server principal has not been granted or denied specific
permissions on a securable object, the user inherits the
permissions granted to public on that object. Only assign public
permissions on any object when you want the object to be
Public
available to all users. You cannot change membership in public.

Note: public is implemented differently than other roles, and


permissions can be granted, denied, or revoked from the public
fixed server roles.

Database Level Roles:

Fixed Database Level


Description
Role
Members of the db_owner fixed database role can perform all
configuration and maintenance activities on the database, and can
db_owner also drop the database in SQL Server. (In SQL Database and Azure
Synapse, some maintenance activities require server-level
permissions and cannot be performed by db_owners.)
Members of the db_securityadmin fixed database role can modify
role membership for custom roles only and manage permissions.
db_securityadmin
Members of this role can potentially elevate their privileges and
their actions should be monitored.
Members of the db_accessadmin fixed database role can add or
db_accessadmin remove access to the database for Windows logins, Windows
groups, and SQL Server logins.
Members of the db_backupoperator fixed database role can back
db_backupoperator
up the database.
Members of the db_ddladmin fixed database role can run any Data
db_ddladmin
Definition Language (DDL) command in a database.
Members of the db_datawriter fixed database role can add,
db_datawriter
delete, or change data in all user tables.
Members of the db_datareader fixed database role can read all
db_datareader data from all user tables and views. User objects can exist in any
schema except sys and INFORMATION_SCHEMA.
Members of the db_denydatawriter fixed database role cannot
db_denydatawriter add, modify, or delete any data in the user tables within a
database.
db_denydatareader Members of the db_denydatareader fixed database role cannot
read any data from the user tables and views within a database.

Backup and Recovery:

Backup: Maintaining a copy of database in different location and it can be used to recover the
database in case of failure.

Backup Architecture:

 While recovering/restoring the databases the .mdf and .ldf can be restored to the same
old previous location or can be restored to a new required location also.

Types of Backups:

The various types of backup available are as follows:

 Full backups
 Differential Backups
 Log backups or T-log backups or transactional log backups
 File and File group backups
 Split backups
 Mirror backups
 Copy only backup
 Tail-log backup

Full Backup:

 It takes the backup of entire database.


 If the database is of size 500 GB, then full backup size will also be 500 GB.
 The extension of full backup is BAK

Differential Backup:

 It takes the backup of all the changes (pages and extents) happened from last full
backup to till now.
 For example, if the database is of size 500 gb and we have taken full backup at 10 am.
 From 10 am to 11 am there is about 10 gb database added and now if we are taking
differential backup, then the size of differential backup will be 10 gb only.
 Differential backups are cumulative.
 The extension is “Bak”.

Log Backup:

 It takes the backup of all the transactions available in the log file and once the backup is
done it will truncate those transactions from the log file.
 The extension is ‘TRN’.
 Log backups are sequential.
Case study (Differential Backup):

 Let us assume that we have a database of size 100 gb.


 A full backup is taken on Sunday with name F1 and differential backup’s are taken daily
from Monday to Saturday with names D1, D2, D3, D4, D5, D6 .
 After full backup is taken, from Monday onwards 1 gb data is added to the database
daily.
 When the full backup is taken the size of full backup will be of 100 gb.
 The differential backup D1 will be of size 1 gb as only 1 gb data is added to the database
on Monday.
 The differential backup D2 will be of size 2 gb as 1 gb data is added to the database on
Monday and 1 gb on Tuesday.
 The differential backup D3 will be of size 3 gb as each day of the week is added with 1 gb
data and so on.
 Now again on next Sunday when the full backup F2 is taken, then the size will be of 107
gb.
Case study (Log backup):

 Let us assume that we have a database of size 100 gb.


 A full backup is taken on Sunday with name F1 and log backup’s are taken daily from
Monday to Saturday with names L1, L2, L3, L4, L5, L6 .
 After full backup is taken, from Monday onwards 1 gb data is added to the database
daily.
 When the full backup is taken the size of full backup will be of 100 gb.
 The log backup L1 will be of size 1 gb as only 1 gb data is added to the database on
Monday.
 Once the log backup is done, the log data file will be truncated.
 Hence all the log backups L2, L3, L4, L5, L6 will be of 1 gb only.
 Now again on next Sunday when the full backup F2 is taken, then the size will be of 107
gb.

How to take Backups:

Backup can be performed in many ways as shown below:

 SSMS – GUI
 SSMS – TSQL
 SQL Server agent job
 Maintenance Plans
 Power shell
 Third Party tools

SSMS – GUI:

 The backup of the database can be done using the SSMS as follows:
 Right click on required database  Tasks  Back Up  General Tab  Select the
backup type (Full/Differential)  Select the Backup destination  Ok.
 Database restoring can be done as follows.
 Right click on database folder  Restore Database  Select device and browse the
backup location  Ok
Restore Options:

We have 3 types of restore options as follows:

 Restore with no Recovery


 Restore with Recovery
 Restore with Standby

Restore with no Recovery:

 If there are any further backups to be restored, then we need to use restore with no
recovery.
 The backup will be restored, but the database gets into the restoring state and we can’t
access the database.
Restore with Recovery:

 If there are no further backups to be restored, then we can choose backup with
recovery option.
 This will restore the backup, brings the database online and will be available for use.

Restore with stand by:

 It will restore the backup and brings the database online available for user in “Read
only” mode.
Backup Strategy:

 Weekly full backup – Sunday 12:00 am


 Daily differential backups at 10 am
 Log backups for every 1 hour

Let us assume that our database is crashed on Thursday 4.30 PM, in such case the employ the
following process to recover our database.

Recovery Process:

 Step1: Restore latest Sunday full backup with no recovery.


 Step2: Restore Thursday’s 10 am differential backup.
 Step3: Restore all the log backups one by one sequentially from 11 am to 4 PM.

Failure Point:

 The time at which the database is crashed is called “failure Point”.


 Ex: in our example, failure point is 4.30 PM

Point in Time Recovery:

 The process of recovering a database exactly at the failure point, then we call it as PIR is
achieved.

Recovery Models:

 The recovery model is a database level property.


 This decides to which point (to what extent) you can recover a database in case of
failure.
 Recovery models are of 3 types as shown below.
 Simple
 Bulk logged
 Full recovery

Simple Recovery Model:

 In simple recovery model, the transaction log file (ldf) will get truncated automatically in
regular intervals (when check pointer occurs).
 As the transaction log is truncated automatically, it won’t allow us to perform log
backups. (Limitation is log backups can’t be performed).
 PIR can’t be achieved in Simple recovery model.

Bulk logged Recovery Model:

 In bulk logged recovery model, the transactions will be minimally logged for bulk
operations like BCP, Bulk insert, select into, index rebuild.
 So we can save the transaction log space of the database.
 For normal operation it works as similar to full recovery model.

Case1: If the database is in bulk logged, if there is bulk operations performed, then we can’t
achieve PIR

Case2: If the database is in bulk logged, if there are no bulk operations, it is as similar to full
recovery model and we can achieve PIR.

Full Recovery Model:

 In Full recovery model, all the transactions will be fully logged into the log file and there
won’t be any automatic truncation.
 Hence we can take log backups and we can achieve PIR.
 It is a best practice to keep all the production databases in ‘Full’ recovery model.

How to check recovery model?

Option 1:

Right click on the database namepropertiesoptions recovery model


Option 2:

select name,recovery_model_desc from sys.databases

How to Change Recovery Model:

Option1:

Right click on the database namepropertiesoptionsrecovery model  change it from


drop down
Option2:

alter database databasename set recovery full/Simple/bulk logged

alter database [BACKUP-DEMO] set recovery full


alter database [BACKUP-DEMO] set recovery simple
alter database [BACKUP-DEMO] set recovery [bulk_logged]

SSMS – TSQL:

 To perform the full backup the query can be written as follows.

backup database [BACKUP-DEMO] to disk=’C:\sql\backups\backupdemo.bak’

 To perform the differential backup the query can be written as follows.

backup database [BACKUP-DEMO] to disk=’C:\sql\backups\backupdemo_Diff.bak’ with


differential

 To perform the log backup the query can be written as follows.

backup log [BACKUP-DEMO] to disk=’C:\sql\backups\backupdemo_Log1.trn’

 To restore the full backup the query can be written as follows.


restore database [BACKUP-DEMO] from disk=’C:\sql\backups\backupdemo.bak’ with
norecovery
 To restore the differential backup the query can be written as follows.

restore database [BACKUP-DEMO] from disk=’C:\sql\backups\backupdemo_Diff.bak’


with norecovery
 To restore the log backup the query can be written as follows.

restore log [BACKUP-DEMO] from disk=’C:\sql\backups\backupdemo_log1.bak’

 If we don’t mention any option, then restoring will be done with the option of backup
with recovery.

SQL Server Agent Job:

 Configuring/running the backups using SQL Server agent can be done as follows.
 SQL Server Agent  Right click on the jobs  New job  Name  Steps  New 
Step Name  Add the full backup command in the open space  Ok  Schedules 
New  Name  Schedule type as recurring  Recurs every as daily  Occurs every 1
Min  Ok.
 We can avoid taking manual backup and can automate the process of taking the
backups using the SQL Server agent job.
File and File Group Backups:

 When we take the backup from SSMS, the backup consists of the entire database.
 When we want to take the backup of a particular data file or file group then we can do
the same using SSMS as follows.
 Right click on the database  Tasks  Backup  File and file groups  Add  Backup
location  Ok
 Using SQL query the backup can be taken as follows.
 backup database [BACKUP-DEMO] file=’ BACKUP-DEMO2’ to disk=’c:\sql\backups\
backupdemo_file2.bak’
 backup database [BACKUP-DEMO] filegroup=’second’ to disk='C:\sql\backups\
backupdemo_fg2.bak',

Split Backup:

 Split backup can be performed to take a database backup to multiple destinations.


 If we take a split backup it will take database backup equally into multiple destinations.
 Using split backup we can optimize the time taken to complete the backup process.
 For example if it takes 4 hours to complete the full backup normally, by using split
backup we can complete the same in 2 hours.
 Using SSMS split backup can be done as follows.
 Right click on the database  Tasks  Backup  File and file groups  Add  Backup
location  Ok

 Using query, split backup can be done as follows.
 backup database [BACKUP-DEMO]
to
disk='C:\sql\backups\backupdemo1.bak',
disk='C:\sql\backups\backupdemo2.bak',
disk='C:\sql\backups\backupdemo3.bak'
 When the split backup is to be taken on 2 different servers, then we perform the
following process.
 The folder to which the backup is to be done has to be made a shared folder.
 Taking backups to shared network using query is as shown below
 backup database [BACKUP-DEMO]
to
disk='\\DESKTOP-IA0FMAF\backups\backupdemo1.bak',
disk='\\DESKTOP-IA0FMAF\backups\backupdemo2.bak',
disk='\\DESKTOP-IA0FMAF\backups\backupdemo3.bak'

Mirror Backups:

 It takes multiple copies of database backup.


 It is for extra safety.
 If one copy of backup is corrupted, then we will have another copy.
 Mirror backup can be done only using query. It can’t be done using SSMS.
 backup database [BACKUP-DEMO]
to Disk='\\DESKTOP-IA0FMAF\backups\backupdemo1.bak'
mirror
to disk='\\DESKTOP-IA0FMAF\backups\backupdemo1.bak' with format
 Restoring the database can be done as follows.
 restore database [BACKUP-DEMO]
from Disk='\\DESKTOP-IA0FMAF\backups\backupdemo1.bak'

Restore Commands:

Various restore commands are as follows:

 Verify only
 Header only
 Filelist only
 Label only

Verify Only:

 We can verify whether the database backup is in valid restorable format or not.
Restore verifyonly from disk='\\DESKTOP-IA0FMAF\backups\backupdemo1.bak'

Header Only:

 This will provide all the metadata of a backup such as database name, database creation
date, backup size, backup start and finish time, server name, version..etc.
 It provides the backupsets information also.
 Restore headeronly from disk='\\DESKTOP-IA0FMAF\backups\samantha.bak'
 Restore headeronly from disk='\\DESKTOP-IA0FMAF\backups\backupdemo1.bak'
Filelistonly:

 This will gives the files information from the backups

Restore filelistonly from disk='\\DESKTOP-IA0FMAF\backups\modeldemo.bak'

Label only:

 This will provide all the backup media information such media type like disk, or tape or
url etc.
 Restore labelonly from disk='\\DESKTOP-IA0FMAF\backups\modeldemo.bak'
Tail log backup:

 It is a log backup, which we perform in the event of database failure.


 This backup is taken manually only after the database is crashed.
 This backup works only when the database crashed with data file corruption.
 Doesn’t works when the log file is corrupted.
 This will take log backup of all the transactions happened from last successful log
backup to failure point. (4 PM to 4.30 PM)

Case Study:

 Weekly full backup – Sunday 12 am


 Daily Differential backups – 10 am
 Log backups for every 1 hour

 Database is crashed at 4.30 pm on Thursday

Recovery process:

 Restore latest Sunday full backup with no recovery.


 Restore Thursday 10 am differential backup with no recovery.
 Restore 11 am, 12 pm, 1 pm, 2 pm, 3 pm log backups with no recovery.
 Restore 4 pm log backup with recovery.

 With above backups, we were able to recover the database only upto 4 pm.
 But the database is crashed at 4.30 pm, So there is about 30 mins of transaction loss.
 To recover the remaining 30 mins of transactions, we need to use tail log backup.

Recovery process:

 Take Tail log backup


 Restore latest Sunday full backup with no recovery.
 Restore Thursday 10 am differential backup with no recovery.
 Restore 11 am, 12 pm, 1 pm, 2 pm, 3 pm, 4 pm log backups with no recovery.
 Restore tail log backup with recovery.

Tail Log back up and Restore Demonstration:


Create a Database:

CREATE DATABASE [TailLogDemo]


alter database [TailLogDemo] set recovery full
Create a Table:

USE [TailLogDemo]
GO

CREATE TABLE [dbo].[Emp_Details]


([ID] [int] NULL,
[Name] [varchar](50) NULL,
[Sal] [money] NULL)
ON [PRIMARY]
GO

Insert Data into the Table:

INSERT INTO [TailLogDemo].[dbo].[Emp_Details]


VALUES (100, 'Ramesh', 5000)
GO 100

Issue a Full Backup:

BACKUP DATABASE TailLogDemo TO


DISK = 'C:\sql\backups\tailogdemo\FULL.BAK'
GO

Insert Data into the table again:

INSERT INTO [TailLogDemo].[dbo].[Emp_Details]


VALUES (200, 'Diff', 6000)
GO 100

Issue a Differential Backup:

BACKUP DATABASE TailLogDemo TO


DISK = 'C:\sql\backups\tailogdemo\Diff.BAK'
with differential
GO

Insert Data into the table again:

INSERT INTO [TailLogDemo].[dbo].[Emp_Details]


VALUES (300, 'Log1', 6000)
GO 100

Issue a log backup1:


BACKUP LOG TailLogDemo TO
DISK = 'C:\sql\backups\tailogdemo\LOG1.TRN'
GO

Insert Data into the table again:

INSERT INTO [TailLogDemo].[dbo].[Emp_Details]


VALUES (400, 'log2', 7000)
GO 100

Issue a log backup2:

BACKUP LOG TailLogDemo TO


DISK = 'C:\sql\backups\tailogdemo\LOG2.TRN'
GO -- Thursday 4 pm

Insert Data into the table again:

INSERT INTO [TailLogDemo].[dbo].[Emp_Details]


VALUES (400, 'Ram', 8000)
GO 100 - until 4.30 PM

use master
Go

Set database to offline:

ALTER DATABASE [TailLogDemo] SET OFFLINE


GO

DELETE DATA FILE (mdf)

Set database to online:

ALTER DATABASE [TailLogDemo] SET ONLINE


GO

Take Tail Log Backup:

USE MASTER
GO
BACKUP LOG TailLogDemo TO DISK
= 'C:\sql\backups\tailogdemo\TAIL.TRN'
with no_truncate
GO

Restore all the Back ups:

Restore database TailLogDemo from disk ='C:\sql\backups\tailogdemo\Full.bak' with


norecovery

Restore database TailLogDemo from disk ='C:\sql\backups\tailogdemo\Diff.bak' with


norecovery

Restore database TailLogDemo from disk ='C:\sql\backups\tailogdemo\Log1.Trn' with


norecovery

Restore database TailLogDemo from disk ='C:\sql\backups\tailogdemo\Log2.Trn' with


norecovery

Restore database TailLogDemo from disk ='C:\sql\backups\tailogdemo\Tail.Trn' with recovery

Copy Only Backups:

 Weekly full backup – Sunday 12 am


 Daily Differential backups – 10 am
 Log backups for every 1 hour

 On Thursday 4.30 PM, A developer raised a ticket to refresh the Dev server with the
production database.

Khan:

 He just took a full backup on Thursday and restored into dev server, request completed.
 Ticket closed.
 Requester is happy.
 Friday – everything went well, no issues.
 Saturday at 4.30 PM database is crashed.

Harinath (on-call):

 Restore Sunday full backup with norecovery.


 Restore Saturday differential backup with norecovery.
 This doesn’t works out as the latest full backup is done on Thursday and which is not
restored here as we are not aware of the backup taken on Thursday.
 In such cases to avoid these kind of problems, we go for performing copy-only backup.

Step 1:

USE master
GO
create database CopyOnlyDemo
alter database CopyOnlyDemo set recovery full

C:\sql\backups\Copy_ONly\Copy_ONLY

BACKUP DATABASE CopyOnlyDemo


TO DISK='C:\sql\backups\Copy_ONly\CopyOnlyDemo_full1.BAK'

As per shedule (weekly on sunday)


BACKUP LOG CopyOnlyDemo TO DISK='C:\sql\backups\Copy_ONly\CopyOnlyDemo_log1.TRN'
WITH INIT --as per shedule (every 1 hour)

BACKUP DATABASE CopyOnlyDemo TO DISK='C:\sql\backups\Copy_ONly\


CopyOnlyDemo_diff1.BAK'
WITH INIT, DIFFERENTIAL --as per shedule (every day at 10:00 AM)

BACKUP LOG CopyOnlyDemo TO DISK='C:\sql\backups\Copy_ONly\CopyOnlyDemo_log1.TRN'


WITH INIT --as per shedule (every 1 hour)

--run special full backup


BACKUP DATABASE CopyOnlyDemo TO DISK='C:\sql\backups\Copy_ONly\
CopyOnlyDemo_full2.BAK'
WITH INIT,copy_only --(manual adhoc fullbackup on thursday at 4.30 PM)

--resume normal backup process


BACKUP DATABASE CopyOnlyDemo TO DISK='C:\sql\backups\Copy_ONly\
CopyOnlyDemo_diff2.BAK'
WITH INIT, DIFFERENTIAL --(as per schedule on Friday 10.00 am)

BACKUP LOG CopyOnlyDemo TO DISK='C:\sql\backups\Copy_ONly\CopyOnlyDemo_log3.TRN'


WITH INIT --(as per schedule log backup)

-- database crashed on saturday at 4 pm


--step 2
RESTORE DATABASE CopyOnlyDemo FROM DISK='C:\sql\backups\Copy_ONly\
CopyOnlyDemo_full1.BAK'
WITH NORECOVERY, REPLACE -- sunday full backup as per schedule

RESTORE DATABASE CopyOnlyDemo FROM DISK='C:\sql\backups\Copy_ONly\


CopyOnlyDemo_diff2.BAK'
WITH NORECOVERY -- latest differential backup i.e saturdays
RESTORE LOG CopyOnlyDemo FROM DISK='C:\sql\backups\Copy_ONly\
CopyOnlyDemo_log3.TRN'
WITH RECOVERY

/**If we try to restore our original full backup, our latest full backup and any transaction log
backup after the differential we get this error. **/

/**Msg 3136, Level 16, State 1, Line 1


This differential backup cannot be restored
because the database has not been restored to
the correct earlier state.
Msg 3013, Level 16, State 1, Line 1

RESTORE DATABASE is terminating abnormally.


If we rerun the process, but this time use the COPY_ONLY option for our special full backup, the
restore process works as planned.
**/
restore database CopyOnlyDemo with recovery
--step 1

USE master
GO
BACKUP DATABASE CopyOnlyDemo TO DISK='C:\sql\backups\Copy_ONly\
CopyOnlyDemo_full.BAK' WITH INIT

BACKUP LOG CopyOnlyDemo TO DISK='C:\sql\backups\Copy_ONly\CopyOnlyDemo_log1.TRN'


WITH INIT

BACKUP DATABASE CopyOnlyDemo TO DISK='C:\sql\backups\Copy_ONly\


CopyOnlyDemo_diff.BAK' WITH INIT, DIFFERENTIAL

BACKUP LOG CopyOnlyDemo TO DISK='C:\sql\backups\Copy_ONly\CopyOnlyDemo_log2.TRN'


WITH INIT

--run special full backup

BACKUP DATABASE CopyOnlyDemo TO DISK='C:\sql\backups\Copy_ONly\


CopyOnlyDemo_full2.BAK' WITH INIT, COPY_ONLY

--resume normal backup process

BACKUP DATABASE CopyOnlyDemo TO DISK='C:\sql\backups\Copy_ONly\


CopyOnlyDemo_diff2.BAK' WITH INIT, DIFFERENTIAL

BACKUP LOG CopyOnlyDemo TO DISK='C:\sql\backups\Copy_ONly\CopyOnlyDemo_log3.TRN'


WITH INIT

--step 2

RESTORE DATABASE CopyOnlyDemo FROM DISK='C:\sql\backups\Copy_ONly\


CopyOnlyDemo_full.BAK' WITH NORECOVERY, REPLACE

RESTORE DATABASE CopyOnlyDemo FROM DISK='C:\sql\backups\Copy_ONly\


CopyOnlyDemo_diff2.BAK' WITH NORECOVERY

RESTORE LOG CopyOnlyDemo FROM DISK='C:\sql\backups\Copy_ONly\


CopyOnlyDemo_log3.TRN' WITH RECOVERY

 The backup and restore history will be stored in the MSDB database.
 The tables in which the backup and restore history is stored is Backupset and
backupmediafamily.
select
bs.database_name,
bs.type,
bs.is_copy_only,
bs.differential_base_lsn,
bs.backup_finish_date,
bmf.physical_device_name
from backupset bs
join backupmediafamily bmf
on bs.media_set_id=bmf.media_set_id
where database_name='CopyOnlyDemo'
order by backup_finish_date descs

Point in Time Recovery:

 Weekly full backup – Sunday 12 AM.


 Daily differential backups – 10 am.
 Log backups for every 1 hour.

 On Thursday 4.30 PM, A developer accidentally deleted some key table from the
database.

Recovery Process:

 Restore Sunday full backup with norecovery


 Restore Thursday differential backup with norecovery
 Restore all the log backups from 11 am, 12 pm, 1 pm, 2pm, 3pm, 4 pm with norecovery
 Restore 5 pm log backup with recovery.
 Restore Sunday full backup with norecovery.
 Restore Thursday differential backup with norecovery.
 Restore all the log backups from 11 am, 12 pm, 1 pm, 2pm, 3pm, 4 pm with norecovery.
 Restore 5 pm log backup with recovery using STOP AT 4.29.59 PM.

RESTORE DATABASE AdventureWorks FROM DISK = 'C:\AdventureWorks.bak' WITH


NORECOVERY

GO

RESTORE LOG AdventureWorks FROM DISK = 'C:\AdventureWorks.TRN' WITH RECOVERY,


STOPAT = 'Jun 11, 2021 04:29:59 PM'

GO
Backup Options:

backup DATABASE [modeldemo]


to DISK = 'C:\sql\backups\modeldemo.BAK'
WITH
stats=30,
password='sssssss',
Differential,--this will take differential backup
init,--it will override existing bac kup set
noinit,-- it will create new backup set
format,-- removes all the disc level inconsistencies
no_truncate,--tail log backup
copy_only--copy only backup

Query to find the backup and restore status:

select
command,
percent_complete,
estimated_completion_time
from sys.dm_exec_requests
where command like '%backup%'

select
command,
percent_complete,
estimated_completion_time
from sys.dm_exec_requests
where command like '%restore%'

High availability and Disaster recovery solutions:

High Availability (HA) is the solution\process\technology to make the application\database


available 24x7 under either planned or un-planned outages. Mainly, there are five options in
MS SQL Server to achieve\setup high availability solution for the databases

RPO – Recovery Process objective

How much data loss affordable.


Ex: RPO – 5 mins and the database is crashed at 4.30 PM.. we should able to recover the
database up to 4.25 PM, that’s fine

If we are able to recovery up to 4 PM.. then it will be considered as SLA miss.

RPO: - 0, the database is crashed at 4.30 PM, then we should recover database to 4.30 PM.

RTO – Recovery Time Objective

How much time we can take to recover the database

RTO – 2 hours, the db is crashed at 4.30 PM and we should be able to recover the database by
6.30 PM

HA Architecture:

High availability solutions:

1. Log shipping - Database solutions


2. Database Mirroring – Database level solution
3. Replication- object level solution
4. Failover clusters – instance level/server level
5. Always On availability group – instance level/ group of databases

Log Shipping:
Log shipping is a Basic database level high availability solution which transfers the transactional
log backups from one server to another server and restores there.

Pre perquisites to configure log shipping:

1. Two servers (minimum)


a. Primary – Production, source in log shipping where we taking the log backups
b. Secondary – standby- the target to where we are sending the log backups
2. Database recovery model – must full or bulk logged.. but recommended is Full.
3. Take full backup of primary database and restore in secondary with no recovery
4. We need two share folders, 1 in primary and other 1 is in secondary
5. SQL server agent must be up and running

Demo:
Adding a file to log shipping primary database:

Add file to primary:

--add file
alter database [LsDemo]
add file (name='lsdemo1',filename='c:\sql\backups\lsdemo1.ndf')

Log shipping restore job failed with the below error:


Solution:

restore log [LsDemo] from


disk='\\DESKTOP-IA0FMAF\backups\logshipping\target\LsDemo_20210612115400.trn'
with norecovery,
move 'lsdemo1' to 'C:\sql\backups\logshipping\lsdemo1.ndf'

Fail over process:

1. Take a tail log backup to take log backup of transactions happened after last log backup
2. Restore all the pending log backups if there are any.. using with no recovery
3. Restore tail log backup with recovery
4. Work with application team to point the application connections to secondary database
5. We have to validate all the logins, orphan users, jobs ..etc
Database Mirroring:

Database Mirroring also Database level High availability solution which transfer “Transaction
logs” from one server another server.

Pre Requisites:

1. Minimum of two servers


a. Principle – source in Mirroring
b. Mirror – Target in Mirroring
c. Witness (optional)

2. Database Recovery Model Must be Full


3. Take a full backup of Principal database and restore it into mirror with norecovery
4. Take a log backup of Principal database and restore it into mirror with norecovery

Mirroring Modes:

1. Synchronous
i. High safety or High protection
ii. High availability
2. Asynchronous Mirroring
i. High Performance mode

You might also like