0% found this document useful (0 votes)
0 views68 pages

Ms SQL Query

The document outlines the roles and responsibilities of a Microsoft SQL Server DBA and Azure SQL DBA, detailing tasks such as installations, configurations, security, and performance tuning. It also provides an overview of data and databases, including the differences between RDBMS and NoSQL products, SQL Server versions, and patching processes. Additionally, it describes various SQL Server editions, their features, and limitations, along with a comparison of their capabilities.

Uploaded by

Preetam Sunku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views68 pages

Ms SQL Query

The document outlines the roles and responsibilities of a Microsoft SQL Server DBA and Azure SQL DBA, detailing tasks such as installations, configurations, security, and performance tuning. It also provides an overview of data and databases, including the differences between RDBMS and NoSQL products, SQL Server versions, and patching processes. Additionally, it describes various SQL Server editions, their features, and limitations, along with a comparison of their capabilities.

Uploaded by

Preetam Sunku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Microsoft SQL Server DBA/Azure SQL DBA

• Developer
o Programming
Stored procedures
Functions
Triggers
Cursors

DBA- Database Administrator


o No programming, but need to learn few commands
o Installations and Configurations
o Patching (SPs, CUs and Hot Fixes)
o Security
o Backup/Recovery
o Migrations/Up gradations
o High Availability Solutions
Log shipping
DB Mirroring
Replication
Clustering
Always-On
o Performance tuning
o Azure SQL
Day to Day DBA Responsibilities:
o Health check monitoring
SQL service status
Database status
Job Failures
Backup issues
Maintenance issues
Disk space related issues.
Performance metrics
o Responding to Tickets (incident, service request, problem)
Remedy/Service Now
P1, P2, P3 and P4
SLA
• P1 – 4 hours
• P2 – 8 hours
• P3 – 4 days
• P4 - 8 days
o Implementing Changes
Patching
Migrations
HA setup
Code deployments
Users creations
o Maintenance
Backups
Index Maintenance
Disk Space maintenance
Integrity checks
What is Data?
• Collection of facts, figures and values from the different sources
• Collection of information can be easily accessed, managed and updated
• Information of the users like user id, passwords etc
• Collection of information from different sources
• Collection of related information
Examples:
• Employee information in a organization/company
• Patients/doctors information in a hospital
• Customers information in a bank
• Student’s information in a school/college
• Adhar information
Database:
A media to store the data and to manipulate the data
DBMS – Database Management system
• HDBMS – Hierarchical Database Management system
• NDBMS – Network Database Management System
• RDBMS – Relational database management System
A relational DBMS (RDBMS) stores data in a tabular form where a column represents a property
and each row in a table represents a record.

RDBMSs allow Create, Read, Update, and Delete (CRUD) operations. Structured Query
Language (SQL) is the language that is used to query, update, and delete data in relational
database management systems (RDBMS). SQL is a standard query language. SQL language’s
queries are also known as SQL commands or SQL statements.

RDBMS Products:
1. SQL Server – Mircosoft, licensed
2. Oracle – Oracle Corporation , licensed
3. DB2 – IBM, Licensed
4. Sybase – SAP, Licensed
5. MySQL – Oracle (open source)
6. MariaDB – Open source
7. PostgreSQL – Open source
8. Green plum – Greenplum, License
9. Informix
10. Azure SQL
11. AWS RDS
12. Amazon Aurora
13. CloudSQL – GCP
NoSQL Products: (Not Only SQL)
• Mongo DB
• Cassandra
• BigData Hadoop
• CouchDB
SQL Server History:
SQL Server was originally developed by Sybase corporation.. Then Sybase approached
Microsoft to take it to the market

SQL Server Versions:


SQL Server is compatible with all the operating systems like Windows, Linux, Solaris Unix.. Etc
SQL Server 1.0
SQL Server 2.0
SQL Server 3.0
SQL Server 4.0
SQL Server 5.0
SQL Server 6.0
SQL Server 6.5
Microsoft SQL Server, they made this product compatible only with Windows operating systems
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

Made this product compatible with Linux Operating Systems:


MS SQL Server 2016
MS SQL Server 2017
MS SQL Server 2019
Release RTM (no SP) Latest CU
SQL Server 2019
SQL Server latest version
SQL Server 15
codename Seattle
Support end date: 2025-01-07
Ext. end date: 2030-01-08 15.0.2000.5
CU12 (15.0.4153.1, August 2021)
SQL Server 2017
SQL Server 14
codename vNext
Support end date: 2022-10-11
Ext. end date: 2027-10-12 14.0.1000.169
CU26 (14.0.3411.3, September 2021)

Starting from SQL Server 2017 Service Packs will no longer be released
SP1 SP2 SP3 SP4
SQL Server 2016
SQL Server 13
Support end date: 2021-07-13
Ext. end date: 2026-07-14 13.0.1601.5

+ CU9
13.0.4001.0
or 13.1.4001.0
+ CU15
13.0.5026.0
or 13.2.5026.0
+ CU17
13.0.6300.2
or 13.3.6300.2
SQL Server 2014
SQL Server 12
Support end date: 2019-07-09
Ext. end date: 2024-07-09 12.0.2000.8

+ CU14
12.0.4100.1
or 12.1.4100.1
+ CU13
12.0.5000.0
or 12.2.5000.0
+ CU18
12.0.6024.0
or 12.3.6024.0
+ CU4

SQL Server 2012


SQL Server 11
codename Denali
Support end date: 2017-07-11
Ext. end date: 2022-07-12 11.0.2100.60
+ CU11
11.0.3000.0
or 11.1.3000.0
+ CU16
11.0.5058.0
or 11.2.5058.0
+ CU16
11.0.6020.0
or 11.3.6020.0
+ CU10
11.0.7001.0
or 11.4.7001.0
Obsolete versions – out of support
SQL Server 2008 R2
SQL Server 10.5
codename Kilimanjaro
Support end date: 2014-07-08
Ext. end date: 2019-07-09 10.50.1600.1 10.50.2500.0
or 10.51.2500.0 10.50.4000.0
or 10.52.4000.0 10.50.6000.34
or 10.53.6000.34
SQL Server 2008
SQL Server 10
codename Katmai
Support end date: 2014-07-08
Ext. end date: 2019-07-09 10.0.1600.22 10.0.2531.0
or 10.1.2531.010.0.4000.0
or 10.2.4000.010.0.5500.0
or 10.3.5500.010.0.6000.29
or 10.4.6000.29
SQL Server 2005
SQL Server 9
codename Yukon
Support end date: 2011-04-12
Ext. end date: 2016-04-12 9.0.1399.06 9.0.2047
9.0.3042
9.0.4035
9.0.5000

SQL Server 2000


SQL Server 8
codename Shiloh
Support end date: 2008-04-08
Ext. end date: 2013-04-09 8.0.194 8.0.384
8.0.532
8.0.760
8.0.2039

SQL Server 7.0


SQL Server 7
codename Sphinx
Support end date: 2005-12-31
Ext. end date: 2011-01-11 7.0.623 7.0.699
7.0.842
7.0.961
7.0.1063

SQL Server 6.5


SQL Server 6.50
codename Hydra
Support end date: 2002-01-01 6.50.201 6.50.213 6.50.240 6.50.258
SP4 6.50.281
SP5 6.50.416
SQL Server 6.0
SQL Server 6
codename SQL95
Support end date: 1999-03-31 6.00.121 6.00.124 6.00.139 6.00.151

Patch:
A Patch nothing but a solution for bugs reported (bug fix)
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.

SQL Server Editions:


• Enterprise: IT is the top edition with all the enterprise feature with maximum capacity and
it is recommended for production usage. Cost of enterprise edition is almost 5X greater
compared to standard edition
• Standard: it comes up with some cut down enterprise features and this also
recommended for production usage
• Developer: it will also come with all the enterprise features with free of cot, but it cannot
be user for production usage
• Express: This is basic SQL server edition, with limited features and limited capacity
• Evaluation: it also enterprise edition with 180 days of free trail validity
Edition comparison:

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.Download SQL2019 Express
EditionDownload SQL2017 Express Edition

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 EditionDownload 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.Download SQL2019 Evaluation EditionDownload SQL2017 Evaluation Edition

Paid editions
Enterprise Enterprise edition is the top-end edition with a full feature set.
Enterprise Core Enterprise edition with the Core-based Licensing. The plain Enterprise
one is limited to just 20 CPU cores.
Standard Standard edition has less features than Enterprise, when there is no requirement
of advanced features.
Azure SQL Database Azure SQL Database is the cloud-based version of SQL Server,
presented as a platform as a service (PaaS) offering on Microsoft Azure.
Specialized editions
Web Web edition is a low total-cost-of-ownership option for Web hosters.
Business Intelligence Business Intelligence edition includes the Standard Edition capabilities
and Business Intelligence tools.
Analytics Platform System (APS) Formerly Parallel Data Warehouse (PDW). A massively
parallel processing (MPP) SQL Server appliance optimized for large-scale data warehousing
such as hundreds of terabytes.
Big Data Clusters (BDC) Starting with SQL Server 2019, SQL Server Big Data Clusters
allow you to deploy scalable clusters of SQL Server, Spark, and HDFS (Hadoop Distributed File
System) containers running on Kubernetes.
LocalDB SQL Server Express LocalDB is a lightweight version of Express that has all of its
programmability features, runs in user mode and has a fast, zero-configuration installation and a
short list of prerequisites.

SQL Server editions


The following table describes the editions of SQL Server.
SQL SERVER EDITIONS
SQL Server edition Definition
Enterprise The premium offering, SQL Server Enterprise edition delivers comprehensive
high-end datacenter capabilities with blazing-fast performance, unlimited virtualization1, and
end-to-end business intelligence - enabling high service levels for mission-critical workloads and
end-user access to data insights.
Standard SQL Server Standard edition delivers basic data management and business
intelligence database for departments and small organizations to run their applications and
supports common development tools for on-premises and cloud - enabling effective database
management with minimal IT resources.
Web SQL Server Web edition is a low total-cost-of-ownership option for Web hosters and
Web VAPs to provide scalability, affordability, and manageability capabilities for small to
large-scale Web properties.
Developer SQL Server Developer edition lets developers build any kind of application on top
of SQL Server. It includes all the functionality of Enterprise edition, but is licensed for use as a
development and test system, not as a production server. SQL Server Developer is an ideal
choice for people who build and test applications.
Express editions Express edition is the entry-level, free database and is ideal for learning
and building desktop and small server data-driven applications. It is the best choice for
independent software vendors, developers, and hobbyists building client applications. If you
need more advanced database features, SQL Server Express can be seamlessly upgraded to
other higher end versions of SQL Server. SQL Server Express LocalDB is a lightweight version
of Express that has all of its programmability features, runs in user mode and has a fast,
zero-configuration installation and a short list of prerequisites.

Edition comparison:
Feature Enterprise Standard Express Express w/ Advanced Services
Max. Compute Capacity (per instance) OS Max. Lesser of 4 sockets / 24 cores
Lesser of 1 socket / 4 cores Lesser of 1 socket / 4 cores
Max. Buffer Pool Memory (per instance) OS Max. 128GB 1410MB 1410MB
Max. Columnstore Cache Memory (per instance) Unlimited 32GB 352MB 352MB
Max. Memory-Optimized Data Size (per instance) Unlimited 32GB 352MB 352MB
Max. database size 524PB 524PB 10GB 10GB
Log Shipping Yes Yes No No
Mirroring Yes Yes As Witness As Witness
Backup Compression Yes Yes No No
Database Snapshots Yes Yes Yes Yes
AlwaysOn AG Yes No No No
Basic Availability Groups(opens new window)
Yes Yes (2 nodes) No No
Encrypted Backups Yes Yes No No
Stretch Database Yes Yes Yes Yes
Table/index Partitioning Yes Yes Yes Yes
Buffer Pool Extension Yes Yes No No
Compression Yes Yes Yes Yes
Resource Governor Yes No No No
In-Memory OLTP Yes Yes Yes Yes
Auditing Yes Yes Yes Yes
Fine Grained Auditing Yes Yes Yes Yes
Dynamic Data Masking Yes Yes Yes Yes
Always Encrypted w/ Secure Enclaves Yes Yes Yes Yes
Transparent Database Encryption Yes Yes No No
Contained Databases Yes Yes Yes Yes
Change Tracking Yes Yes Yes Yes
Merge Replication Yes Yes As Subscriber As Subscriber
Transactional Replication Yes Yes As Subscriber As Subscriber
Transactional Replication to Azure Yes Yes No No
Snapshot Replication Yes Yes As Subscriber As Subscriber
P2P Transactional Replication Yes No No No
SQL Server Agent Yes Yes No No
Dedicated Admin Connection Yes Yes Yes Yes
PowerShell SMO Support Yes Yes Yes Yes
Full Text Search Yes Yes No Yes
CLR Integration Yes Yes Yes Yes
Import/Export Wizard Yes Yes Yes Yes
Database Mail Yes Yes No No
UTF-8 Yes Yes Yes Yes
Java Runtime Integration Yes Yes Yes Yes
Polybase Compute Node Yes Yes Yes Yes
Master Instance for Big Data Cluster Yes Yes Yes Yes
Acceleterated Database Recovery Yes Yes No No
Intelligent Database: automatic tuning Yes No No No
Intelligent Database: batch mode for row store Yes No No No
Intelligent Database: row mode memory grant feedback Yes No No No
Intelligent Database: approximate count distinct Yes Yes Yes Yes
Intelligent Database: table variable deferred compilation Yes Yes Yes Yes
Intelligent Database: scalar UDF inlining Yes Yes Yes Yes
Parallel Query Processing(opens new window)
Yes Yes No No

Downloading SQL Server:


https://www.microsoft.com/en-in/sql-server/sql-server-downloads
Evaluation edition:

Developer Edition:

SSMS – SQL Server Management studio


https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view
=sql-server-ver15

SQL Server Pricing:

How to find a server name?


Right click on my computer/This PC -> properties

CMD prompt/Powershell:
IP address:

RunMsinfo32

Rundiskmgmt.msc

Computer Management:

SQL Server Installation:


Hardware and Software Pre requisites:
1. SQL Server 2019 requires a minimum of 6 GB of available hard-disk space.
2. RAM – 1 GM is minimum and Recommended 4 GB
3. Processor – Speed 2.0 GHZ or faster
Software Requirements:
1. OS – Windows 10 or above /Windows server 2016/above
2. SQL Server 2019 can be installed only on 64 Bit OS
3. .NET framework (4.5) or later (minimum OS .Net requirement)
4. SQL Server Native Client
5. SQL Server Setup support files

Operating system support


The following table shows which editions of SQL Server 2019 (15.x) are compatible with which
versions of Windows:
OPERATING SYSTEM SUPPORT
SQL Server edition: Enterprise Developer Standard Web Express
Windows Server 2022 Datacenter Yes Yes Yes Yes Yes
Windows Server 2022 Datacenter: Azure Edition Yes Yes Yes Yes Yes
Windows Server 2022 Standard Yes Yes Yes Yes Yes
Windows Server 2019 Datacenter Yes Yes Yes Yes Yes
Windows Server 2019 Standard Yes Yes Yes Yes Yes
Windows Server 2019 Essentials Yes Yes Yes Yes Yes
Windows Server 2016 Datacenter Yes Yes Yes Yes Yes
Windows Server 2016 Standard Yes Yes Yes Yes Yes
Windows Server 2016 Essentials Yes Yes Yes Yes Yes
Windows 10 IoT Enterprise No Yes Yes No Yes
Windows 10 Enterprise No Yes Yes No Yes
Windows 10 Professional No Yes Yes No Yes
Windows 10 Home No Yes Yes No Yes
Feature Disk space requirement
Database Engine and data files, Replication, Full-Text Search, and Data Quality Services1480
MB
Database Engine (as above) with R Services (In-Database) 2744 MB
Database Engine (as above) with PolyBase Query Service for External Data 4194 MB
Analysis Services and data files 698 MB
Reporting Services 967 MB
Microsoft R Server (Standalone) 280 MB
Reporting Services - SharePoint 1203 MB
Reporting Services Add-in for SharePoint Products 325 MB
Data Quality Client 121 MB
Client Tools Connectivity 328 MB
Integration Services 306 MB
Client Components (other than SQL Server Books Online components and Integration Services
tools) 445 MB
Master Data Services 280 MB
SQL Server Books Online Components to view and manage help content*27 MB
All Features 8030 MB

Installing SQL Server on a domain controller


For security reasons, we recommend that you do not install SQL Server on a domain controller.
SQL Server Setup will not block installation on a computer that is a domain controller, but the
following limitations apply:
• You cannot run SQL Server services on a domain controller under a local service
account.
• After SQL Server is installed on a computer, you cannot change the computer from a
domain member to a domain controller. You must uninstall SQL Server before you change the
host computer to a domain controller.
• After SQL Server is installed on a computer, you cannot change the computer from a
domain controller to a domain member. You must uninstall SQL Server before you change the
host computer to a domain member.
• SQL Server failover cluster instances are not supported where cluster nodes are domain
controllers.
• SQL Server is not supported on a read-only domain controller. SQL Server Setup cannot
create security groups or provision SQL Server service accounts on a read-only domain
controller. In this scenario, Setup will fail.
• A SQL Server failover cluster instance is not supported in an environment where only a
read-only domain controller is accessible.

Instance:
Instance is nothing but a SQL Server; In one machine we can install multiple instances. Each
instance should unique name.
Types of Instances:
1. Default - If we choose instance type as default, it will automatically assigns windows
machine name as a default instance name. so in one machine, we can setup only one default
instance
2. Named: If we choose instance type as named, it will allows us assign a name as per our
business requirements. We can setup 49 named instances in one machine
Total in one server, we can setup 50 SQL servers…

SQL Server Management Studio (SSMS):


It is a GUI Tool with which we can connect to SQL server and perform any database related
activities like creation of databases, tables, views, sps, backups, restores , HA configuration
..etc.

SQL Server Configuration Manager (SSCM):


Configuration manager is tool where we can list of SQL Server services installed on a particular
machine and also we can perfrom activities like start, stop, restarting SQL server..etc and also
we can change the start up mode and also we can change the service accounts.
RunSqlservermanager15.msc for 2019
Sqlservermanager14.msc for 2017
Sqlservermanager13.msc for 2016
Sqlservermanager12.msc for 2014

Different Ways to Start/Stop/Restart SQL Server services:


1. Configuration manager
Runsqlservermanaer15.mscSQL server servicesright click on SQL Server
servicestart/stop/restart

2. Service console:
Runservices.mscright click on SQL servicesstart/stop/restart

3. Command Prompt
Open CMD as administrator

Default:
NET START MSSQLSERVER
NET STOP MSSQLSERVER
Named Instance:
NET START MSSQL$<INSTANCE NAME>
NET STOP MSSQL$<INSTANCE NAME>

4. Powershell
Default:
Start-service –name mssqlserver
Stop-service –name mssqlserver
Named:
Start-service –name ‘mssql$instancename’
Stop-service –name ‘mssql$instancename’

5. SSMS

Connectivity with Different Ways:


Default:
Server Name - <serveranme>
Server Name - . (dot)
Server Name – (local)

Named Instance:
Server Name - <serveranme/Instance>

Server Name - <./Instance>

Server Name - <(local)/Instance>

How to verify authentication mode?

How To change authentication mode:


Option #1:
Right click on instance namepropertiessecurity->Server authenticationchange the
authenticationrestart sql server

Option#2:
RunREGEDIT

If login mode =1, windows authentication


Login mode =2, mixed authentication

How to reset SA password:


Connect the instancesecurityloginsright click SAproperties change the password

How to find the version of the SQL server ?


select @@version as Version
RTM:

CU12:

How to find the server name?


select @@SERVERNAME as ServerName

Uninstall a patch:
Control panelprogrammsview installed updates

Below are the patches for SQL server 2019

Right click on any patchuninstall

Uninstall sql server

CONNECTIVITY:
How to Enable TCP/IP for a SQL server?
Configuration managerSQL Server network configurationsprotocols for <SQL server>right click
on TCP/IP enableRestart SQL Servvice

What is the default port number of SQL Server?


1433
How to check SQL server port ?

Can we Change the Default port of a SQL server?


Yes, we must change as. the default port number is known every one. As post installation best
practices, we need to change default port number.
How to Change ?
Configuration managerSQL Server network configurationsprotocols for <SQL server>right click
on TCP/IP PropertiesIP addresses Change the default portrestart the SQL Service
What is port range for SQL Server?
It uses 1433 by default. If you're referring to the dynamic port range for TCP/UDP, it is
49152–65535
For named instances, SQL server will get port assigned dynamically.

How to make port for SQL Server static?


1. Remove the port from TCP Dynamic ports and put it on TCP port
2. Remove 0 (zero) from TCP Dynamic ports fop all IP Addresses
Connectivity Test between the Servers:

SQL Connectivity between the app and DB server:

Telnet success:

Telnet Failure:

SQL Development Basics:


1. Data types: At the time table creation, we can define columns data type. So that the
column should accept only that particular type of data
Ex: int, char, varchar(), date, datetime..etc

SQL Server Data Types


String Data Types
Data type Description Max size Storage
char(n) Fixed width character string 8,000 characters Defined width
varchar(n) Variable width character string 8,000 characters 2 bytes + number of
chars
varchar(max) Variable width character string 1,073,741,824 characters 2 bytes +
number of chars
text Variable width character string 2GB of text data 4 bytes + number of chars
nchar Fixed width Unicode string 4,000 characters Defined width x 2
nvarchar Variable width Unicode string 4,000 characters
nvarchar(max) Variable width Unicode string 536,870,912 characters
Ntext Variable width Unicode string 2GB of text data
binary(n) Fixed width binary string 8,000 bytes
varbinary Variable width binary string 8,000 bytes
varbinary(max) Variable width binary string 2GB
Image Variable width binary string 2GB
Numeric Data Types
Data type Description Storage
Bit Integer that can be 0, 1, or NULL
Tinyint Allows whole numbers from 0 to 255 1 byte
Smallint Allows whole numbers between -32,768 and 32,767 2 bytes
Int Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes
Bigint Allows whole numbers between -9,223,372,036,854,775,808 and
9,223,372,036,854,775,807 8 bytes
decimal(p,s) Fixed precision and scale numbers.
Allows numbers from -10^38 +1 to 10^38 –1.
The p parameter indicates the maximum total number of digits that can be stored (both to the
left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18.
The s parameter indicates the maximum number of digits stored to the right of the decimal point.
s must be a value from 0 to p. Default value is 0 5-17 bytes
numeric(p,s) Fixed precision and scale numbers.
Allows numbers from -10^38 +1 to 10^38 –1.
The p parameter indicates the maximum total number of digits that can be stored (both to the
left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18.
The s parameter indicates the maximum number of digits stored to the right of the decimal point.
s must be a value from 0 to p. Default value is 0 5-17 bytes
smallmoney Monetary data from -214,748.3648 to 214,748.36474 bytes
Money Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 bytes
float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308.
The n parameter indicates whether the field should hold 4 or 8 bytes. float(24) holds a 4-byte
field and float(53) holds an 8-byte field. Default value of n is 53. 4 or 8 bytes
Real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes
Date and Time Data Types
Data type Description Storage
datetime From January 1, 1753 to December 31, 9999 with an accuracy of 3.33
milliseconds 8 bytes
datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 100
nanoseconds 6-8 bytes
smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute 4 bytes
Date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes
Time Store a time only to an accuracy of 100 nanoseconds 3-5 bytes
datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10 bytes
timestamp Stores a unique number that gets updated every time a row gets created or
modified. The timestamp value is based upon an internal clock and does not correspond to real
time. Each table may have only one timestamp variable
Other Data Types
Data type Description
sql_variant Stores up to 8,000 bytes of data of various data types, except text, ntext, and
timestamp
uniqueidentifier Stores a globally unique identifier (GUID)
Xml Stores XML formatted data. Maximum 2GB
Cursor Stores a reference to a cursor used for database operations
Table Stores a result-set for later processing

2. Constraints:
Constrains allows us to create a condition on the table
a. Primary Key: it won’t allow null values and duplicates. In one table we can create only
one primary key
b. Not null: It won’t allow any null values
c. Unique: it won’t allow duplicates, but it will allow one null value
d. Check: it accepts values in a particular range.
Age >18 and age <35
e. Default: while creating a table.. we can assign default value to particular column.
EX: Location varchar(50) default ‘Hyd’
f. Identity: if we have any column with fixed auto incremental values..we can use Identity
Ex: SNO int Identity (1,1)
g. Foreign Key: it must be a primary key in some other table and it accept the values only
from reference table.

SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the accuracy
and reliability of the data in the table. If there is any violation between the constraint and the
data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and
table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table
• FOREIGN KEY - Prevents actions that would destroy links between tables
• CHECK - Ensures that the values in a column satisfies a specific condition
• 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

3. SQL languages
a. DDL: Data definition language
• Create
Create database <database Name>
eX:
create database Devbasics

• Alter
• DROP
drop database [Devbasics]
USE [master]
GO

/****** Object: Database [Devbasics2] Script Date: 10/21/2021 9:59:43 AM ******/


DROP DATABASE [Devbasics2]
GO
USE [master]
GO

/****** Object: Database [Devbasics2] Script Date: 10/21/2021 9:59:43 AM ******/


DROP DATABASE [Devbasics2]
GO
• Truncate
b. DML: Data Manipulation language
Insert
Update
Delete
Merge
c. DCL: Data control Language
Grant
With grant
Revoke
d. TCL: Transaction control language
Commit
Rollback
Save point
4. Joins and unions
5. Stored Procedures

How to change default database locations?


Right click on the instance namepropertiesdatabase Default setting

How to change the Service account:


Configuration managerright click on the instance logonchange the service account restart the
service

Database Creation script:


USE [master]
GO

/****** Object: Database [Devbasics2] Script Date: 10/21/2021 9:51:27 AM ******/


CREATE DATABASE [Devbasics2]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'Devbasics2', FILENAME = N'F:\Devbasics2.mdf' , SIZE = 8192KB , MAXSIZE =
UNLIMITED, FILEGROWTH = 65536KB )
LOG ON
( NAME = N'Devbasics2_log', FILENAME = N'F:\Devbasics2_log.ldf' , SIZE = 8192KB ,
MAXSIZE = 2048GB , FILEGROWTH = 65536KB )
WITH CATALOG_COLLATION = DATABASE_DEFAULT
GO

IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [Devbasics2].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO

ALTER DATABASE [Devbasics2] SET ANSI_NULL_DEFAULT OFF


GO

ALTER DATABASE [Devbasics2] SET ANSI_NULLS OFF


GO

ALTER DATABASE [Devbasics2] SET ANSI_PADDING OFF


GO

ALTER DATABASE [Devbasics2] SET ANSI_WARNINGS OFF


GO

ALTER DATABASE [Devbasics2] SET ARITHABORT OFF


GO

ALTER DATABASE [Devbasics2] SET AUTO_CLOSE OFF


GO

ALTER DATABASE [Devbasics2] SET AUTO_SHRINK OFF


GO

ALTER DATABASE [Devbasics2] SET AUTO_UPDATE_STATISTICS ON


GO
ALTER DATABASE [Devbasics2] SET CURSOR_CLOSE_ON_COMMIT OFF
GO

ALTER DATABASE [Devbasics2] SET CURSOR_DEFAULT GLOBAL


GO

ALTER DATABASE [Devbasics2] SET CONCAT_NULL_YIELDS_NULL OFF


GO

ALTER DATABASE [Devbasics2] SET NUMERIC_ROUNDABORT OFF


GO

ALTER DATABASE [Devbasics2] SET QUOTED_IDENTIFIER OFF


GO

ALTER DATABASE [Devbasics2] SET RECURSIVE_TRIGGERS OFF


GO

ALTER DATABASE [Devbasics2] SET ENABLE_BROKER


GO

ALTER DATABASE [Devbasics2] SET AUTO_UPDATE_STATISTICS_ASYNC OFF


GO

ALTER DATABASE [Devbasics2] SET DATE_CORRELATION_OPTIMIZATION OFF


GO

ALTER DATABASE [Devbasics2] SET TRUSTWORTHY OFF


GO

ALTER DATABASE [Devbasics2] SET ALLOW_SNAPSHOT_ISOLATION OFF


GO

ALTER DATABASE [Devbasics2] SET PARAMETERIZATION SIMPLE


GO

ALTER DATABASE [Devbasics2] SET READ_COMMITTED_SNAPSHOT OFF


GO

ALTER DATABASE [Devbasics2] SET HONOR_BROKER_PRIORITY OFF


GO

ALTER DATABASE [Devbasics2] SET RECOVERY FULL


GO
ALTER DATABASE [Devbasics2] SET MULTI_USER
GO

ALTER DATABASE [Devbasics2] SET PAGE_VERIFY CHECKSUM


GO

ALTER DATABASE [Devbasics2] SET DB_CHAINING OFF


GO

ALTER DATABASE [Devbasics2] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )


GO

ALTER DATABASE [Devbasics2] SET TARGET_RECOVERY_TIME = 60 SECONDS


GO

ALTER DATABASE [Devbasics2] SET DELAYED_DURABILITY = DISABLED


GO

ALTER DATABASE [Devbasics2] SET ACCELERATED_DATABASE_RECOVERY = OFF


GO

ALTER DATABASE [Devbasics2] SET QUERY_STORE = OFF


GO

ALTER DATABASE [Devbasics2] SET READ_WRITE


GO

DEV basics Demo:


--DDL commands
--creating the database
create database [DevBasics]
--cheaging the recovery model
ALTER DATABASE [Devbasics] SET RECOVERY simple
GO
--to add a file to database
alter database [DevBasics] add file
(name='devbasics1',filename='F:\sqllab\devbscis1.ndf')

--creating table
create table employee
(id int,
name varchar(50),
sal int,
location varchar(50),
DOJ datetime)
--adding column to the table
Alter table [dbo].[employee] add dept varchar(50)
--drop a column from the table
alter table [dbo].[employee] drop column dept

--dropin the entire table


drop table [dbo].[employee]

--DML Commands
insert into [dbo].[employee] values
(1,'Mike',10000,'Hyd',(getdate()-365))

insert into [dbo].[employee] values


(1,'Mike',10000,'Hyd',(getdate()-365)),
(2,'bob',10000,'Hyd',(getdate()-365)),
(3,'denise',30000,'Hyd',(getdate()-365)),
(4,'greg',10000,'Hyd',(getdate()-365)),
(5,'neil',80000,'Bang',(getdate()-365))

update [dbo].[employee] set name='denise'


where id=5

delete from [dbo].[employee]

delete from [dbo].[employee]


where id=5

truncate table [dbo].[employee]

drop table [dbo].[employee]

select * from [dbo].[employee]

--PULLS All the data from table


SELECT * FROM [Sales].[SalesOrderDetail]

--column filter
SELECT SalesOrderID,UnitPrice FROM [Sales].[SalesOrderDetail]
--row filters
SELECT * FROM [Sales].[SalesOrderDetail]
where SalesOrderID=43659

SELECT * FROM [Sales].[SalesOrderDetail]


where SalesOrderID<>43659

SELECT * FROM [Sales].[SalesOrderDetail]


where SalesOrderID=43659 and UnitPrice>1000

SELECT * FROM [Sales].[SalesOrderDetail]


where SalesOrderID=43659 OR UnitPrice>1000

SELECT * FROM [Sales].[SalesOrderDetail]


where SalesOrderID in (43659,43661, 43660)

SELECT * FROM [Sales].[SalesOrderDetail]


where OrderQty between 20 and 40

SELECT * FROM [Sales].[SalesOrderDetail]


order by SalesOrderID desc;

SELECT * FROM [Sales].[SalesOrderDetail]


order by SalesOrderID asc;

SELECT * FROM [Sales].[SalesOrderDetail]


order by OrderQty asc;

SELECT top 10 SalesOrderID FROM [Sales].[SalesOrderDetail]


order by OrderQty asc;

SELECT min(OrderQty) as minorderqty FROM [Sales].[SalesOrderDetail]


SELECT max(OrderQty) as maxorderqty FROM [Sales].[SalesOrderDetail]

SELECT sum(OrderQty) as total FROM [Sales].[SalesOrderDetail]


SELECT avg(OrderQty) as avg FROM [Sales].[SalesOrderDetail]

SELECT count(*) from [Sales].[SalesOrderDetail]

SELECT SalesOrderID,sum(OrderQty) as totalqty


from [Sales].[SalesOrderDetail]
group by SalesOrderID
SELECT SalesOrderID,sum(OrderQty) as totalqty
from [Sales].[SalesOrderDetail]
group by SalesOrderID
having sum(OrderQty)>100
order by SalesOrderID asc

select * into [Sales].[SalesOrderDetail_tmp]


from
[Sales].[SalesOrderDetail]

select * from [Sales].[SalesOrderDetail_tmp]

truncate table [Sales].[SalesOrderDetail_tmp]

insert into [Sales].[SalesOrderDetail_tmp]


select * from [Sales].[SalesOrderDetail]

Architectures:
1. Database Architecture
1. Data file Architecture
`Page Architecture
2. Log file architecture
2. SQL server Architecture
3. Memory Architecture

Databases:
1. System Databases: The system databases are gets created by default as part SQL
installation
a. Master
b. Model
c. Msdb
d. Tempdb
e. Resource
2. User Databases: User Databases are something which we create to store
users/Business data
Master:
Master is a master of all the databases and it maintains all the systems level information such
as logins, linked servers, end points and it also maintains information about all other databases
and database files information also, open sessions, connections..etc
Logins:
select name from [sys].[syslogins]

Linked Server:
If we want access data of one SQL server from another SQL Server

select * from [sys].[sysservers]

Information about all other Databases:


select * from sys.databases

Database files info:


select name, type_desc,physical_name
from sys.master_files

select name,filename from sys.sysaltfiles

All the open sessions’ information:


select * from sys.dm_exec_requests

sp_who
sp_who2

** With out master database SQL server will not work..**


Database ID for Master: 1
Recovery model of Master: Simple
Model:
It is Template database in SQL server, whenever we create a new user database or TempDB.
This will inherit all the properties of a model database to the new user database we are creating.
Ex1:
We have a requirement to create 10 tables by default in every database that we create
Solution:
Create the 10 tables in model database; from there whatever new databases we create gets the
ten table by default.
Ex2:
User is asking to created 100 database and all the databases should get recovery model as
‘Simple’ by default
Solution:
Change the recover model of model database to ‘Simple’, from the whatever new databases we
created get created with simple recovery model.

Without model, SQL server will start/not ?


No, it will not start the SQL server. Because whenever we restart SQL server ,it has to create a
new tempdb. If model is not available, it may not be able to create tempdb. So model is not
available, SQL server will not start
MSDB:
SQL Server Agent Service- For every SQL Server that we install a corresponding Agent service
will be configured. This agent service will be used to automate the activities in SQL Server. So
here we can create jobs and add a task and put a schedule.

Ex:
Daily_sales
Sales_history
Requirement –
all the daily sales information will be inserted into Daily_sales table
Every Day mid night, we need insert all the data from Daily_Sales to sale_history and then
delete from daily_Sales

USE [DevBasics]
GO
Create table daily_sales
(salesID int, orderqty int, orderDate datetime)

Create table sales_history


(salesID int, orderqty int, orderDate datetime)

insert into daily_sales values


(102,1, getDate())

insert into sales_history


select * from daily_sales

truncate table [dbo].[daily_sales]

USE [DevBasics]
GO
Create table daily_sales
(salesID int, orderqty int, orderDate datetime)
Create table sales_history
(salesID int, orderqty int, orderDate datetime)

insert into daily_sales values


(104,12, getDate()+1),
(105,1, getDate()+1),
(106,10, getDate()+1),
(107,11, getDate()+1)

select * from daily_sales


select * from sales_history

insert into sales_history


select * from daily_sales

truncate table [dbo].[daily_sales]


MSDB: it maintains all the agent related information like jobs, alerts, operators, notification also
maintains backup/restore history also. Also maintains log shipping information’, always On
history..
Jobs related tables:

Backup history:

AlwaysOn and Logshipping

What is database ID for MSDB: 4


What is default recovery model of MSDB: Simple
Without MSDB, SQL server starts/not ?
SQL Server will start absolutely file, but agent service will not work.. so job will have impact.

TempdB: it is temporary database in SQL Server, it maintains all the intermittent results of a
transaction temporarily. It is a central and critical database and this will be used by transaction
from every databases.
**Whenever we restart SQL server, a new TempDB will be created

Temporary Tables:
#Temp (local Temp tables): the span is limited to a session where it is created.
create table #Temp1 (id int)
create table ##Temp2 (id int)

insert into #Temp1 values (1)


insert into ##Temp2 values (1)

select * from #Temp1


select * from ##Temp2
##Temp (|Global Temp Tables)
The span of global temp table to other session as well.. we can access it from other sessions..
create table #Temp1 (id int)
create table ##Temp2 (id int)

insert into #Temp1 values (1)


insert into ##Temp2 values (1)

select * from #Temp1


select * from ##Temp2
Without TempDB, SQL server starts/not ?
Yes, will start the sql server and creates new tempdb file..

How to find the location of Database:


Option#1:
Right click on the databasepropertiesfiles

Option#2:
use [DevBasics]
go
sp_helpfile

Option3#:
select name,physical_name from sys.master_files

select name,physical_name from sys.master_files


where database_id >4

select * from sys.master_files


where database_id >4 and type_desc='ROWS'

select * from sys.master_files


where database_id >4 and type_desc='LOG'

select * from sys.master_files


where database_id >4 and FILE_ID <>2

SELECT NAME,FILENAME FROM SYS.sysaltfiles


Option4#: only for master database
Startup parameters maintains the location of master database (data file and log file)
Configuration ManagerSQL server servicesright click on the instance nameproperties startup
parameters

-d : gives master database data file location


-dC:\Program Files\Microsoft SQL Server\MSSQL15.SQLSEP21_1\MSSQL\DATA\master.mdf

-l : gives the location of master database log file


-lC:\Program Files\Microsoft SQL Server\MSSQL15.SQLSEP21_1\MSSQL\DATA\mastlog.ldf

-e: gives error log location


What happens in the backend when we restart SQL server?
Whenever we restart SQL server, it has to start all the databases one by one..First it start with
master database, to get master database files information, it reads the startup
parameters..THEN it will bring master database online. Once database is online, as it is
maintaining locations of all other databases. SQL server reads the location of each database
and gets into that location to see corresponding files are there and then it starts all the
databases one by one online.
It read – d to get master database location and –l to get the master log location

-dC:\Program Files\Microsoft SQL Server\MSSQL15.SQLSEP21_1\MSSQL\DATA\master.mdf


It will go
C:\Program Files\Microsoft SQL Server\MSSQL15.SQLSEP21_1\MSSQL\DATA\
Then it will look for
master.mdf
Reads –l parameter:
-lC:\Program Files\Microsoft SQL Server\MSSQL15.SQLSEP21_1\MSSQL\DATA\mastlog.ldf
It will go to
C:\Program Files\Microsoft SQL Server\MSSQL15.SQLSEP21_1\MSSQL\DATA\
It will check for file name
mastlog.ldf

How to find when your SQL server restarted last time?


We can find with Tempdb creation date time (when ever restart SQL server, a new Tempdb will
be created)

Error Log:
It is log file in SQL server and maintains all the error messages, warnings and informational
messages. In SQL server, we need to start trouble any issues with verifying error log.
How to find error log location:
Option #1:
-e in startup parameters provides the location of error log

What exactly the error log contains:


SQL version
Edition
Os Details
Time Zone
Hardware Details
Authentication mode

Reads the startup parameters and brings master database online:

Then it brings all other database online, one by one..

No of cores, RAM and collation

Port of SQL server:

Option#2:
SSMSunder Instance NamemanagementSQL server logs

What is default error log count? – 6


Can we change this default error log count ?
Yes, between 6-99
How to change it ?

Right click on the SQL Server logs configure Restart SQL server/Recycle error log

How to recycle error log ?

exec sp_cycle_errorlog

Customer have a requirement to generate a new error log file everyday with limit of 30 file ?

Create a sql server agent job add sp_cycle_errorlog to step add schedule

Option #3:
We have two types logs
1. SQL Server log
2. Agent log

exec sp_readerrorlog 0,1


--SQL server current log file
exec sp_readerrorlog 0,2
--Agent current log file

exec sp_readerrorlog 1,1


--Archive 1 of SQL server log
exec sp_readerrorlog 30,1
--archive 30 of SQL server

exec sp_readerrorlog 4,2


--Archive 4 of Agent

exec sp_readerrorlog 0,1,'error'

Moving System Databases:


Why do we need to move the system databases ?
When we install SQL server with default options, the sql server system database file will be
created in C- Drive

As we know C – Drive OS drive, it is not a best practice to keep any of the database files in C
drive.. as part of any assessment, if we see any system/user databases in C- drive, we need to
move the system databases to other drive..

How to move:

--Moving Model Database


--step #1: identify the current location of model database
use model
go
sp_helpfile
--or
--right click on the model--> propeties-->file
--or
select * from sys.master_files where database_id=3
--Step#2: modify the current location model database in system catalog
ALTER DATABASE MODEL MODIFY FILE
(NAME='modeldev',FILENAME='F:\SQLLab\SYSTEMDATABASES\model.mdf')
ALTER DATABASE MODEL MODIFY FILE
(NAME='modellog',FILENAME='F:\SQLLab\SYSTEMDATABASES\modellog.ldf')
--STEP#3: STOP THE SQL SERVER
--STEP#4: COPY THE FILES FROM OLD TO NEW DIRECTORY MANULLAY
--STEP#5: START THE SQL SERVER
--sTEP#6: VERIFY THE CURRENT LOCATIN OF MODEL DATABASE
USE MODEL
GO
sp_helpfile

MSDB:
--Moving MSDB Database
--step #1: identify the current location of MSDB database
use MSDB
go
sp_helpfile
--or
--right click on the model--> propeties-->file
--or
select * from sys.master_files where database_id=4
--Step#2: modify the current location msdb database in system catalog
ALTER DATABASE [msdb] MODIFY FILE
(NAME='MSDBData',FILENAME='F:\SQLLab\SYSTEMDATABASES\MSDBData.mdf')
ALTER DATABASE [msdb] MODIFY FILE
(NAME='MSDBLog',FILENAME='F:\SQLLab\SYSTEMDATABASES\MSDBLog.ldf')
--STEP#3: STOP THE SQL SERVER
--STEP#4: COPY THE FILES FROM OLD TO NEW DIRECTORY MANULLAY
--STEP#5: START THE SQL SERVER
--sTEP#6: VERIFY THE CURRENT LOCATIN OF msdb DATABASE
USE msdb
GO
sp_helpfile

TEMPDB:
--Moving Tempdb Database
--step #1: identify the current location of temdbdb database
use tempdb
go
sp_helpfile
--or
--right click on the model--> propeties-->file
--or
select * from sys.master_files where database_id=2
--Step#2: modify the current location tempdb database in system catalog
ALTER DATABASE [tempdb] MODIFY FILE
(NAME='tempdev',FILENAME='F:\SQLLab\SYSTEMDATABASES\tempdb.mdf')
ALTER DATABASE [tempdb] MODIFY FILE
(NAME='temp2',FILENAME='F:\SQLLab\SYSTEMDATABASES\tempdb_mssql_2.ndf')
ALTER DATABASE [tempdb] MODIFY FILE
(NAME='temp3',FILENAME='F:\SQLLab\SYSTEMDATABASES\tempdb_mssql_3.ndf')
ALTER DATABASE [tempdb] MODIFY FILE
(NAME='temp4',FILENAME='F:\SQLLab\SYSTEMDATABASES\tempdb_mssql_4.ndf')

ALTER DATABASE [tempdb] MODIFY FILE


(NAME='templog',FILENAME='F:\SQLLab\SYSTEMDATABASES\templog.ldf')
--STEP#3: Restasrt THE SQL SERVER
--sTEP#4: VERIFY THE CURRENT LOCATIN OF tempdb DATABASE
USE tempdb
GO
sp_helpfile

Master:
--Moving master Database
--step #1: identify the current location of master database
use master
go
sp_helpfile
--or
--right click on the master--> propeties-->file
--or
select * from sys.master_files where database_id=1
--Step#2: modify the startup paramter with the new path

--STEP#3: stop THE SQL SERVER


--step4: copy the files from old to new location
--sTEP#5: VERIFY THE CURRENT LOCATIN OF master DATABASE
USE master
GO
sp_helpfile

Joins:
If we want to retrieve the data from two or more tables. Then we can write joins. If we want join
tow tables, there should be a common column between these tables.

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:
• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records
from the right table
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records
from the left table
• FULL (OUTER) JOIN: Returns all records when there is a match in either left or right
table

Case study – pull all the databases along with file names

select
sd.name,
sd.create_date,
sd.recovery_model_desc,
smf.type_desc,
smf.physical_name from
sys.databases sd join sys.master_files smf
on sd.database_id=smf.database_id

Example:
create table orders (ORderID int, customerID int, orderdate datetime)

create table customers


(custid int, customername varchar(50), contactname varchar(50),
country varchar(50))

insert into customers values


(1,'Alfreds Futterkiste','Maria Anders','Germany'),
(2,'Ana Trujillo Emparedados y helados','Ana Trujillo','Mexico'),
(3,'Antonio Moreno Taquería','Antonio','Mexico')

insert into orders values


(10308,2,getdate()),
(10309,37,getdate()),
(10310,77,getdate())

select * from customers


select * from orders

select O.orderdate,C.customername,O.orderdate from orders O


join customers c
on o.customerID=c.custid

--left join
select O.ORderID,C.customername,O.orderdate
from orders O
LEFT join customers c
on o.customerID=c.custid

--RIGHT join
select O.ORderID,C.customername,O.orderdate
from orders O
right join customers c
on o.customerID=c.custid
--FULL join
select O.ORderID,C.customername,O.orderdate
from orders O
full join customers c
on o.customerID=c.custid

Union:
The UNION operator is used to combine the result-set of two or more SELECT statements.
• Every SELECT statement within UNION must have the same number of columns
• The columns must also have similar data types
• The columns in every SELECT statement must also be in the same order
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

Union selects only distinct values.. but union all selects duplicates also..

Backup and Recovery:

Maintaining a copy of original data in a different location. In the event of original data loss, we
can recover it from the backup available.
It is a DBA prime responsibility to configure the regular backups from all our production
databases..

Backup/Recovery Architecture:

Types of backups:

1. Full backup
2. Differential backup
3. Log or Transactional log backups
4. File and file group backups
5. Split backup
6. Mirror backups
7. Tail log backups
8. Copy only backup

Full backup:
It is copy of entire database.. if I have database of 500 Gb.. then if I take full backup of that
database and the backup size will be ‘500 Gb’..
The extension of full back up is ‘bak’

Differential backups:
This takes backup of all the changes happened from last successful full backup to till now.

I have full backup happened at 10 AM and from there upto 12 PM, about 10 GB data added..
now when we take differential backup at 12:00 PM, it takes the backup of 10 GB added after last
full backup

The extension for differential backup: bak

Differential backup case study:

*****Differential backups are cumulative

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 of log backup is - TRN


****Log backups are sequential

LOG BACKUP CASE STUDY:

Backup Strategy:

Weekly full backups – Sunday 12:00 am


Daily Differential backups – 6 am
T-log backups for every 1 hour

**The database is crashed at Thursday 4.30 PM

Restore latest Sunday full backup


Restore latest Thursday differential backup
Restore all the log backups from Thursday 6 AM to 4 PM.

Failure Point:
The exact time at which the database is crashed is called ‘Failure point’
In our case failure point is ‘Thursday 4.30 PM’

Point In Time Recovery (PIR):


The process of recovering a database to exact failure point is called Point in time recovery.

Recovery Models:
It is a database level option and it decides to which point of time we can recover a database in
the event of failure.

Types of Recovery Models:

1. Simple
2. Bulk logged
3. Full Recovery

Simple: In simple recovery model or if we put our database in simple recovery model.. The
transaction log file (ldf) gets truncated automatically in regular intervals. So we can’t take log
backup in simple recovery model, as we don’t have log backup, we can’t achieve point in time
recovery. This is not recommended for production OLTP (online transactional processing)
databases. This can be set for Non production databases and OLAP (Online analytical
processing)

Bulk logged Recovery Model:


In Bulk logged recovery, the transactions will be minimally logged for all the bulk operations
(BCP, Bulk insert, select into, index rebuild..etc).. this will basically saves the transactional log
file space. For normal operation, it works as similar to full recovery model. In Bulk logged
recovery model, we can take Transactional log backups.

Case 1: Database is in bulk logged recovery model and there are bulk operations performed..
then Point time recover is not possible

Case 2: Database is in bulk logged recovery model and there are no bulk operations performed,
so it is as similar to full recovery model,. Then point time recovery is possible.
** Bulk logged recovery model is recommended for any database when we performing bulk
operations like BCP, Bulk insert, select into, index rebuild ..etc
Full Recovery model:
In full recovery model, all the transactions will be fully logged into the transaction log file and it
wont truncate any of these transaction automatically.. we can take transaction backups..as we
have transaction log backup, we can achieve Point time recovery.
It is recommended to keep all the production databases in full recovery model.

How to check recovery model:

Option #1:

Right click on the database name propertiesoptions

Option #2:
select name,recovery_model_desc from sys.databases

Option#3:
use [DevBasics]
go
sp_helpdb

How to change the recovery model:

Option#1:
Right click on the database namepropertiesoptionschange the recovery model from the
dropdown

Option#2:
use master
go
alter database [DevBasics] set recovery simple
alter database [DevBasics] set recovery Full
alter database [DevBasics] set recovery bulk_logged

Recovery Options:

• Restore with no recovery


• Restore with recovery
• Restore standby

Weekly full backups – Sunday 12:00 am


Daily Differential backups – 6 am
T-log backups for every 1 hour

With no recovery:

If there are any further backups to be restored, then we need to choose, with no recovery. It
restores the backup, but it will not bring the database online. The database will be in restoring
state and we cant access it.

With recovery:
When there are no further backups to be restore and this is our last log back as part of the
recovery.. the new can with recovery and it restores the backup and brings the database online
for use.

With Standby:
It restores the backup and brings database online with read-only enabled and can’t make any
changes to data.

Ways to backup:
1. SSMS – GUI:

Restore Process:
2. SSMS – T-SQL command

create table test (id int, name varchar(50))


insert into test values (1,'full')
go 10
select * from test

BACKUP DATABASE [BackupDemo]


TO DISK='F:\SQLLab\backups\backupdemo.bak'

insert into test values (2,'Diff')


go 10

BACKUP DATABASE [BackupDemo]


TO DISK='F:\SQLLab\backups\backupdemo_diff.bak'
with differential

insert into test values (3,'log1')


go 10

BACKUP LOG [BackupDemo]


TO DISK='F:\SQLLab\backups\backupdemo1.TRN'

insert into test values (4,'log2')


go 10

BACKUP LOG [BackupDemo]


TO DISK='F:\SQLLab\backups\backupdemo2.TRN'

RESTORE DATABASE [BackupDemo]


FROM DISK='F:\SQLLab\backups\backupdemo.bak'
WITH NORECOVERY
RESTORE DATABASE [BackupDemo]
FROM DISK='F:\SQLLab\backups\backupdemo_diff.bak'
with NORECOVERY

RESTORE LOG [BackupDemo]


FROM DISK='F:\SQLLab\backups\backupdemo1.TRN'
WITH NORECOVERY

RESTORE LOG [BackupDemo]


FROM DISK='F:\SQLLab\backups\backupdemo2.TRN'
WITH RECOVERY

3. SQL server agent


4. Maintenance plans
5. Powershell
6. Third party tools

Case study:

F – Full backup
D – Differential backup
T – Transactional log backups
P – Failure points/PIT

P4 – Amulya
• Restore F1 with no recovery
• Restore T1 with no recovery
• Restore T2 with no recovery
• Restore D1 with recovery

P4 – Anil
• Restore F1 with no recovery
• Restore T1 with no recovery
• Restore T2 with no recovery
• Restore D1 with no recovery
• Restore D3 with recovery
P4 – Sreekar
• Restore F1 with no recovery
• Restore D1 with no recovery
• Restore T1 with no recovery
• Restore T2 with recovery

P4 – Bharath, sharif, barath, manohar, William, Durga, santosh, RT


• Restore F1 with no recovery
• Restore D1 with recovery

P4 – Ramu
• Restore F1 with no recovery
• Restore D3 with no recovery
• Restore T8 with recovery

P9- Durga
Restore F1 with no recovery
Restore D1 with no recovery
Restore D2 with no recovery
Restore D5 with recovery
Restore F2 with recovery
P9- Manohar
Restore F2 with recovery

P8 – Sreekar
• Restore F1 with no recovery
• Restore D2 with no recovery
• Restore t5 w/r
P6- Santosh
• Restore F1 with no recovery
• Restore D1 with no recovery
• Restore t3 with no recovery
• Restore t4 w/r

P11 – Sreenu
• Restore F2 with no recovery
• Restore T6 with no recovery
• Restore t7 w/r

Case study:
I am trying to take a log backup and log backup option is not showing?
May be the database is in simple recovery model, log backups are allowed only in full or bulk
logged recovery model

I have changed the recovery model to Full, but still my log backup is not working?.. it is failing
with below error..

Ans: when ever we change the recovery model, we need to take a fresh full back.. then only the
log backups will work..

File and File group backup:


If I have a database with multiple files and file groups, Instead of taking full back (all the files).
We can take backup of particular data file or a particular file group.

Commands to add files to databases:


USE [master]
GO
alter database [BackupDemo]
add file (name='backupdemo3',filename='F:\SQLLAB\backupdemo3.ndf')

ALTER DATABASE [BackupDemo]


ADD FILE ( NAME = N'backupdemo4',
FILENAME = N'F:\SQLLab\backupdemo4.ndf' , SIZE = 8192KB , FILEGROWTH = 65536KB )
TO FILEGROUP [second]
GO
T-SQL:
backup database [BackupDemo] file='Backupdemo1'
to disk='F:\SQLLab\backups\backupdemo_f1.bak'

backup database [BackupDemo] filegroup='second'


to disk='F:\SQLLab\backups\backupdemo_fg2.bak'

backup database [BackupDemo]


to disk='F:\SQLLab\backups\backupdemo_full.bak'

Split Backup:
If my target backup location doesn’t have enough space to accommodate the backup.. Then we
can use split backup, this will divide the database backup equally in to multiple destinations.
This split backup improves the backup performance as it will initiate multiple threads to write the
backup into backup location.

Demo:

Restore:

T-SQL:
backup database [BackupDemo]
to
disk='F:\SQLLab\backups\backupdemo_s1.bak',
disk='F:\SQLLab\backups\backupdemo_s2.bak'

restore database [BackupDemo]


from
disk='F:\SQLLab\backups\backupdemo_s1.bak',
disk='F:\SQLLab\backups\backupdemo_s2.bak'

Mirror Backup:
Taking multiple copies of full backup at a time for extra safety.

backup database [BackupDemo]


to disk='F:\SQLLab\backups\backupdemo_M1.bak'
mirror
to disk='F:\SQLLab\backups\backupdemo_M2.bak' with format

Tail Log backup:


It is also a log backup, It takes the backup of all the transaction happened from last successful
log backup to failure point.

Weekly Sunday 12:00 – full backups


Daily differential backups – 6 am
Log backups for every 1 hours

Database is crashed on Thursday 4.30 PM

Recovery process:
• Restore latest Sunday full backup with no recovery
• Restore Thursday 6 am differential backup with no recovery
• Restore log backups from 7am to 3 PM with no recovery
• Restore 4 pm log backup with recovery

So, we are able to recover the database up to 4 PM, but we are losing about 30 mins
transactions.

To recover remaining 30 mins of transaction, we can perform tail log backup.. this takes the
backup of all the transaction happened from last successful log backup (Thursday 4 PM) and to
failure point (Thursday 4.30 PM).

If we have database crashed. But the log file healthy.. in that case we can take tail log backup..

Recovery process:
• Perform the manual tail log backup
• Restore latest Sunday full backup with no recovery
• Restore Thursday 6 am differential backup with no recovery
• Restore log backups from 7am to 4 PM with no recovery
• Restore tail log backup with recovery
Demo:
--Tail Log back up and Restore Demonstration:
--Create a Database
CREATE DATABASE [TailLogTest]

--Create a Table
USE [TailLogTest]
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 [TailLogTest].[dbo].[Emp_Details]
VALUES (100, 'Ramesh', 5000)
GO 100

--Issue a Full backup


BACKUP DATABASE TailLogTest TO
DISK = 'F:\SQLLab\backups\taillog\FULL.BAK'
GO

--Insert Data into the table again


INSERT INTO [TailLogTest].[dbo].[Emp_Details] VALUES (200, 'Rajesh', 6000)
GO 100
BACKUP DATABASE TailLogTest TO
DISK = 'F:\SQLLab\backups\taillog\Diff.BAK'
with differential
GO
--Insert Data into the table again
INSERT INTO [TailLogTest].[dbo].[Emp_Details] VALUES (200, 'Rajesh', 6000)
GO 100

--Issue a log backup1


BACKUP LOG TailLogTest TO
DISK = 'F:\SQLLab\backups\taillog\log1.TRN'
GO

--Insert Data into the table again


INSERT INTO [TailLogTest].[dbo].[Emp_Details] VALUES (300, 'Raj', 7000)
GO 100
--Issue a log backup2
BACKUP LOG TailLogTest TO
DISK = 'F:\SQLLab\backups\taillog\log2.TRN'
GO -- thursday 4 pm

--Insert Data into the table again


INSERT INTO [TailLogTest].[dbo].[Emp_Details]
VALUES (400, 'Ram', 8000)
GO 100 - until 4.30 PM

use master
Go
--Set database to offline
ALTER DATABASE [TailLogTest] SET OFFLINE
GO

---DELETE DATA FILE (mdf)

--Set database to offline


ALTER DATABASE [TailLogTest] SET ONLINE
GO

--TAKE TAIL LOG BACKUP


USE MASTER
GO
BACKUP LOG TailLogTest TO DISK
= 'F:\SQLLab\backups\taillog\tail.TRN'
with no_truncate
GO

--Restore all the back ups:


Restore database TailLogTest from
disk ='F:\SQLLab\backups\taillog\Full.bak'
with norecovery ,replace

Restore database TailLogTest from


disk ='F:\SQLLab\backups\taillog\diff.bak'
with norecovery

Restore database TailLogTest from disk ='F:\SQLLab\backups\taillog\Log1.Trn' with norecovery


Restore database TailLogTest from disk ='F:\SQLLab\backups\taillog\Log2.Trn' with norecovery
Restore database TailLogTest from disk ='F:\SQLLab\backups\taillog\Tail.Trn' with recovery
Copy Only:

Weekly Sunday 12:00 – full backups


Daily differential backups – 6 am
Log backups for every 1 hour

On Thursday 4.30 PM, got a request to refresh dev server with a production backup.

On Saturday 4.30 PM, database is crashed..

--step 1
USE master
GO
create database CopyOnlyDemo

--F:\SQLLab\backups\copyonly\Copy_ONLY (sunday full bakup)


BACKUP DATABASE CopyOnlyDemo
TO DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_full1.BAK'

-- as per shedule (weekly on sunday)


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

BACKUP DATABASE CopyOnlyDemo TO


DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_diff1.BAK'
WITH INIT, DIFFERENTIAL --as per shedule (every day at 10:00 AM)

BACKUP LOG CopyOnlyDemo TO


DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_log1.TRN'
WITH INIT --as per shedule (every 1 hour)

--run special full backup


BACKUP DATABASE CopyOnlyDemo TO
DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_full2.BAK'
WITH INIT --(manual adhoc fullbackup on thursday at 4.30 PM)

--resume normal backup process


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

BACKUP DATABASE CopyOnlyDemo TO


DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_diff3.BAK'
WITH INIT, DIFFERENTIAL --(as per schedule on saturday 10.00 am)

BACKUP LOG CopyOnlyDemo TO


DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_log2.TRN'
WITH INIT --(as per schedule log backup)

-- database crashed on saturday at 4 pm


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

RESTORE DATABASE CopyOnlyDemo FROM


DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_diff3.BAK'
WITH NORECOVERY -- latest differential backup i.e saturdays

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


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 40
RESTORE DATABASE is terminating abnormally.

Completion time: 2021-11-10T10:22:04.4837048+05:30*/

RESTORE LOG CopyOnlyDemo FROM


DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_log2.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
--F:\SQLLab\backups\copyonly\Copy_ONLY (sunday full bakup)
BACKUP DATABASE CopyOnlyDemo
TO DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_full1.BAK'

-- as per shedule (weekly on sunday)


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

BACKUP DATABASE CopyOnlyDemo TO


DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_diff1.BAK'
WITH INIT, DIFFERENTIAL --as per shedule (every day at 10:00 AM)

BACKUP LOG CopyOnlyDemo TO


DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_log1.TRN'
WITH INIT --as per shedule (every 1 hour)

--run special full backup


BACKUP DATABASE CopyOnlyDemo TO
DISK='F:\SQLLab\backups\copyonly\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='F:\SQLLab\backups\copyonly\CopyOnlyDemo_diff2.BAK'
WITH INIT, DIFFERENTIAL --(as per schedule on Friday 10.00 am)

BACKUP DATABASE CopyOnlyDemo TO


DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_diff3.BAK'
WITH INIT, DIFFERENTIAL --(as per schedule on saturday 10.00 am)

BACKUP LOG CopyOnlyDemo TO


DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_log2.TRN'
WITH INIT --(as per schedule log backup)

--step 2
RESTORE DATABASE CopyOnlyDemo FROM
DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_full1.BAK' WITH NORECOVERY,
REPLACE
RESTORE DATABASE CopyOnlyDemo FROM
DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_diff3.BAK' WITH NORECOVERY
RESTORE LOG CopyOnlyDemo FROM
DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_log2.TRN' WITH RECOVERY

What is the database and tables maintain the backup and restore history:

Database: MSDB

Tables:
backupset – database name
and backupmediafamily – file location

select database_name from backupset

select physical_device_name from 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
order by bs.backup_finish_date desc

How to bring the database oneline which is stuck in restoring state/readonly?

restore database [CopyOnlyDemo] with recovery

Backup Options:

BACKUP DATABASE CopyOnlyDemo


TO DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_full5.BAK'
with
stats
--copy_only
--differential

12 percent processed.
22 percent processed.
32 percent processed.
42 percent processed.
52 percent processed.
62 percent processed.
72 percent processed.
81 percent processed.
91 percent processed.
100 percent processed.
Processed 336 pages for database 'CopyOnlyDemo', file 'CopyOnlyDemo' on file 1.
Processed 2 pages for database 'CopyOnlyDemo', file 'CopyOnlyDemo_log' on file 1.
BACKUP DATABASE successfully processed 338 pages in 0.278 seconds (9.484 MB/sec).

Completion time: 2021-11-10T10:49:24.0561435+05:30

BACKUP DATABASE [BackupDemo]


TO DISK='F:\SQLLab\backups\backupdemo.BAK'
with
stats=50,
noinit -- creates the new backup set every time
init --overrides the backup set
--copy_only
--differential

Restore commands:
• Restore Verify only – checks wether backup is in valid restorable format or not
restore verifyonly from DISK='F:\SQLLab\backups\backupdemo.BAK'

restore verifyonly from DISK='F:\SQLLab\backups\copyonly\CopyOnlyDemo_full5.BAK'

• Restore header only: This will provide all the metadata of backup – database name,
backup name, backup type, backup date and it provides the backup sets information.
Backup set:

• Restore filelistonly – it will list out all the file information from the backup
restore filelistonly
from DISK='F:\SQLLab\backups\backupdemo.bak'

• Restore Lableonly –This will basically give us the backup media information.

Backup Strategy:
Weekly Sunday 12:00 – full backups
Daily differential backups – 6 am
Log backups for every 1 hour

On Thursday 4.30 PM, a developer accidentally deleted a table from the production.

o Restore Sunday full backup w/n


o Restore Thursday differential backup w/n
o Restore up to 4 PM log backups w/n
o Restore 5 PM log backup w/r, STOPAT 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 = 'Mar 23, 2009 05:31:00 PM'
GO

How to find the status of backup/Restore:


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%'

Fixed Server-Level Roles


The following table shows the fixed server-level roles and their capabilities.
FIXED SERVER-LEVEL ROLES
Fixed server-level role Description
sysadmin Members of the sysadmin fixed server role can perform any activity in the server.
serveradmin Members of the serveradmin fixed server role can change server-wide
configuration options and shut down the server.
securityadmin 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.

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.
processadmin Members of the processadmin fixed server role can end processes that are
running in an instance of SQL Server.
setupadmin Members of the setupadmin fixed server role can add and remove linked servers
by using Transact-SQL statements. (sysadmin membership is needed when using Management
Studio.)
bulkadmin Members of the bulkadmin fixed server role can run the BULK INSERT
statement.

The bulkadmin role or ADMINISTER BULK OPERATIONS permissions is not supported for SQL
Server on Linux. Only the sysadmin can perform bulk inserts for SQL Server on Linux.
diskadmin The diskadmin fixed server role is used for managing disk files.
dbcreator Members of the dbcreator fixed server role can create, alter, drop, and restore
any database.
Public 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 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.

sp_configure
go

sp_configure 'show advanced options', 1


go
reconfigure
go

sp_configure
sp_configure 'max server memory (MB)', 1024
go
reconfigure
go

sp_configure 'xp_cmdshell', 1
go
reconfigure
go

sp_configure 'max server memory (MB)'


go

Database Level Roles:

Fixed-Database Roles
The following table shows the fixed-database roles and their capabilities. These roles exist in all
databases. Except for the public database role, the permissions assigned to the fixed-database
roles cannot be changed.
FIXED-DATABASE ROLES
Fixed-Database role name Description
db_owner Members of the db_owner fixed database role can perform all configuration and
maintenance activities on the database, and can 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.)
db_securityadmin Members of the db_securityadmin fixed database role can modify role
membership for custom roles only and manage permissions. Members of this role can
potentially elevate their privileges and their actions should be monitored.
db_accessadmin Members of the db_accessadmin fixed database role can add or remove
access to the database for Windows logins, Windows groups, and SQL Server logins.
db_backupoperator Members of the db_backupoperator fixed database role can back up the
database.
db_ddladmin Members of the db_ddladmin fixed database role can run any Data Definition
Language (DDL) command in a database.
db_datawriter Members of the db_datawriter fixed database role can add, delete, or change
data in all user tables.
db_datareaderMembers of the db_datareader fixed database role can read all data from all user
tables and views. User objects can exist in any schema except sys and
INFORMATION_SCHEMA.
db_denydatawriter Members of the db_denydatawriter fixed database role cannot 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.

MSDB Roles:
msdb role name Description
db_ssisadmin

db_ssisoperator

db_ssisltduser Members of these database roles can administer and use SSIS. Instances of
SQL Server that are upgraded from an earlier version might contain an older version of the role
that was named using Data Transformation Services (DTS) instead of SSIS. For more
information, see Integration Services Roles (SSIS Service).

dc_admin

dc_operator

dc_proxy Members of these database roles can administer and use the data collector. For
more information, see Data Collection.

PolicyAdministratorRole Members of the db_ PolicyAdministratorRole database role can


perform all configuration and maintenance activities on Policy-Based Management policies and
conditions. For more information, see Administer Servers by Using Policy-Based Management.

ServerGroupAdministratorRole

ServerGroupReaderRole Members of these database roles can administer and use


registered server groups.
dbm_monitor Created in the msdb database when the first database is registered in Database
Mirroring Monitor. The dbm_monitor role has no members until a system administrator assigns
users to the role.

High Availability and Disaster Recovery:

High availability is to ensure the database services are available up and running for applications
all the time.

SLA – Service level agreement

RPO – Recovery process objective – 15 mins


The amount of data loss acceptable in the event of database failure
Ex: RPO 15 mins
The database crashed at 4.30 PM, we are able to recover the data up to 4.15 PM. Then the
SLA for RPO is met

RTO – Recovery Time objective


The time required for recovering the database services
Ex: RTO 4 hours
The database crashed at 4.30 PM, we will have time up to 8.30 PM to recovery the database.

HA solutions:
• Log shipping - Database
• Database Mirroring – Database
• Replication – Database Level/Object level
• Failover clusters – Instance/Server level
• Always On –SQL server 2012 – Database (group of database)

Log Shipping:
Log shipping is basic database level high availability solution which transfers the transactional
log backups from one server (prod) to another server (standby) and it restores in the stand by
server automatically.

Pre requisites to configure Log shipping:


1. Minimum two servers
a. Primary – production: source SQL server in log shipping
b. Secondary – standby: Target SQL server in log shipping

2. Database must be in Full or bulk logged Recovery Model, but recommended is full
recovery model
3. Two network share folders – one in primary and another one is in secondary
4. SQL server agent must be up and running
5. Take a full backup of primary database and restore it in secondary w/n

Add a file to log shipping primary database:

use LsDemo
go
sp_helpfile
USE [master]
GO
ALTER DATABASE [LsDemo] ADD FILE
( NAME = N'LsDemo1', FILENAME = N'F:\SQLLab\LsDemo1.ndf' , SIZE = 8192KB ,
FILEGROWTH = 65536KB )
TO FILEGROUP [PRIMARY]
GO

What will the impact to log shipping ?

The restore job will fail, when it restore the log backup generated after we added the file to
primary database. It will try to create same file to the secondary database in the same location.
Because of the restore job will fail with below error.

How to Fix it :
We need to identify the log backup which is generate after adding the file to primary database

We can identify that using log shipping monitoring—

Last copied file

The red highligheted is the culprit

Restore the log backup using with move option manually-


TUF (Transaction undo file):
Transaction undo file which maintains all the uncommitted transactions from primary and it will
be created when we have secondary database configured in stand by mode and this will
created in the same location of secondary database files.

What will happened of my TUF is deleted ?

Log shipping restore job will fail

How to fix ?
We need to reconfigure log shipping, take a full backup of primary and restore it into secondary
with norecovery

--Primary
backup database [LsDemo]
to disk='F:\SQLLab\logshipping\lsdemo_full.bak'

--secondary
restore database [LsDemo]
from disk='F:\SQLLab\logshipping\lsdemo_full.bak'
with norecovery

Restore job is successful

Log shipping is working fine, some log backups are deleted before they restore into the
secondary:

Restore job fails with LSN Mismath

How to Fix:

We need to take one differential from primary and restore it in secondary w/n
backup database [LsDemo]
to disk='F:\SQLLab\logshipping\lsdemo_diff.bak'
with differential
restore database [LsDemo]
from disk='F:\SQLLab\logshipping\lsdemo_diff.bak'
with norecovery

Restore job is successful:

How to change the secondary database from restoring to stand by Vice versa:

Fail over process in Log shipping:

1. Take a tail log backup (this will take backup of all the transaction happened from last log
backup to failure point)
2. Identify all the pending log backups from primary and sencondary shares and restore
w/n
3. Restore tail log backup w/r

restore database [LsDemo] with recovery

4. Work with application team to point their application to secondary database.

Database Mirroring:

Mirroring also database level solution which transfers transaction logs from one server to
another server and apply those transactions.

Pre requisites:
1. Minimum two server
a. Principal – Production, source in Mirroring
b. Mirror- Stand by , target in Mirroring
c. Witness server (Optional)
2. Database Must be in ‘Full’ Recovery model
3. Take full backup of Principal database and restore it in mirror w/n
4. Take a log backup of principal database and restore in mirror w/n
5. Service account should have GRANT connect permissions on endpoints

Types/Modes of Mirroring:
1. Synchronous:
a. High protection/High Safety – The transaction will be first applied on the mirror server,
then based on commit acknowledgement.. Transaction will be committed on the principal. So
there won’t any transaction loss, at any point of time the principal and mirror will be in sync.
b. High Availability mode – if we add third witness serve to High safety mode, that’s
becomes a high availability mode and we can achieve database level automatic failover. The
witness server continuously monitoring your principal and mirror, when ever principal goes
down, it will bring mirror online automatically.

2. Asynchronous
a. High Performance Mode – The transaction will be immediately committed on the
principal and then send it to mirror and it does not wait for any acknowledgement. There can be
a case, where the transaction is committed successfully on principal but failed on mirror. There
can some data mismatch... if the principal is down, so there can some data loss. The advantage
is performance will be good.

Demo:
backup database [MirrorDemo]
to disk='F:\SQLLab\mirroring\mirrordemo.bak'

backup log [MirrorDemo]


to disk='F:\SQLLab\mirroring\mirrordemo.trn'

restore filelistonly
from disk='F:\SQLLab\mirroring\mirrordemo.bak'

restore database [MirrorDemo]


from disk='F:\SQLLab\mirroring\mirrordemo.bak'
with
move 'MirrorDemo' to 'F:\SQLLab\mirroring\MirrorDemo.mdf',
move 'MirrorDemo_log' to 'F:\SQLLab\mirroring\MirrorDemo_log.ldf',
norecovery

restore log [MirrorDemo]


from disk='F:\SQLLab\mirroring\mirrordemo.trn'
with norecovery
T-SQL Method:
--Run on mirror
alter database [MirrorDemo] set partner='TCP://Ramesh:5022'
--Run on Principal
alter database [MirrorDemo] set partner='TCP://Ramesh:5023'

--Manual failover (run this on principal)


alter database [MirrorDemo] set partner failover

--Remove the mirroring (run this on principal)


Alter database [MirrorDemo] set partner off

Changing modes:

--Run on Principal (high safety to high perfromance)


alter database [MirrorDemo] set partner safety off
--Run on Principal (high perfromance to high safety)
alter database [MirrorDemo] set partner safety full

Adding Witness:

--Run on Principal (Remove the witness)


alter database [MirrorDemo] set witness off
--Run on Principal (add the witness)
alter database [MirrorDemo] set witness='TCP://Ramesh:5024'

Mirroring States:
• Synchronized
• Synchronizing
• Disconnected
• Suspended
• Failover Pending
Mirroring state Description
SYNCHRONIZING The contents of the mirror database are lagging behind the contents of
the principal database. The principal server is sending log records to the mirror server, which is
applying the changes to the mirror database to roll it forward.
At the start of a database mirroring session, the database is in the SYNCHRONIZING state. The
principal server is serving the database, and the mirror is trying to catch up.
SYNCHRONIZED When the mirror server becomes sufficiently caught up to the principal
server, the mirroring state changes to SYNCHRONIZED. The database remains in this state as
long as the principal server continues to send changes to the mirror server and the mirror server
continues to apply changes to the mirror database.
If transaction safety is set to FULLautomatic failover and manual failover are both supported in
the SYNCHRONIZED state, there is no data loss after a failover.
If transaction safety is off, some data loss is always possible, even in the SYNCHRONIZED
state.
SUSPENDED The mirror copy of the database is not available. The principal database is
running without sending any logs to the mirror server, a condition known as running exposed.
This is the state after a failover.
A session can also become SUSPENDED as a result of redo errors or if the administrator
pauses the session.
SUSPENDED is a persistent state that survives partner shutdowns and startups.
PENDING_FAILOVER This state is found only on the principal server after a failover has
begun, but the server has not transitioned into the mirror role.
When the failover is initiated, the principal database goes into the PENDING_FAILOVER state,
quickly terminates any user connections, and takes over the mirror role soon thereafter.
DISCONNECTED The partner has lost communication with the other partner.

Replication
It is basically object level solution which replicates whatever the objects we want replicates.

Jobs created after Distribution database configured:

What is the minimum pre requisites to configure Transactional replication?

Table must have primary key.

What are the different files created in snapshot folder?

Tracer Tokens:
Gives the latency information in replication

Adding new Articles:


->>add the article to publication
EXEC sp_changepublication
@publication = 'Tran_pub',
@property = 'allow_anonymous' ,
@value = 'false'
GO
EXEC sp_changepublication
@publication = 'Tran_pub',
@property = 'immediate_sync' ,
@value = 'false'
GO

run the snapshot

Transaction replication with out snapshot:

Command What It Does

Command Opens the command prompt.

Compmgmt.ms Opens the computer management


c console.

Devmgmt.msc Opens the device manager.

Diskmgmt.msc Opens the disk management tool.

Eventvwr.msc Opens the event viewer.

Fsmgmt.msc Opens shared folders.

Gpedit.msc Opens the group policy editor.

Lusrmgr.msc Opens the local users and groups.

Mailto: Opens the default email client.


Msconfig Opens the system configuration utility.

Msinfo32 Opens the system information utility.

Perfmon.msc Opens the performance monitor.

Regedit Opens the registry editor.

Rsop.msc Opens resultant set of policy.

Secpol.msc Opens local security settings.

Services.msc Opens services utility.

System.ini Windows loading information.

Win.ini Windows loading information.

Winver Shows current version of Windows.

Control Panel Access Run Commands


The following commands access various parts of the Control Panel
directly:

Command What It Does

Appwiz.cpl Add/Remove
Programs

Timedate.cpl Date/Time Properties


Desk.cpl Display Properties

Fonts Fonts Folder

Inetcpl.cpl Internet Properties

Main.cpl Keyboard Properties


keyboard

Main.cpl Mouse Properties

Mmsys.cpl Multimedia Properties

Mmsys.cpl sounds Sound Properties

Sysdm.cpl System Properties

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy