Category Archives: SQL Server

Restore Database with Tail-log Backup

Restore & Recover Database with Tail Backup (SQL Server)

Table of Contents


0. What is a Tail-Log Backup?
1. Create Test Database
2. Create Table & Insert Data
3. Take FULL Backup
4. Insert More Data (Simulate Activity)
5. Take LOG Backup
6. More Transactions
7. Simulate Failure
8. Take Tail-Log Backup (Final Log Backup)
9. Listdown All Backup files
10. Restore FULL Backup
11. Restore LOG Backup
12. Restore TAIL Backup (Final Restore – Last step)
13. Verify Data



0. What is a Tail-Log Backup?

Definition: A tail-log backup captures the “tail” of the transaction log — the portion of log records that have not yet been backed up.

Purpose: It ensures no data loss and maintains the log chain for point-in-time recovery.

Usage: Taken before restoring a database, especially after failure or corruption, to secure the most recent changes.
BACKUP LOG [DatabaseName] TO DISK = 'Path\TailLog.trn' WITH NO_TRUNCATE; (If DB corrupted/Offline/Recovery Pending)

Migration: When moving a database to another server, the tail-log backup ensures no data is lost during the cutover, if planned then use BACKUP LOG [DatabaseName] TO DISK = 'Path\TailLog.trn' WITH NORECOVERY; 

Requirement: The log file (.ldf) must be available, if it’s missing or corrupted, a tail-log backup isn’t possible.


1. Create Test Database

CREATE DATABASE TEST;
GO

ALTER DATABASE TEST SET RECOVERY FULL;
GO



2. Create Table & Insert Data

USE TEST;
GO

CREATE TABLE emp (
    id INT,
    name VARCHAR(50)
);

INSERT INTO emp VALUES (1, 'SUGI');
GO



3. Take FULL Backup

BACKUP DATABASE TEST TO DISK = 'K:\BACKUP\TEST\Test_full.bak';



4. Insert More Data (Simulate Activity)

INSERT INTO emp VALUES (2, 'TEJA');
GO



5. Take LOG Backup

BACKUP LOG TEST TO DISK = 'K:\BACKUP\TEST\Test_log1.trn';

 


6. More Transactions

INSERT INTO emp VALUES (3, 'JANA');
GO



7. Simulate Failure

DISCLAIMER: The commands given below is just for learning purposes and should only be used on testing systems. I will not take any responsibility of any consequences or loss of data caused by these commands.

Now assume: Database issue / corruption / accidental restore requirement

Before starting a restore, you SHOULD take a tail-log backup (final log backup)

1. Insert Data
2. Kill SQL Server
3. Rename or Move Data File (MDF)
4. Start SQL Server
5. Database won't be accesable.
6. Take Tail-log backup (Final backup)
7. Restore Full Backup with NORECOVERY
8. Restore Log backups (All Log backups) with NORECOVERY;
9. Restore (Final restore) Tail-log backup with RECOVERY;
10. Database will come Online.
-- Generate activity

INSERT INTO emp VALUES (4, 'SOMU');
GO

-- Remove MDF (OS level)
SELECT name, physical_name FROM sys.master_files WHERE database_id = DB_ID('TEST');

Get-Service -Name 'MSSQLSERVER'

Stop-Service -Name 'MSSQLSERVER' -Force

Move-Item -Path "D:\MSSQL16.MSSQLSERVER\MSSQL\Data\TEST.mdf" -Destination "T:\SQLDATA\TEST.mdf"

Test-Path "T:\SQLDATA\TEST.mdf"
Test-Path "D:\MSSQL16.MSSQLSERVER\MSSQL\Data\TEST.mdf"

Start-Service -Name 'MSSQLSERVER'
Get-Service -Name 'MSSQLSERVER'

  



8. Take Tail-Log Backup

-- IF Database accesable  
BACKUP LOG TEST TO DISK = 'K:\BACKUP\TEST\Test_tail.trn' WITH NORECOVERY;

-- If DB is damaged (DB in SUSPECT Mode/Offline/Recovery Pending)
BACKUP LOG TEST TO DISK = 'K:\BACKUP\TEST\Test_tail.trn' WITH NO_TRUNCATE;

NORECOVERYNO_TRUNCATE
Difference
  • Puts the database into restoring state.
  • Prevents further transactions.
  • Ensures no more changes happen after backup starts, until restore completes.
  • Typically used when DB is still accessible/online.
  • Use NORECOVERY when you are planning a restore and want to freeze the database.
  • Allows log backup even if database is damaged/offline.
  • Does NOT require database to be online.
  • Skips normal checks and forces log capture.
  • Log file must be accesable, else log backup will fail.


9. Listdown All Backup files

Full Backup file: K:\BACKUP\TEST\Test_full.bak
Log Backup file 1: K:\BACKUP\TEST\Test_log1.trn


10. Restore FULL Backup

RESTORE DATABASE TEST FROM DISK = 'K:\BACKUP\TEST\Test_full.bak' WITH NORECOVERY;


11. Restore LOG Backup

RESTORE LOG TEST FROM DISK = 'K:\BACKUP\TEST\Test_log1.trn' WITH NORECOVERY;


12. Restore TAIL Backup (Final Step)

RESTORE LOG TEST FROM DISK = 'K:\BACKUP\TEST\Test_tail.trn' WITH RECOVERY;


13. Verify Data

USE TEST;
GO
SELECT * FROM emp;
 

Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

SQL Server AlwaysOn Automatic Failover

SQL Server AlwaysOn Automatic Failover

Table of Contents


1. What is Automatic Failover?
2. Requirements for Automatic Failover
3. Environment
4. Verify Automatic Failover Configuration
5. Simulate Automatic Failover
6. Verify New Primary Replica
7. Verify Listener Connectivity
8. Best Practices


1. What is Automatic Failover?

Automatic Failover in SQL Server AlwaysOn Availability Groups allows SQL Server to automatically switch the primary replica to a secondary replica when the primary server becomes unavailable. This ensures high availability and minimizes application downtime.

Automatic failover works only when replicas are configured with Synchronous Commit Mode and Automatic Failover Enabled.

2. Requirements for Automatic Failover

1. Availability Mode must be SYNCHRONOUS COMMIT
2. Failover Mode must be AUTOMATIC
3. Databases must be SYNCHRONIZED
4. Windows Server Failover Cluster (WSFC) must be healthy

3. Environment

Server NameIP AddressRoleAvailability ModeFailover Mode
NTICBPSQLSGV01192.168.2.21PrimarySynchronous commitAUTOMATIC
NTICBPSQLSGV02192.168.2.22SecondarySynchronous commitAUTOMATIC
NTICBRSQLSGV03192.168.3.10SecondaryAsynchronous commitMANUAL

4. Verify Automatic Failover Configuration

SELECT 
ar.replica_server_name,
ar.availability_mode_desc,
ar.failover_mode_desc
FROM sys.availability_replicas ar;

-------
select
    ag.name as aag_name,
    ar.replica_server_name,
    d.name as [database_name],
    hars.is_local,
    hars.synchronization_state_desc as synchronization_state,
    hars.synchronization_health_desc as synchronization_health,
    hars.database_state_desc as db_state,
    hars.is_suspended,
    hars.suspend_reason_desc as suspend_reason,
    hars.last_commit_lsn,
    hars.last_commit_time
from sys.dm_hadr_database_replica_states as hars
join sys.availability_replicas as ar
    on hars.replica_id = ar.replica_id
join sys.availability_groups as ag
    on ag.group_id = hars.group_id
join sys.databases as d
    on d.group_database_id = hars.group_database_id
order by aag_name, replica_server_name;


5. Simulate Automatic Failover (DO ONLY IN TEST MACHINES)

To test automatic failover, stop the SQL Server service on the current primary server.

When the primary replica goes offline, the cluster automatically promotes the secondary replica configured for automatic failover.

Stop-Service MSSQLSERVER


6. Verify New Primary Replica

SELECT 
ag.name AS AG_Name,
ar.replica_server_name,
ars.role_desc
FROM sys.availability_groups ag
JOIN sys.availability_replicas ar 
ON ag.group_id = ar.group_id
JOIN sys.dm_hadr_availability_replica_states ars 
ON ar.replica_id = ars.replica_id;

-----

select
    ag.name as aag_name,
    ar.replica_server_name,
    d.name as [database_name],
    hars.is_local,
    hars.synchronization_state_desc as synchronization_state,
    hars.synchronization_health_desc as synchronization_health,
    hars.database_state_desc as db_state,
    hars.is_suspended,
    hars.suspend_reason_desc as suspend_reason,
    hars.last_commit_lsn,
    hars.last_commit_time
from sys.dm_hadr_database_replica_states as hars
join sys.availability_replicas as ar
    on hars.replica_id = ar.replica_id
join sys.availability_groups as ag
    on ag.group_id = hars.group_id
join sys.databases as d
    on d.group_database_id = hars.group_database_id
order by aag_name, replica_server_name;


7. Verify Listener Connectivity

Connect using the Availability Group Listener and verify which server is currently serving connections.

SELECT @@SERVERNAME;
The result should display the new primary replica after automatic failover.


8. Best Practices

  • Always configure at least two replicas for automatic failover.
  • Monitor synchronization state regularly.
  • Use synchronous commit for automatic failover partners.
  • Test automatic failover periodically in non-production environments.

Summary:
Automatic Failover in SQL Server AlwaysOn ensures high availability by automatically promoting a synchronized secondary replica to primary when the primary server fails.
Proper configuration of synchronous commit mode and automatic failover settings is
essential for seamless failover with minimal downtime.


Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

SQL Server AlwaysOn Manual Failover

SQL Server AlwaysOn Manual Failover (3-Node Setup) using SSMS (GUI Method)

Table of Contents


0. Pre-requisites
1. Environment
2. Check Synchronization State
3. Identify Failover Target
4. Perform Manual Failover (Run Failover Command on NTICBPSQLSGV02)
5. Verify New Primary
6. Verify Listener Connectivity
7. Validate Database Status and Synchronization Health


0. Pre-requisites

# Manual failover requires Synchronous commit mode.
# Databases must be SYNCHRONIZED.
# No data loss during planned failover.

Note: Forced Failover (Emergency Only). This may cause data loss.

1. Environment

Availability Group : NTICBPSQLSGA05
Server NameIP AddressRole
NTICBPSQLSGV01192.168.2.21Primary Replica
NTICBPSQLSGV02192.168.2.22Secondary Replica
NTICBRSQLSGV03192.168.3.10Secondary Replica

2. Check Synchronization State

select
    ag.name,
    ar.replica_server_name,
    ar.availability_mode_desc as [availability_mode],
    ars.synchronization_health_desc as replica_sync_state,
    rcs.database_name,
    drs.synchronization_state_desc as db_sync_state,
    rcs.is_failover_ready,
    rcs.is_pending_secondary_suspend,
    rcs.is_database_joined
from sys.dm_hadr_database_replica_cluster_states as rcs
join sys.availability_replicas as ar
    on ar.replica_id = rcs.replica_id
join sys.dm_hadr_availability_replica_states as ars
    on ars.replica_id = ar.replica_id
join sys.dm_hadr_database_replica_states as drs
    on drs.group_database_id = rcs.group_database_id
    and drs.replica_id = ar.replica_id
join sys.availability_groups as ag
    on ag.group_id = ar.group_id;

3. Identify Failover Target

Current Primary  : NTICBPSQLSGV01
Failover Target  : NTICBPSQLSGV02

4. Perform Manual Failover (Run Failover Command on NTICBPSQLSGV02)

On NTICBPSQLSGV02:

The key concept is the location where the FAILOVER command is executed.
If you want to promote Node2 as the new Primary replica, you must first log in to server  Node2, open SQL Server Management Studio (SSMS), connect to the SQL instance on Node2, and then initiate the failover.

ALTER AVAILABILITY GROUP … FAILOVER command does not specify the target node, on whichever server you run this command it becomes the new Primary.

T-SQL

ALTER AVAILABILITY GROUP [NTICBPSQLSGA05] FAILOVER;
GO

—- OR —-

GUI Steps:

Right Click Availability Group
→ Click Failover
→ Select the Secondary Replica
→ Perform Manual Failover
→ Finish the Wizard

5. Verify New Primary

SELECT 
    ag.name AS AG_Name,
    ar.replica_server_name,
    ars.role_desc
FROM sys.availability_groups ag
JOIN sys.availability_replicas ar 
     ON ag.group_id = ar.group_id
JOIN sys.dm_hadr_availability_replica_states ars
     ON ar.replica_id = ars.replica_id;

6. Verify Listener Connectivity

Connect using the Listener Name and verify the hostname.
It should now route connections to Node2.

7. Validate Database Status and Synchronization Health

select
    ag.name,
    ar.replica_server_name,
    ar.availability_mode_desc as [availability_mode],
    ars.synchronization_health_desc as replica_sync_state,
    rcs.database_name,
    drs.synchronization_state_desc as db_sync_state,
    rcs.is_failover_ready,
    rcs.is_pending_secondary_suspend,
    rcs.is_database_joined
from sys.dm_hadr_database_replica_cluster_states as rcs
join sys.availability_replicas as ar
    on ar.replica_id = rcs.replica_id
join sys.dm_hadr_availability_replica_states as ars
    on ars.replica_id = ar.replica_id
join sys.dm_hadr_database_replica_states as drs
    on drs.group_database_id = rcs.group_database_id
    and drs.replica_id = ar.replica_id
join sys.availability_groups as ag
    on ag.group_id = ar.group_id;
select
    ag.name as aag_name,
    ar.replica_server_name,
    d.name as [database_name],
    hars.is_local,
    hars.synchronization_state_desc as synchronization_state,
    hars.synchronization_health_desc as synchronization_health,
    hars.database_state_desc as db_state,
    hars.is_suspended,
    hars.suspend_reason_desc as suspend_reason,
    hars.last_commit_lsn,
    hars.last_commit_time
from sys.dm_hadr_database_replica_states as hars
join sys.availability_replicas as ar
    on hars.replica_id = ar.replica_id
join sys.availability_groups as ag
    on ag.group_id = hars.group_id
join sys.databases as d
    on d.group_database_id = hars.group_database_id
order by aag_name, replica_server_name;

Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

Add Database to AG

Adding a Database to an Existing SQL Server Always On Availability Group using Backup and Restore Method.

Table of Contents


  1. Verify Prerequisites
  2. Existing Always On Availability Group
  3. Create Database
  4. Set FULL Recovery Model
  5. Create Tables
  6. Insert Sample Data
  7. Verify Data
  8. Take Full Backup on Primary
  9. Transfer Backup to Secondary Replica
  10. Restore Database on Secondary Replica
  11. Add Database to Existing Availability Group
  12. Join Database on Secondary Replica
  13. Verify AG Synchronization Status

Adding a database to an existing Always On Availability Group (AG) allows the database to participate in High Availability and Disaster Recovery along with other databases in the group.

Important:

Automatic seeding streams the entire database over the AG endpoint network. Primary automatically transfers database to secondary, no need to take backup and restore manually. Please make sure grant ALTER AVAILABILITY GROUP [NTICBPSQLSGA05] GRANT CREATE ANY DATABASE; to AG it self, else database will not get create automatically on secondary replica. 

For large production databases (size 100 GB or more), then manual backup and restore is the preferred and more reliable method for seeding the database into the Availability Group.if you are using SEEDING_MODE = AUTOMATIC, when SQL Server detects that the database already exists on the secondary in RESTORING state, it does NOT trigger automatic seeding. Instead, it simply joins the database to the AG automatically.

if you are using SEEDING_MODE = MANUAL, you need to run the below command to join the secondary replica.ALTER DATABASE [TRDPA] SET HADR AVAILABILITY GROUP = [NTICBPSQLSGA05];

1. Verify Prerequisites

- Database must be in FULL recovery model
- A full backup must exist
- A transaction log backup must exist
- Database must not already be part of another AG

2. Existing Always On Availability Group

3. CREATE DATABASE

USE [master];
GO

CREATE DATABASE TRDPA;
GO

4. SET FULL RECOVERY MODEL (MANDATORY FOR AG)

ALTER DATABASE TRDPA SET RECOVERY FULL;
GO

SELECT name, recovery_model_desc FROM sys.databases WHERE name = 'TRDPA';
GO

5. CREATE TABLES

USE [TRDPA];
GO

-- Trade Header Table
CREATE TABLE dbo.TradeHeader (
    TradeID INT IDENTITY(1,1) NOT NULL,
    TradeRef VARCHAR(20) NOT NULL,
    TradeDate DATE NOT NULL,
    SettlementDate DATE NOT NULL,
    TraderName VARCHAR(100) NOT NULL,
    DeskName VARCHAR(50) NOT NULL,
    Status VARCHAR(20) NOT NULL DEFAULT 'PENDING',
    CreatedAt DATETIME2(3) NOT NULL DEFAULT SYSUTCDATETIME(),
    UpdatedAt DATETIME2(3) NOT NULL DEFAULT SYSUTCDATETIME(),
    CONSTRAINT PK_TradeHeader PRIMARY KEY CLUSTERED (TradeID),
    CONSTRAINT CHK_Status CHECK (Status IN ('PENDING','CONFIRMED','SETTLED','CANCELLED'))
);
GO

-- Trade Detail Table
CREATE TABLE dbo.TradeDetail (
    DetailID INT IDENTITY(1,1) NOT NULL,
    TradeID INT NOT NULL,
    Instrument VARCHAR(50) NOT NULL,
    AssetClass VARCHAR(30) NOT NULL,
    Quantity DECIMAL(18,4) NOT NULL,
    Price DECIMAL(18,6) NOT NULL,
    Notional AS (Quantity * Price) PERSISTED,
    Currency CHAR(3) NOT NULL DEFAULT 'USD',
    Direction CHAR(1) NOT NULL,
    CONSTRAINT PK_TradeDetail PRIMARY KEY CLUSTERED (DetailID),
    CONSTRAINT FK_TradeDetail_Header FOREIGN KEY (TradeID)
        REFERENCES dbo.TradeHeader(TradeID),
    CONSTRAINT CHK_Direction CHECK (Direction IN ('B','S'))
);
GO

-- Audit Log Table
CREATE TABLE dbo.AuditLog (
    AuditID INT IDENTITY(1,1) NOT NULL,
    TradeID INT NOT NULL,
    ActionType VARCHAR(20) NOT NULL,
    ActionBy VARCHAR(100) NOT NULL DEFAULT SYSTEM_USER,
    ActionAt DATETIME2(3) NOT NULL DEFAULT SYSUTCDATETIME(),
    OldStatus VARCHAR(20) NULL,
    NewStatus VARCHAR(20) NULL,
    Remarks NVARCHAR(500) NULL,
    CONSTRAINT PK_AuditLog PRIMARY KEY CLUSTERED (AuditID)
);
GO

6. INSERT SAMPLE DATA

-- Trade Headers
INSERT INTO dbo.TradeHeader (TradeRef, TradeDate, SettlementDate, TraderName, DeskName, Status)
VALUES
    ('TRD-2026-00001', '2026-03-01', '2026-03-03', 'John Smith',    'Equities',      'CONFIRMED'),
    ('TRD-2026-00002', '2026-03-03', '2026-03-05', 'Sarah Connor',  'Fixed Income',  'SETTLED'),
    ('TRD-2026-00003', '2026-03-05', '2026-03-07', 'Mike Johnson',  'FX',            'PENDING'),
    ('TRD-2026-00004', '2026-03-07', '2026-03-11', 'Emily Davis',   'Equities',      'CONFIRMED'),
    ('TRD-2026-00005', '2026-03-10', '2026-03-12', 'Raj Patel',     'Commodities',   'PENDING'),
    ('TRD-2026-00006', '2026-03-10', '2026-03-12', 'Lisa Wang',     'FX',            'CANCELLED'),
    ('TRD-2026-00007', '2026-03-11', '2026-03-13', 'Tom Harris',    'Fixed Income',  'PENDING'),
    ('TRD-2026-00008', '2026-03-11', '2026-03-13', 'Anna Brown',    'Equities',      'CONFIRMED');
GO

-- Trade Details
INSERT INTO dbo.TradeDetail (TradeID, Instrument, AssetClass, Quantity, Price, Currency, Direction)
VALUES
    (1, 'AAPL US Equity',      'Equity',       1000.0000,  178.500000, 'USD', 'B'),
    (1, 'MSFT US Equity',      'Equity',        500.0000,  415.250000, 'USD', 'B'),
    (2, 'US10Y Treasury',      'Fixed Income', 2000.0000,   98.750000, 'USD', 'S'),
    (3, 'EUR/USD',             'FX',        1000000.0000,    1.085000, 'USD', 'B'),
    (4, 'TSLA US Equity',      'Equity',        300.0000,  172.900000, 'USD', 'S'),
    (4, 'NVDA US Equity',      'Equity',        200.0000,  875.600000, 'USD', 'B'),
    (5, 'Gold Futures Jun26',  'Commodity',      50.0000, 2185.400000, 'USD', 'B'),
    (6, 'GBP/USD',             'FX',         500000.0000,    1.270000, 'USD', 'S'),
    (7, 'US2Y Treasury',       'Fixed Income', 1500.0000,   99.125000, 'USD', 'B'),
    (8, 'AMZN US Equity',      'Equity',        400.0000,  178.320000, 'USD', 'B');
GO

-- Audit Log
INSERT INTO dbo.AuditLog (TradeID, ActionType, OldStatus, NewStatus, Remarks)
VALUES
    (1, 'STATUS_CHANGE', 'PENDING',   'CONFIRMED', 'Confirmed by risk desk'),
    (2, 'STATUS_CHANGE', 'PENDING',   'CONFIRMED', 'Confirmed by risk desk'),
    (2, 'STATUS_CHANGE', 'CONFIRMED', 'SETTLED',   'Settlement confirmed by ops'),
    (6, 'STATUS_CHANGE', 'PENDING',   'CANCELLED', 'Cancelled - counterparty default');
GO

7. VERIFY DATA

SELECT 
    h.TradeRef,
    h.TradeDate,
    h.TraderName,
    h.DeskName,
    h.Status,
    d.Instrument,
    d.Direction,
    d.Quantity,
    d.Price,
    d.Notional,
    d.Currency
FROM dbo.TradeHeader h
JOIN dbo.TradeDetail d 
ON h.TradeID = d.TradeID
ORDER BY h.TradeDate, h.TradeRef;
GO

8. FULL BACKUP on Primary

A Full Backup contains data pages and enough transaction log to make the database consistent, but it does NOT include all transaction log activity after the backup started.
Therefore we take a separate transaction log backup to maintain the log chain.

BACKUP DATABASE TRDPA 
TO DISK = 'K:\Microsoft SQL Server\TRDPA\TRDPA_full.bak';
GO

BACKUP LOG TRDPA 
TO DISK = 'K:\Microsoft SQL Server\TRDPA\TRDPA_log.trn';
GO

9. Transfer Backup to Secondary Replica(s)

Shared backup location: //Nticbpsqlsgv01/trdpa

Copy backup files from the shared location to secondary servers.

10. Restore Database on Secondary Replica(s)

10.1 Restore on Secondary Replica 1

RESTORE DATABASE TRDPA 
FROM DISK = 'K:\Microsoft SQL Server\TRDPA\TRDPA_full.bak' 
WITH NORECOVERY;

RESTORE LOG TRDPA 
FROM DISK = 'K:\Microsoft SQL Server\TRDPA\TRDPA_log.trn' 
WITH NORECOVERY;

10.2 Restore on Secondary Replica 2

-- Restore Database
RESTORE DATABASE TRDPA FROM DISK = 'K:\Microsoft SQL Server\TRDPA\TRDPA_full.bak' WITH NORECOVERY;

-- Restore LOG
RESTORE LOG TRDPA FROM DISK = 'K:\Microsoft SQL Server\TRDPA\TRDPA_log.trn' WITH NORECOVERY;

11. ADD DATABASE TO EXISTING AG (Primary Server)

ALTER AVAILABILITY GROUP [NTICBPSQLSGA05] ADD DATABASE [TRDPA];

12. Join Database on Secondary Replica(s)

When SQL Server detects that the database already exists on the secondary in RESTORING state, it does NOT trigger automatic seeding. Instead, it simply joins the database to the AG automatically.You only need to run the below command when using Manual Seeding.

ALTER DATABASE [TRDPA] SET HADR AVAILABILITY GROUP = [NTICBPSQLSGA05];
GO

13. VERIFY AG SYNC STATUS

SELECT 
    ag.name AS ag_name,
    ar.replica_server_name,
    db.database_name,
    drs.synchronization_state_desc,
    drs.synchronization_health_desc,
    drs.log_send_queue_size,
    drs.redo_queue_size,
    drs.last_commit_time
FROM sys.availability_groups ag
JOIN sys.availability_replicas ar
    ON ag.group_id = ar.group_id
JOIN sys.dm_hadr_availability_replica_states rs
    ON ar.replica_id = rs.replica_id
JOIN sys.dm_hadr_database_replica_states drs
    ON rs.replica_id = drs.replica_id
JOIN sys.availability_databases_cluster db
    ON drs.group_database_id = db.group_database_id
WHERE db.database_name = 'TRDPA'
ORDER BY ar.replica_server_name;
GO

 

Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

Who is NT AUTHORITY\SYSTEM?

Who is NT AUTHORITY\SYSTEM?

NT AUTHORITY\SYSTEM is the Local System account — a built-in Windows identity. The Windows Server Failover Clustering service (ClusSvc.exe) runs under this identity by default. This means when WSFC (via hadrres.dll) connects to SQL Server, it authenticates as NT AUTHORITY\SYSTEM using Windows Authentication.

Why does WSFC need to log into SQL Server?

Because health monitoring requires actually querying SQL Server internals. WSFC can’t just check if the SQL Server process is running — that’s not enough. It needs to know:

  • Is the AG synchronized?
  • Are there any critical errors?
  • Is the instance responding to queries?

All of that requires a real SQL connection with real permissions.

The Three Grants assigned by default

SELECT 
    pr.name                AS principal_name,
    pr.type_desc           AS principal_type,
    pe.permission_name,
    pe.state_desc          AS grant_state,
    pe.class_desc          AS permission_class
FROM sys.server_permissions pe
JOIN sys.server_principals pr
    ON pe.grantee_principal_id = pr.principal_id
WHERE pr.name = 'NT AUTHORITY\SYSTEM'
ORDER BY pe.permission_name;

-- Grant 1: ALTER ANY AVAILABILITY GROUP
GRANT ALTER ANY AVAILABILITY GROUP TO [NT AUTHORITY\SYSTEM];

This allows WSFC (via the SYSTEM account) to change the state of AGs — for example, changing a replica’s role from secondary to primary during failover. Without this, WSFC could detect a failure but couldn’t actually execute the promotion.

-- Grant 2: CONNECT SQL
GRANT CONNECT SQL TO [NT AUTHORITY\SYSTEM];

This is the basic right to log in to the SQL Server instance at all. Without CONNECT SQL, the Windows login exists but can’t establish a session. It’s the gatekeeper permission.

-- Grant 3: VIEW SERVER STATE
GRANT VIEW SERVER STATE TO [NT AUTHORITY\SYSTEM];

This allows reading Dynamic Management Views (DMVs) like:

  • sys.dm_hadr_availability_replica_states — synchronization state
  • sys.dm_os_ring_buffers — error events
  • sys.dm_exec_requests — active queries

sp_server_diagnostics internally queries many of these DMVs, so this permission is essential for the health check to return meaningful data.

Why not just grant sysadmin?

This is the principle of least privilege in action. sysadmin would work, but it would also allow WSFC to read any data, modify any configuration, drop any database, etc. The three specific grants give WSFC exactly what it needs and nothing more. If the SYSTEM account were ever misused or compromised at the OS level, the blast radius on SQL Server is limited.

Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

Windows Server 2022 Failover Cluster

Windows Server 2022 Failover Cluster using PowerShell
for SQL Server Always On Availability Groups

Table of Contents



0. Environment

NodeHostnameIP Address
DB Node 1NTICBPSQLSGV01192.168.2.21
DB Node 2NTICBPSQLSGV02192.168.2.22
DB Node 3NTICBPSQLSGV03192.168.2.23
DB Node 4NTICBPSQLSGV04192.168.2.24
Cluster NameNTICBPSQLSGC05192.168.2.25
DCDC01192.168.2.20

1. Prerequisites

  • All four servers must run Windows Server 2022.
  • All servers must be joined to the same Active Directory domain.
  • Ensure proper DNS name resolution between all nodes.
  • Verify network connectivity and configure static IP addresses.
  • Install the latest Windows updates and vendor drivers.

2. Install Failover Clustering Feature

Run the following command on each node as Administrator.

On NTICBPSQLSGV01

PS C:\Users\Administrator> Install-WindowsFeature -Name Failover-Clustering -IncludeManagementTools                     
Success Restart Needed Exit Code      Feature Result
------- -------------- ---------      --------------
True    No             Success        {Failover Clustering, Remote Server Admini...


PS C:\Users\Administrator> hostname
NTICBPSQLSGV01
PS C:\Users\Administrator>
PS C:\Users\Administrator> Get-WindowsFeature -Name Failover-Clustering

Display Name                                            Name                       Install State
------------                                            ----                       -------------
[X] Failover Clustering                                 Failover-Clustering            Installed

PS C:\Users\Administrator>

On NTICBPSQLSGV02

PS C:\Users\Administrator> Install-WindowsFeature -Name Failover-Clustering -IncludeManagementTools                     
Success Restart Needed Exit Code      Feature Result
------- -------------- ---------      --------------
True    No             Success        {Failover Clustering, Remote Server Admini...


PS C:\Users\Administrator> hostname
NTICBPSQLSGV02
PS C:\Users\Administrator> Get-WindowsFeature -Name Failover-Clustering

Display Name                                            Name                       Install State
------------                                            ----                       -------------
[X] Failover Clustering                                 Failover-Clustering            Installed


PS C:\Users\Administrator>

On NTICBPSQLSGV03

PS C:\Users\Administrator> Install-WindowsFeature -Name Failover-Clustering -IncludeManagementTools                     
Success Restart Needed Exit Code      Feature Result
------- -------------- ---------      --------------
True    No             Success        {Failover Clustering, Remote Server Admini...


PS C:\Users\Administrator> hostname
NTICBPSQLSGV03
PS C:\Users\Administrator> Get-WindowsFeature -Name Failover-Clustering

Display Name                                            Name                       Install State
------------                                            ----                       -------------
[X] Failover Clustering                                 Failover-Clustering            Installed

PS C:\Users\Administrator>

On NTICBPSQLSGV04

PS C:\Users\Administrator> Install-WindowsFeature -Name Failover-Clustering -IncludeManagementTools                     
Success Restart Needed Exit Code      Feature Result
------- -------------- ---------      --------------
True    No             Success        {Failover Clustering, Remote Server Admini...


PS C:\Users\Administrator> hostname
NTICBPSQLSGV04
PS C:\Users\Administrator> Get-WindowsFeature -Name Failover-Clustering

Display Name                                            Name                       Install State
------------                                            ----                       -------------
[X] Failover Clustering                                 Failover-Clustering            Installed


PS C:\Users\Administrator>
✔ Failover Clustering feature installed successfully on all nodes.

 

3. Import Cluster Module and Validate Cluster Configuration

On NTICBPSQLSGV01

Load the Windows Failover Clustering PowerShell module into your current PowerShell session.
Run validation before creating the cluster:

On NTICBPSQLSGV01:

PS C:\Users\Administrator> hostname
NTICBPSQLSGV01
PS C:\Users\Administrator> Import-Module FailoverClusters
PS C:\Users\Administrator>

PS C:\Users\Administrator> Test-Cluster -Node NTICBPSQLSGV01,NTICBPSQLSGV02,NTICBPSQLSGV03,NTICBPSQLSGV04
WARNING: System Configuration - Validate Software Update Levels: The test reported some warnings..
WARNING: Network - Validate Network Communication: The test reported some warnings..
WARNING:
Test Result:
HadUnselectedTests, ClusterConditionallyApproved
Testing has completed for the tests you selected. You should review the warnings in the Report.  A cluster solution is
supported by Microsoft only if you run all cluster validation tests, and all tests succeed (with or without warnings).
Test report file path: C:\Users\Administrator\AppData\Local\Temp\2\Validation Report 2025.12.29 At 18.28.44.htm

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        12/29/2025   6:34 PM        1346352 Validation Report 2025.12.29 At 18.28.44.htm


PS C:\Users\Administrator>

Note: Warnings are acceptable, but errors must be resolved.
Always review the cluster validation report.

 

4. Create the Cluster

New-Cluster `
 -Name NTICBPSQLSGC05 `
 -Node NTICBPSQLSGV01,NTICBPSQLSGV02,NTICBPSQLSGV03,NTICBPSQLSGV04 `
 -StaticAddress 192.168.2.25 `
 -NoStorage

PS C:\Users\Administrator> New-Cluster `
>>  -Name NTICBPSQLSGC05 `
>>  -Node NTICBPSQLSGV01,NTICBPSQLSGV02,NTICBPSQLSGV03,NTICBPSQLSGV04 `
>>  -StaticAddress 192.168.2.25 `
>>  -NoStorage

Name
----
NTICBPSQLSGC05


PS C:\Users\Administrator>
✔ Cluster NTICBPSQLSGC05 created successfully.

 

5. Verify Cluster Configuration

Cluster Name

PS C:\Users\Administrator> Get-Cluster

Name
----
NTICBPSQLSGC05


PS C:\Users\Administrator>

Cluster Nodes

PS C:\Users\Administrator> Get-ClusterNode

Name           State Type
----           ----- ----
NTICBPSQLSGV01 Up    Node
NTICBPSQLSGV02 Up    Node
NTICBPSQLSGV03 Up    Node
NTICBPSQLSGV04 Up    Node


PS C:\Users\Administrator>

Cluster Resources

PS C:\Users\Administrator> Get-ClusterResource

Name               State  OwnerGroup    ResourceType
----               -----  ----------    ------------
Cluster IP Address Online Cluster Group IP Address
Cluster Name       Online Cluster Group Network Name


PS C:\Users\Administrator>

Cluster Network

PS C:\Users\Administrator> Get-ClusterNetwork | Format-Table Name, Address, Role, State

Name              Address                 Role State
----              -------                 ---- -----
Cluster Network 1 192.168.2.0 ClusterAndClient    Up


PS C:\Users\Administrator>
✔ All cluster components are online and healthy.

6. Add Witness

In this test lab environment, the File Share Witness (FSW) is hosted on the Domain Controller (DC).

Using a Domain Controller as File Share Witness is NOT recommended for production.

  • In production, the File Share Witness should be hosted on:
    • A dedicated file server
    • Azure Cloud Witness (recommended)
  • The witness folder must have Full Control for:
    • The Windows Failover Cluster computer object
    • SQL Server Always On cluster name object
       

Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

Log Shipping (SQL Server 2022)

Log Shipping – SQL Server 2022 (Complete Guide)

Table of Contents


  1. Overview
  2. Oracle Data Guard vs SQL Server Log Shipping
  3. Log Shipping Architecture
  4. Environment Details
  5. Prerequisites
  6. Step-by-Step Configuration
  7. Verification & Testing

Log Shipping (SQL Server 2022)

Overview

Log Shipping copies transaction log backups from the Primary server to one or more Secondary servers and restores them, keeping databases synchronized for Disaster Recovery (DR) or Read-Only Reporting scenarios.

Oracle Data Guard vs SQL Server Log Shipping

Oracle Data Guard
Redo transport is internal, continuous, and process-driven (LGWR → RFS → MRP).

SQL Server Log Shipping
Log transport is external, file-based, and job-driven (Backup → Copy → Restore).

Log Shipping Architecture

Log Shipping is a disaster recovery (DR) solution where:

  • Primary Server takes transaction log backups and saves them to a shared network path.
  • Secondary Server copies and restores those logs (STANDBY or NORECOVERY mode).
  • No shared storage is required — only T-Log backups over a network share.

Environment Details

ItemPrimarySecondary
HostnameSGMSQL1SGMSQL2
SQL Server VersionSQL Server 2022SQL Server 2022
SQL EditionEnterprise / StandardEnterprise / Standard
SQL Server Log on AsRAJASEKHAR\MSAPGEBSGSQL$RAJASEKHAR\MSAPGEBSGSQL$
Instance NameMSSQLSERVERMSSQLSERVER
Database NameSALESSALES
Recovery ModelFULLFULL
DR LocationDC / Region 1DR / Region 2
T-Log Backup Path\\SGMSQL1\Backup_LogShip
Copy Destination PathN/AD:\LogShipping\Copy

Prerequisites

  • SQL Server 2022 Standard or Enterprise
  • Same database name (collation recommended to be same)
  • Database must be in FULL recovery model
  • SQL Server Agent must be running on Primary & Secondary
  • Service accounts must have Read/Write access to the shared folder

Step-by-Step Configuration

Step 1: Prepare the Primary Database

Right-click database → Properties → Options → Set Recovery Model = FULL.

Recovery Model

Take a full database backup.

Full Backup

Step 2: Enable Log Shipping

Database → Properties → Transaction Log Shipping →
Enable this as a primary database.

Enable Log Shipping

Step 3: Configure Backup Settings

  • Network path
  • Local backup folder (if you are storing Tlog Backups in local drive )
  • Backup job schedule (e.g. every 5 minutes)

Backup Settings

Step 4: Add Secondary Database

Initialize Secondary → Restore from backup (recommended).

Initialize Secondary

Configure Copy and Restore jobs.

Copy Job
Restore Job

Step 5: Finish Configuration

Click OK. SQL Server will automatically create all required jobs.

Finish

Verification & Testing

Jobs will be created automatically:

  • Primary: LSBackup_SALES, LSAlert_SGMSQL1
  • Secondary: LSCopy, LSRestore, LSAlert_SGMSQL2

Secondary database should be in Standby / Read-Only mode.

Standby Mode

Testing

Create a table on Primary and verify it appears on Secondary after restore.

On Primary :

On Standby : (After 5 Minutes)

Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

Sql Server Basics For Oracle Dbas

SQL Server Basics

Concise comparisons and practical snippets so you can learn from Oracle to SQL Server with confidence.

1. SQL Server: Instance vs Database

SQL Server: An instance is the running database server (a service). Each instance can host multiple databases.
A database inside SQL Server contains its own data and log files.

Oracle: Typical Oracle deployment ties a single database to an instance (SGA + background processes). With Multitenant you can have many PDBs inside a CDB.

SQL Server

  • Many databases per instance
  • Service-based architecture (MSSQLSERVER or named instance)
  • Files: MDF (data), LDF (log), NDF (secondary)

Oracle

  • Traditionally 1 DB per instance (CDB/PDB changes this model)
  • Memory structures (SGA/PGA) + background processes (DBWR, LGWR)
  • Files: Datafiles, Redo logs, Control files

2. SQL Server Editions (Quick Comparison)

Choose edition based on features and budget. As an Oracle DBA, map them roughly like this:

SQL ServerOracleNotes
ExpressOracle XEFree; good for labs and demos
StandardStandard EditionMost production needs
EnterpriseEnterprise EditionAdvanced HA, performance features

3. System Databases Explained

SQL Server automatically creates a set of system databases that store instance-level metadata and runtime state.

DatabasePurposeOracle Equivalence
masterInstance-level metadata, logins, configData dictionary + SPFILE
modelTemplate for new DBs(No direct Oracle equivalent)
msdbAgent jobs, backup history, alertsScheduler + RMAN catalog
tempdbTemporary objects & workspace (re-created at startup)TEMP tablespace, some UNDO functionality overlaps
mssqlsystemresource (resource)Hidden read-only system objectsContained in Oracle binaries

Tip: Monitor tempdb closely — it’s a common bottleneck for SQL Server workloads.

4. SQL Server Files: MDF, LDF, NDF

SQL Server separates data and log storage:

  • MDF — primary data file
  • NDF — secondary data file(s) — Optional
  • LDF — transaction log file

Oracle maps these to datafiles (for data) and redo logs (for transaction logging).

-- Example: Add a data file in SQL Server
ALTER DATABASE MyDB
ADD FILE (NAME = MyDB_Data2, FILENAME = 'D:\\MSSQL\\DATA\\MyDB_Data2.ndf', SIZE = 512MB);

-- Example: Add a log file
ALTER DATABASE MyDB
ADD LOG FILE (NAME = MyDB_Log2, FILENAME = 'E:\\MSSQL\\LOG\\MyDB_Log2.ldf', SIZE = 256MB);

5. Authentication: Windows vs SQL Logins

SQL Server supports two primary authentication modes:

  1. Windows Authentication — Uses Active Directory; preferred for security.
  2. SQL Server Authentication — Username/password stored in SQL Server (use strong passwords).

Oracle typically uses database accounts or external authentication (LDAP/OS), but SQL Server’s tight AD integration is a major difference.

6. Indexes in SQL Server (vs Oracle)

Common SQL Server index types:

  • Clustered Index — The table rows are stored in index order (only one per table). Similar to Oracle’s Index-Organized Table (IOT).
  • Non-Clustered Index — Like Oracle B-tree indexes.
  • Columnstore Index — Columnar storage for analytics (similar goal to Oracle In-Memory).

Example: Create a non-clustered index

CREATE NONCLUSTERED INDEX IX_MyTable_Col
ON dbo.MyTable (Col);

7. High-level Architecture Differences

Key comparisons:

AreaSQL ServerOracle
MemoryBuffer Pool, Plan CacheSGA, PGA
ProcessesServices (no separate background DB procs)BG procs: DBWR, LGWR, CKPT, PMON, SMON
Storage unitPage = 8KB (default)Block (variable, often 8KB)

8. What is SQL Server Agent?

SQL Server Agent is the built-in job scheduler used for:

  • Backups
  • Maintenance tasks
  • Custom automation (scripts, SSIS jobs)

Oracle equivalent: DBMS_SCHEDULER and external cron/RMAN scripts.

-- Example: Create a simple SQL Agent job (T-SQL to create job requires msdb context and stored procedures)
-- Use SQL Server Management Studio UI for easiest job creation.

9. Backup Types: Full, Differential, Log

SQL Server supports:

  • Full backups
  • Differential backups (changes since last full)
  • Transaction log backups (for point-in-time recovery)

These map to Oracle RMAN concepts—use log backups (archive) for point-in-time restores.

-- Example: Take a full backup to disk
BACKUP DATABASE MyDB TO DISK = 'E:\\backups\\MyDB_full.bak' WITH INIT;

-- Transaction log backup
BACKUP LOG MyDB TO DISK = 'E:\\backups\\MyDB_log.trn';

10. SQL Server DBA Daily Checklist

  1. Check SQL Agent job failures (msdb.dbo.sysjobhistory)
  2. Verify backups completed and test restore regularly
  3. Monitor disk space on data and log drives
  4. Check errorlog for critical errors (sp_readerrorlog)
  5. Look for blocking sessions and long-running queries
  6. Monitor CPU, memory, and I/O waits

Quick query to find top CPU consuming queries:

SELECT TOP 10 qs.total_elapsed_time/qs.execution_count AS avg_elapsed_ms,
       qs.execution_count, SUBSTRING(qt.text, (qs.statement_start_offset/2)+1,
       ((CASE qs.statement_end_offset
          WHEN -1 THEN DATALENGTH(qt.text)
          ELSE qs.statement_end_offset
        END - qs.statement_start_offset)/2) + 1) AS statement_text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
ORDER BY avg_elapsed_ms DESC;

 

Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. Ensure that you test it in a non-production environment before applying.

Thank you,

Rajasekhar Amudala

Email: br8dba@gmail.com

LinkedIn: https://www.linkedin.com/in/rajasekhar-amudala/

Restore Database without Tail Backup

MS SQL SERVER – Restore & Recover Database without Tail Backup

Table of Contents
___________________________________________________________________________________________________

Pre-requisites

0. Verify Recovery Model
1. Take Full Database Backup
2. Create Table DBA and Insert some data
3. Take T-LOG Backup
4. Insert into table DBA
5. Take T-LOG Backup
6. Insert into table DBA
7. Take T-LOG Backup
8. Insert into table DBA
9. Take Differential Database Backup
10. Insert into table DBA
11. Capture Table DBA total rows — 10 Rows
12. Take T-Log Backup

Backup Validation

13. List Backup
14. Validate Backup – RESTORE VERIFYONLY
15. Check contents of backup – RESTORE HEADERONLY

Delete Database — Test Simulation – Don’t try in office machines

16. Using SSMS (GUI)
17. Using T-SQL

Restore & Recover Database

18. Restore & Recover Database using SSMS (GUI)
19. Restore Database using T-SQL (WITH NO RECOVERY)
20. Recover Database using T-SQL (WITH RECOVERY)
21. Verify Table DBA total rows – 10 Rows

___________________________________________________________________________________________________


Pre-requisites


0. Verify Recovery Model

SELECT name AS [Database Name],recovery_model_desc AS [Recovery Model] FROM sys.databases where name = 'TEST'
GO



1. Take Full Database Backup

BACKUP DATABASE [TEST] 
TO DISK = N'H:\DB_BACKUP\TEST_NEW\FULL_DB_BACKUP_TEST_261120.bak' 
WITH NAME = N'FULL DATABASE BACKUP - TEST',STATS 
GO


2. Create Table DBA and Insert some data

-- create table DBA
CREATE TABLE DBA 
(
NAME	VARCHAR(10),
ROLE	VARCHAR(10)
);
GO
-- Insert data to table 
INSERT INTO DBA VALUES ('SUGI','DBA');
INSERT INTO DBA VALUES ('TEJA','DBA');
INSERT INTO DBA VALUES ('BALA','DBA');
INSERT INTO DBA VALUES ('SURENDAR','DBA');



3. Take T-LOG Backup

BACKUP LOG [TEST] 
TO DISK = N'H:\DB_BACKUP\TEST_NEW\DB_BACKUP_TEST_TLOG_261120.bak' 
WITH NAME= N'T-LOG BACKUP FOR DATABASE TEST',STATS 
GO


4. Insert into table DBA

INSERT INTO DBA VALUES ('SREERAM','INFRA');



5. Take T-LOG Backup

BACKUP LOG [TEST] 
TO DISK = N'H:\DB_BACKUP\TEST_NEW\DB_BACKUP_TEST_TLOG_261120.bak' 
WITH NAME= N'T-LOG BACKUP FOR DATABASE TEST',STATS 
GO


6. Insert into table DBA

INSERT INTO DBA VALUES ('PAVAN','HADOOP');



7. Take T-LOG Backup

BACKUP LOG [TEST] 
TO DISK = N'H:\DB_BACKUP\TEST_NEW\DB_BACKUP_TEST_TLOG_261120.bak' 
WITH NAME= N'T-LOG BACKUP FOR DATABASE TEST',STATS 
GO


8. Insert into table DBA

INSERT INTO DBA VALUES ('SRINIVAS','MW');



9. Take Differential Database Backup

BACKUP DATABASE [TEST] 
TO DISK = N'H:\DB_BACKUP\TEST_NEW\DIFF_DB_BACKUP_TEST_261120.bak' 
WITH DIFFERENTIAL,NOINIT, NAME = N'DIFFERENTIAL BACKUP TEST DATABASE',STATS 
GO


10. Insert into table DBA

INSERT INTO DBA VALUES ('RAVI','DEV');
INSERT INTO DBA VALUES ('RAMESH','DBA');
INSERT INTO DBA VALUES ('SRINIVAS','DBA');


11. Capture Table DBA total rows — 10 Rows




12. Take T-Log Backup

BACKUP LOG [TEST] 
TO DISK = N'H:\DB_BACKUP\TEST_NEW\DB_BACKUP_TEST_TLOG_261120.bak' 
WITH NAME= N'T-LOG BACKUP FOR DATABASE TEST',STATS 
GO


Backup Validation

13. List Backup

-- List all database backups from last week.

SELECT 
CONVERT(CHAR(100), SERVERPROPERTY('Servername')) AS Server, 
msdb.dbo.backupset.database_name, 
msdb.dbo.backupset.backup_start_date, 
msdb.dbo.backupset.backup_finish_date, 
msdb.dbo.backupset.expiration_date, 
CASE msdb..backupset.type 
WHEN 'D' THEN 'Database' 
WHEN 'L' THEN 'Log' 
END AS backup_type, 
msdb.dbo.backupset.backup_size, 
msdb.dbo.backupmediafamily.logical_device_name, 
msdb.dbo.backupmediafamily.physical_device_name, 
msdb.dbo.backupset.name AS backupset_name, 
msdb.dbo.backupset.description 
FROM msdb.dbo.backupmediafamily 
INNER JOIN msdb.dbo.backupset ON msdb.dbo.backupmediafamily.media_set_id = msdb.dbo.backupset.media_set_id 
WHERE (CONVERT(datetime, msdb.dbo.backupset.backup_start_date, 102) >= GETDATE() - 7) 
ORDER BY 
msdb.dbo.backupset.database_name, 
msdb.dbo.backupset.backup_finish_date 



14. Validate Backup – RESTORE VERIFYONLY

--Verify Full Backup
RESTORE VERIFYONLY FROM DISK = 'H:\DB_BACKUP\TEST_NEW\FULL_DB_BACKUP_TEST_261120.bak'; 
-- Verify Diff Backup
RESTORE VERIFYONLY FROM DISK = 'H:\DB_BACKUP\TEST_NEW\DIFF_DB_BACKUP_TEST_261120.bak'; 
-- Verify T-LOG Backup 
RESTORE VERIFYONLY FROM DISK = 'H:\DB_BACKUP\TEST_NEW\DB_BACKUP_TEST_TLOG_261120.bak'; 


15. Check contents of backup – RESTORE HEADERONLY


--Check Contents - Full Backup
RESTORE HEADERONLY FROM DISK = 'H:\DB_BACKUP\TEST_NEW\FULL_DB_BACKUP_TEST_261120.bak'; 
--Check Contents - Diff Backup
RESTORE HEADERONLY FROM DISK = 'H:\DB_BACKUP\TEST_NEW\DIFF_DB_BACKUP_TEST_261120.bak'; 
--Check Contents - T-LOG Backup 
RESTORE HEADERONLY FROM DISK = 'H:\DB_BACKUP\TEST_NEW\DB_BACKUP_TEST_TLOG_261120.bak'; 



Delete Database — Test Simulation – Don’t try in office machines


16. Using SSMS (GUI)








17. Using T-SQL

Drop database TEST;




Restore & Recover Database


18. Restore & Recover Database using SSMS (GUI)


















19. Restore Database using T-SQL (WITH NO RECOVERY)

-- drop database test
DROP DATABASE TEST;





-- Restore Database from FULL DB Backup
RESTORE DATABASE TEST 
FROM DISK = N'H:\DB_BACKUP\TEST_NEW\FULL_DB_BACKUP_TEST_261120.bak'
WITH FILE = 1,
NORECOVERY,
NOUNLOAD,
STATS = 5
GO



-- Restore Database from LAST DATABASE DIFFERENTIAL BACKUP
RESTORE DATABASE TEST 
FROM DISK = N'H:\DB_BACKUP\TEST_NEW\DIFF_DB_BACKUP_TEST_261120.bak'
WITH
NORECOVERY,
NOUNLOAD,
STATS = 5
GO


20. Recovery Database using T-SQL (WITH RECOVERY)

-- Recover Database using T-LOG Which was taken after LAST DB DEFFERENTAIL Backup 


-- DB Differential Backups always Cumulative (It will take backup from Last Full backup only, Not from Last Cumulative Backup)

No need to use T-LOG FILES 1,2 and 3 for recovery, because we took DB Differential Backup before T-LOG (4th time backup). Hence we need T-LOG File 4 only required for recovery. T-LOG 1,2 and 3 No more required.



RESTORE LOG TEST 
FROM DISK=N'H:\DB_BACKUP\TEST_NEW\DB_BACKUP_TEST_TLOG_261120.bak'
WITH FILE = 4,
RECOVERY,
NOUNLOAD,
STATS = 5
GO


21. Verify Table DBA total rows – 10 Rows


Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

Database Backup-FULL-DIFFERENTIAL-TLOG

MS SQL – Database Backup

Table of Contents
___________________________________________________________________________________________________

1. What is Full Database Backup

2. What is Differential Database Backup

3. What is Transaction Log Backup

4. Verify Recovery Model for Database

5. How to Take Full Database Backup

a) Using SSMS (GUI)
b) Using T-SQL

6. How to Take Differential Database Backup

a) Using SSMS (GUI)
b) Using T-SQL

7. How to Take Transaction Log Backup (T-LOG)

a) Using SSMS (GUI)
b) Using T-SQL

8. List Backup

9. Validate Backup – RESTORE VERIFYONLY

10. Check contents of backup – RESTORE HEADERONLY

___________________________________________________________________________________________________


1. How to Take Full Database Backup

This backs up the whole database. 
In order to have further differential or transaction log backups you have to create the full database backup first.

Syntax:

BACKUP DATABASE [DBNAME] TO DISK = N'H:\DB_BACKUP\FULL_DB_BACKUP_TEST.bak' WITH NAME = N'FULL DATABASE BACKUP - DBNAME',STATS 
GO


2. What is Differential Database Backup

Differential database backups are cumulative. This means that each differential database backup backs up the all the changes from the last Full database backup and NOT last Differential backup.

Syntax:

BACKUP DATABASE [DBNAME] TO DISK = N'H:\DB_BACKUP\FULL_DB_BACKUP_TEST.bak' WITH DIFFERENTIAL,NOINIT, NAME = N'DIFFERENTIAL BACKUP DBNAME DATABASE',STATS 
GO


3. What is Transaction Log Backup

It takes complete transaction log file 

Syntax:

BACKUP LOG [DBNAME] TO DISK = N'H:\DB_BACKUP\FULL_DB_BACKUP_TLOG.bak' WITH NAME= N'T-LOG BACKUP FOR DATABASE DBNAME',STATS 
GO


4. Verify Recovery Model for Database

SELECT name AS [Database Name],recovery_model_desc AS [Recovery Model] FROM sys.databases
GO



5. How to Take Full Database Backup

a) Using SSMS (GUI)

      


b) Using T-SQL

BACKUP DATABASE [TEST] TO DISK = N'H:\DB_BACKUP\TEST_BKP\FULL_DATABASE_BACKUP_TEST.bak' WITH NAME = N'FULL DATABASE BACKUP - TEST',STATS 
GO




6. How to Take Differential Database Backup

a) Using SSMS (GUI)










b) Using T-SQL

BACKUP DATABASE [TEST] TO DISK = N'H:\DB_BACKUP\TEST_BKP\FULL_DATABASE_BACKUP_TEST.bak' WITH DIFFERENTIAL,NOINIT, NAME = N'DIFFERENTIAL BACKUP TEST DATABASE',STATS 
GO




7. How to Take Transaction Log Backup (T-LOG)

a) Using SSMS (GUI)















b) Using T-SQL

BACKUP LOG [TEST] TO DISK = N'H:\DB_BACKUP\TEST_BKP\TEST_DB_BACKUP_TLOG.bak' WITH NAME= N'T-LOG BACKUP FOR DATABASE TEST',STATS 
GO




8. List Backup

-- List all database backups from last week.

SELECT 
CONVERT(CHAR(100), SERVERPROPERTY('Servername')) AS Server, 
msdb.dbo.backupset.database_name, 
msdb.dbo.backupset.backup_start_date, 
msdb.dbo.backupset.backup_finish_date, 
msdb.dbo.backupset.expiration_date, 
CASE msdb..backupset.type 
WHEN 'D' THEN 'Database' 
WHEN 'L' THEN 'Log' 
END AS backup_type, 
msdb.dbo.backupset.backup_size, 
msdb.dbo.backupmediafamily.logical_device_name, 
msdb.dbo.backupmediafamily.physical_device_name, 
msdb.dbo.backupset.name AS backupset_name, 
msdb.dbo.backupset.description 
FROM msdb.dbo.backupmediafamily 
INNER JOIN msdb.dbo.backupset ON msdb.dbo.backupmediafamily.media_set_id = msdb.dbo.backupset.media_set_id 
WHERE (CONVERT(datetime, msdb.dbo.backupset.backup_start_date, 102) >= GETDATE() - 7) 
ORDER BY 
msdb.dbo.backupset.database_name, 
msdb.dbo.backupset.backup_finish_date 




9. Validate Backup – RESTORE VERIFYONLY

RESTORE VERIFYONLY FROM DISK = 'H:\DB_BACKUP\TEST_BKP\FULL_DATABASE_BACKUP_TEST.bak'; 
RESTORE VERIFYONLY FROM DISK = 'H:\DB_BACKUP\TEST_BKP\TEST_DB_BACKUP_TLOG.bak'; 


10. Check contents of backup – RESTORE HEADERONLY

RESTORE HEADERONLY FROM DISK = 'H:\DB_BACKUP\TEST_BKP\FULL_DATABASE_BACKUP_TEST.bak'; 
RESTORE HEADERONLY FROM DISK = 'H:\DB_BACKUP\TEST_BKP\TEST_DB_BACKUP_TLOG.bak'; 

Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

 

SQL Server – Recovery Models

MS SQL Server – Recovery models

Table of Contents
___________________________________________________________________________________________________

1. Types of Recovery Models

i) Simple recovery model            – Full and Differential backup
ii) Bulk-logged recovery model – Full, differential and log backup
iii) Full recovery model                 – Full, differential and log backup

2. Find recovery model
a) Using SSMS (GUI)
b) Using T-SQL

3. Change Recovery model
a) Using SSMS (GUI)
b) Using T-SQL

___________________________________________________________________________________________________


1. Types of Recovery Models

i) Simple recovery model

-- Simple recovery model every transaction will be logged into the transaction log file, but at regular intervals the transaction log file will be TRUNCATED whenever a CHECKPOINT operation occurs. 
-- Generally used in Development environment where Database Priority/Point-in-time priority is less
-- Not supported Transaction log backups
-- No Point-in-time recovery possible
-- Data loss chances are more


ii) Bulk-logged recovery model


-- In Bulk-logged recovery model every transaction will be logged into the transaction log file, but bulk insert operations are minimally logged.
-- Supports transaction log backups 
-- No automatic Truncate of Transaction log.
-- Chances of data loss if bulk insert operations fail
-- May or may not be possible to perform point-in-time recovery
-- Disk consumption will be high when normal transactions but in bulk Disk consumption will be low

iii) Full recovery model

-- In FULL recovery model every transaction will be logged into the transaction log file. 
-- This recovery model is generally used in Production databases
-- Supports transaction log backups 
-- No automatic Truncate of Transaction log.
-- Minimal/No Data Loss. 
-- Point-in-time Recovery
-- Performance Overhead and large transactions at times can take more time.
-- The downside of this model is that it can consume a lot of disk space very fast.
-- Make sure setup regular T-Log Backup, so that after T-Log backup it will truncate T-Log (space will be released)


2. Find recovery model

a) Using SSMS (GUI)

TEST (Database) -- Right Click --- Properties

b) Using T-SQL

USE master;
GO
select [name], DATABASEPROPERTYEX([name],'recovery') As RecoveryModel
from sysdatabases
where name  in ('master','model','tempdb','msdb','test')
GO


3. Change Recovery model

a) Using SSMS (GUI)


b) Using T-SQL

-- SET RECOVERY MODEL TO FULL
USE MASTER;
GO
ALTER DATABASE TEST SET RECOVERY FULL;
GO







-- SET RECOVERY MODEL TO SIMPLE
USE MASTER;
GO
ALTER DATABASE TEST SET RECOVERY SIMPLE;
GO

 

Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

Authentication Method

Authentication Method

We recommend users to run their SQL Server with mixed authentication mode. To inspect the authentication mode of your SQL Server, follow screen shots below.

Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
WhatsApp : +
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

Allow Remote Connection

Allow Remote Connection

Your need to make sure that remote connection to your SQL Server is enabled. To verify this setting follow the screen shots below.


 

Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
WhatsApp : +
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

Enable TCP/IP Connection

Enable TCP/IP Connection

To check whether your server enabled to TCP/IP connections

Open SQL Server Configuration Manager and Follow screen shots.

Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
WhatsApp : +
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

Install Only SQL Server Management Studio

How to Install Only SQL Server Management Studio 2014

Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
WhatsApp : +
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

Install Microsoft SQL Server Express 2014

Steps to Install Microsoft SQL Server Express 2014

Before you start, it’s highly recommend to check hardware and software requirements for Installing SQL Server 2014

Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com
WhatsApp : +
Linkedin: https://www.linkedin.com/in/rajasekhar-amudala/

Create Database using GUI

Create Database using the SQL Server Management Studio GUI

SQL Server Version: 2016

1. Click on SQL Server Management Studio GUI



2. Login



3. Create New Database

Ensure that the correct server is expanded in the Object Explorer.









Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.

Thank you,
Rajasekhar Amudala
Email: br8dba@gmail.com