0% found this document useful (0 votes)
6 views192 pages

Final Exam

Uploaded by

il
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)
6 views192 pages

Final Exam

Uploaded by

il
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/ 192

Administration des

bases de données
www.imenemami.com/adminBD/cours.pdf
Plan
1. Introduction
2. Backup and Restore
3. Manage logins and server roles
4. Implement and maintain indexes
5. Import and export data
6. Manage SQL Server Agent
7. Manage and configure databases
8. Identify and resolve concurrency problems
9. Collect and analyse troubleshooting data
10. Audit SQL Server Instances
11. Additional SQL server components
Introduction
Downloading SQL Server Developer 2019
Download a free specialized edition
▪ Basic, Custom or Download Media
▪ Langage: English
▪ Package ISO or CAB

Editions and supported features of SQL Server 2019: Enterprise, Developer, Express,…
https://docs.microsoft.com/en-us/sql/sql-server/editions-and-components-of-sql-server-version-
15?view=sql-server-ver15

Hardware and software requirements: https://docs.microsoft.com/en-us/sql/sql-server/install/hardware-


and-software-requirements-for-installing-sql-server-ver15?view=sql-server-ver15
Introduction
Installing SQL Server Developer 2019
SQL Server Installation Center – Installation
▪ New SQL Server stand-alone installation or add features to an existing installation
▪ Free edition: Developer
▪Features selection: Database Engine Services
▪ Instance Configuration: Default instance
▪ Database Engine Configuration: Add current user
Introduction
Installing SQL Server Management Studio (SSMS)
https://docs.microsoft.com/fr-fr/sql/ssms/download-sql-server-management-studio-
ssms?redirectedfrom=MSDN&view=sql-server-ver15
Introduction
Downloading Demo Database

AdventureWorks
www.imenemami.com/adminBD/sampleBD/AdventureWorks.bak
Backup and Restore
Restoring AdventureWorks with SSMS
T-SQL (Transact-SQL)

RESTORE DATABASE [AdventureWorks2014] FROM


DISK=N'E:\adminBD\Adventure+Works+2014+Full+Database+Backup\AdventureWo
rks2014.bak'
WITH FILE = 1, MOVE N'AdventureWorks2014_Data'
TO N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\AdventureWorks2014_Data.mdf',
MOVE N'AdventureWorks2014_Log' TO N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\AdventureWorks2014_Log.ldf',
NOUNLOAD,
STATS = 5
Backup and Restore
The backup and restore component provides an essential safeguard for protecting critical data
stored in your databases.
Why backup?
▪ Backing up is the only way to protect your data
▪ Recover your data from many failures, such as:
✓ User errors, for example, dropping a table by mistake.
✓ Media and Hardware failures, for example, a damaged disk drive or permanent loss of a server.
✓ Natural disasters.

Restoring a backup consists of creating a database containing exclusively all the data contained in
the backup
T-SQL (Transact-SQL)
j
Backing up Database
Backing up Database
BACKUP DATABASE [AdventureWorks2014] TO DISK =
N'E:\adminBD\DBA\AdventureWorksBackup'
WITH NOFORMAT, NOINIT,
NAME = N'AdventureWorks2014-Full-Database-Backup’,
SKIP, NOREWIND, NOUNLOAD, STATS = 1
Recovery Model
❖ SIMPLE

❖ FULL

❖ BULK LOGGED
Different backup models
❖ FULL BACKUP

❖DIFFERENTIAL BACKUP

❖TRANSACTION LOG BACKUP


Different backup models in SSMS
Point in time recovery
Quiz
••
No Recovery mode is used when restoring multiple backups. This mode allows multiple backups to be applied to the database while it remains offline and unusable. The
modifications are not yet committed to the database version that the user sees. Recovery mode is used either when there's only one backup to restore or when restoring the
last backup in a series of backups (in which No Recovery mode was used for the previous backups). If used after No Recovery mode, this mode commits all the changes to
the database, rolls back any incomplete transactions, and brings the database online, making it ready for use.

Using NORECOVERY and RECOVERY

Typically, we restore full


backups, differential
backups, and transaction log
backups (except for the last
one) in No Recovery mode.
We then restore the final
transaction log backup in
Recovery mode to complete
the process and bring the
database online.
Using NORECOVERY and RECOVERY
BACKUP LOG [AdventureWorks2014] TO DISK = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\Backup\AdventureWorks2014_LogBackup_2022-02-11_07-49-49.bak'
WITH NOFORMAT, NOINIT, NAME = N'AdventureWorks2014_LogBackup_2022-02-11_07-49-49', NOSKIP,
NOREWIND, NOUNLOAD, NORECOVERY , STATS = 5
RESTORE DATABASE [AdventureWorks2014Backup4] FROM DISK = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\Backup\AdventureWorks2014_LogBackup_2022-02-04_08-42-27.bak'
WITH FILE = 2, MOVE N'AdventureWorks2014_Data' TO N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\AdventureWorks2014Backup4_Data.mdf', MOVE
N'AdventureWorks2014_Log' TO N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\AdventureWorks2014Backup4_Log.ldf', NORECOVERY,
NOUNLOAD, STATS = 5
RESTORE DATABASE [AdventureWorks2014Backup4] FROM DISK = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\Backup\AdventureWorks2014_LogBackup_2022-02-04_08-42-27.bak'
WITH FILE = 3, NORECOVERY, NOUNLOAD, STATS = 5
RESTORE LOG [AdventureWorks2014Backup4] FROM DISK = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\Backup\AdventureWorks2014_LogBackup_2022-02-04_08-42-27.bak'
WITH FILE = 4, NORECOVERY, NOUNLOAD, STATS = 5
RESTORE LOG [AdventureWorks2014Backup4] FROM DISK = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\Backup\AdventureWorks2014_LogBackup_2022-02-11_07-49-49.bak'
WITH NOUNLOAD, STATS = 5, STOPAT = N'2022-02-11T07:49:58'
Using NORECOVERY and RECOVERY
use [master]

Go

restore database [AdventureWorks2014] with recovery


Backup an SQL server environment and
system databases
❖ Master
❖ Model
❖ Msdb
❖ TempDB
❖ Resource
Perform backup/restore based on strategies
❖ What you are backing up and how often the data is updated
❖ How much data can you afford to loose
❖ How much space will a full database use ?
❖ Backup redundancy
❖ Reliability
❖ Expiration of the backup
❖ Compression
❖ Encryption
Recover from a corrupted drive
❖ What happens if the backup media is damaged ?

✓ Mirrored Media

✓ Allow the restore to continue despite the errors


oDatabase consistency check
oRepair data loss (single user mode and rollback immediate)
Recover from a corrupted drive
RESTORE DATABASE [AdventureWorks2014backup]
FROM DISK = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\Backup\AdventureWorks2014_LogBackup_2022-01-27_13-
18-47.bak'
WITH CONTINUE_AFTER_ERROR, NORECOVERY, FILE = 6

ALTER DATABASE [AdventureWorks2014backup] SET SINGLE_USER WITH ROLLBACK IMMEDIATE


DBCC CHECKDB ([AdventureWorks2014backup], REPAIR_ALLOW_DATA_LOSS)

ALTER DATABASE [AdventureWorks2014backup] SET MULTI_USER


Quiz
Manage logins and server roles
Create login accounts
❖ Logins
❖ Create a login
❖ Windows authentification / SQL server authentification

CREATE LOGIN [DESKTOP-ICEQ7B9\SQLTest]


FROM WINDOWS
WITH DEFAULT_DATABASE=[AdventureWorks2014]
Manage access to the server
❖ Serveradmin
❖ Alter settings, shutdown, alter any endpoint, create any endpoint

❖Securityadmin
❖ Alter any login

❖Processadmin
❖ Alter any connection

❖Setupadmin
❖ Alter any linked server

❖Bulkadmin
❖ Administer Bulk operations
Manage access to the server
❖ Diskadmin
❖ Alter resources

❖Dbcreator
❖ Alter any database, create any database

❖Sysadmin
❖ Can perform any activity on the server

❖Public
❖ No server-level permission (except view any database and connect permission)

ALTER SERVER ROLE [sysadmin] ADD MEMBER [DESKTOP-ICEQ7B9\SQLTest]


ALTER SERVER ROLE [sysadmin] DROP MEMBER [DESKTOP-ICEQ7B9\SQLTest]
Create and maintain user-defined server roles
❖ Create my own server rôle
❖ Name
❖ Owner: AUTHORIZATION
❖ Securables (Endpoints, logins, servers, availability groups, server roles)

CREATE SERVER ROLE [myServerRole1]


ALTER SERVER ROLE [myServerRole1] ADD MEMBER [DESKTOP-ICEQ7B9\SQLTest]
GRANT ALTER ANY LOGIN TO [myServerRole1]
Create database user accounts
❖ Add user account

CREATE USER [SQLTest] FOR LOGIN [DESKTOP-ICEQ7B9\SQLTest] WITH DEFAULT_SCHEMA=[dbo]


Fixed database-level roles
❖ db_owner
❖ Has all permission in the database

❖db_securityadmin
❖ Alter any role, create role, view definition

❖db_accessadmin
❖Alter any user, connect

❖db_backupoperator
❖Backup database, backup log, checkpoint

❖db_ddladmin
❖Data definition Langage commands in the database
Fixed database-level roles
❖ db_datawriter
❖ Grant Insert, update, delete on database
❖db_denydatawriter
❖Deny Insert, update, delete on database
❖db_datareader
❖Grant Select on database
❖db_denydatareader
❖Deny Select on database
❖public
❖No database level permissions (except some database permissionss for example: view any column
master key definition and select permission on system tables)

ALTER ROLE [db_datareader] ADD MEMBER [SQLTest]


User database-level roles
❖ New database rôle
❖Name
❖Owner
❖Members
❖Secrurables
❖Permisssions (Alter, Control, select, insert, update, select, references, execute, take ownership…)

CREATE ROLE [myNewDBRole]


ALTER ROLE [myNewDBRole] ADD MEMBER [SQLTest]
GRANT SELECT ON [HumanResources].[Department] TO [myNewDBRole]
DENY SELECT ON [HumanResources].[Employee] TO [myNewDBRole]
Creating and using schemas
USE [AdventureWorks2014]
GO
CREATE SCHEMA [myNewSchema] AUTHORIZATION [SQLTest]
GO

❖ Schema owner
Creating access to server/database with
least privilege
❖ Principle of least privilege
❖ Use fixed server roles
❖ Restrict use of sysadmin
❖ Assign permissions to role
❖ Use stored procedures and functions
❖Permission statements
❖ Grant, Deny, Revoke (REVOKE SELECT ON HumanResources.Department TO myNewDBRole)

❖ Owernership chains
Protect objects from being modified
use [AdventureWorks2014]

DENY ALTER ON [Production].[Culture] TO [SQLTest]


DENY CONTROL ON [Production].[Culture] TO [SQLTest]
DENY DELETE ON [Production].[Culture] TO [SQLTest]
DENY INSERT ON [Production].[Culture] TO [SQLTest]
DENY TAKE OWNERSHIP ON [Production].[Culture] TO [SQLTest]
DENY UPDATE ON [Production].[Culture] TO [SQLTest]
Quiz
Implement and maintain indexes
What are indexes ?
❖ Clustred indexes
❖ Unique column properties

❖ Non-clustred indexes
❖Non-unique
Implement indexes
CREATE CLUSTERED INDEX [IX_NewTable_ID] ON [dbo].[NewTable]
(
[ID] ASC
)

CREATE NONCLUSTERED INDEX [IX_NewTable_Color] ON [dbo].[NewTable]


(
[ColorName] ASC
)
INCLUDE([ObjectName])

DROP INDEX [IX_NewTable_ID] ON [dbo].[NewTable]


Fragmentation
A B
ObjectName ColorName ID ObjectName ColorName ID
ObjectName ColorName ID
Table Black 1
Table Brown 2
Computer Gold 3
Printer Black 4
Printer Red 5 C D
Bookcase Brown 6 ObjectName ColorName ID ObjectName ColorName ID
Computer Black 7
Book White 8
Book Green 9
Table Glod 10
Fragmentation
A B
ObjectName ColorName ID ObjectName ColorName ID
ObjectName ColorName ID
Table Black 1
Table Brown 2 Computer Gold 3
Computer Gold 3 Table Black 1
Printer Black 4 Table Brown 2
Printer Red 5 C D
Bookcase Brown 6 ObjectName ColorName ID ObjectName ColorName ID
Computer Black 7
Book White 8
Book Green 9
Table Glod 10
Fragmentation
A B
ObjectName ColorName ID ObjectName ColorName ID ObjectName ColorName ID
Table Black 1
Table Brown 2 Computer Gold 3 Table Black 1

Computer Gold 3 Printer Black 4 Table Brown 2

Printer Black 4 Printer Red 5

Printer Red 5 C D
Bookcase Brown 6 ObjectName ColorName ID ObjectName ColorName ID
Computer Black 7
Bookcase Brown 6
Book White 8
Computer Black 7
Book Green 9
Table Glod 10
Fragmentation A B
ObjectName ColorName ID ObjectName ColorName ID
ObjectName ColorName ID
Table Black 1 Computer Gold 3 Table Black 1
Table Brown 2 Printer Black 4 Table Brown 2
Computer Gold 3 Printer Red 5 Table Gold 10
Printer Black 4 C D
ObjectName ColorName ID ObjectName ColorName ID
Printer Red 5
Bookcase Brown 6 Book White 8 Book Green 9
Computer Black 7 Bookcase Brown 6
Book White 8 Computer Black 7
Book Green 9
Book (Green) D
Table Glod 10
Book (White), Computer (Black) C
Computer(Gold), Printer A
Table B
Fragmentation A B
ObjectName ColorName ID ObjectName ColorName ID
ObjectName ColorName ID
Table Black 1 Computer Gold 3 Table Black 1
Table Brown 2 Table Brown 2
Computer Gold 3 Printer Red 5 Table Gold 10
Printer Black 4 C D
ObjectName ColorName ID ObjectName ColorName ID
Printer Red 5
Bookcase Brown 6 Book White 8 Book Green 9
Computer Black 7 Bookcase Brown 6
Book White 8 Computer Black 7
Book Green 9
Book (Green) D
Table Glod 10
Book (White), Bookcase (Brown), Computer (Black) C
Computer (Gold), Printer A
Table B
Fragmentation A B
ObjectName ColorName ID ObjectName ColorName ID
ObjectName ColorName ID
Table Black 1 Computer Gold 3 Table Black 1
Table Brown 2 Table Brown 2
Computer Gold 3 Printer Red 5 Table Gold 10
Printer Red 5 C D
ObjectName ColorName ID ObjectName ColorName ID
Bookcase Brown 6
Computer Black 7 Book White 8 Book Brown 11
Book White 8 Bookcase Brown 6 Book Green 9
Book Green 9 Computer Black 7
Table Glod 10
Book (Brown) Book (Green) D
Book Brown 11
Book (White), Compter (Black) C
Computer(Gold), Printer A
Table B
ObjectName ColorName ID

Bookcase Brown 6 E
Computer Black 7

Fragmentation A B
ObjectName ColorName ID ObjectName ColorName ID
ObjectName ColorName ID
Table Black 1 Computer Gold 3 Table Black 1
Table Brown 2 Table Brown 2
Computer Gold 3 Printer Red 5 Table Gold 10
Printer Red 5 C D
ObjectName ColorName ID ObjectName ColorName ID
Bookcase Brown 6
Computer Black 7 Book White 8 Book Brown 11
Book White 8 Book Yellow 12 Book Green 9
Book Green 9
Book (Brown) Book (Green) D
Table Glod 10
Book (White), Book(Yellow) C
Book Brown 11
BookCase Computer (Black) E
Book Yellow 12
Computer(Gold), Printer A
Table B
Fragmentation
❖ Reorganize
Computer(Gold), Printer A ObjectName ColorName ID
Table B
Book (White), Book(Yellow) C Computer Gold 3

Book (Brown), Book (Green) D


BookCase, Computer (Black) E Printer Red 5

Book (Brown) Book (Green) D ObjectName ColorName ID


Book (White), Book(Yellow) C
BookCase, Computer (Black) E Computer Gold 3

Computer(Gold), Printer A Printer Red 5

Table B
Fragmentation
❖ Rebuild
❖ Drops the index and starts from scratch
❖ Sort out (Book, Bookcase, Computer,…)

Only use rebuild when it is absolutely necessary, when the fragmentation has reached such an
extent that you just have to delete it and start again.
Fragmentation
❖ Reorganize

ALTER INDEX [IX_NewTable_ID] ON [dbo].[NewTable] REORGANIZE

❖ Rebuild

ALTER INDEX [IX_NewTable_ID] ON [dbo].[NewTable] REBUILD PARTITION = ALL WITH


(ONLINE = ON)
How fragmented are the indexes
select * from
sys.dm_db_index_physical_stats(DB_ID('AdventureWork
s2014'),OBJECT_ID('[Person].[Address]'),null,null,n
ull) as stats
join sys.indexes as si
on stats.object_id=si.object_id and
stats.index_id=si.index_id
Fill Factor
❖ When you are creating a page in a first place, don’t make it 100 % full.
❖ Reorgonize less
❖ Rebuild less

ALTER INDEX [IX_NewTable_Color] ON [dbo].[NewTable] REBUILD PARTITION =


ALL WITH (FILLFACTOR = 80)
Optimise indexes
CREATE NONCLUSTERED INDEX [NCDemo] ON [Person].[Address]
(
[AddressID] ASC
)
WHERE city='London'
Identify unused indexes
❖ user_seeks
❖ user_scans
❖ user_lookups
❖ user_updates

select * from sys.dm_db_index_usage_stats as stats


join sys.indexes as si
on stats.object_id=si.object_id and stats.index_id=si.index_id
Disable or drop unused indexes
ALTER INDEX [IX_NewTable_ID] ON [dbo].[NewTable] DISABLE

DROP INDEX [IX_NewTable_Color] ON [dbo].[NewTable]


Quiz
Import and export data
Transfer data
❖ Detach and attach a database

EXEC master.dbo.sp_detach_db @dbname = N'AdventureWorks2014backup’

CREATE DATABASE [AdventureWorks2014backup] ON


( FILENAME = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\AdventureWorks2014backup_Data.mdf' ),
( FILENAME = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\AdventureWorks2014backup_Log.ldf' )
FOR ATTACH
Transfer data
❖ Import flat file

❖ Import data

❖Export data

❖Copy database (SQL Server Agent)


Bulk Insert
create table dbo.flatFile (Heading1 varchar(50), Heading2 varchar(50))

bulk insert [dbo].[flatFile] from 'E:\newFiletest.txt'


with
(FIELDTERMINATOR=',',
ROWTERMINATOR='\n',
FIRSTROW=2
)
Quiz
Manage SQL Server Agent
Create, maintain and monitor jobs
❖ Automation

❖ Enable/Start SQL Server Agent

❖Job: Full backup every day at midnight


Create, maintain and monitor jobs
❖ Job steps
Create, maintain and monitor jobs
Create, maintain and monitor jobs
❖ Job schedule
Administer jobs
USE msdb

Go

select * from sysjobs

select * from sysjobsteps

select * from syssessions

select * from sysjobactivity

select * from sysjobhistory

select * from sysschedules


RAISERROR
❖ User-defined error
RAISERROR (id, severitynumber, statenumber) (id >= 50000, severity <=10
information, >=19 fatal error , state between 0 and 255)

select * from sys.messages

exec sp_addmessage 50001, 16, 'Iam raising an alert’

RAISERROR (50001, 16, 1)


Alerts
❖ SQL Server event alert

❖ Server performance condition alert

❖ WMI (Windows Management Instrumentation) event alert


Create Event Alerts
Create Event Alerts
RAISERROR and event Alerts
RAISERROR (50001, 16, 1) WITH LOG
Create alerts on critical server condition
Operators
❖ Database Mail
❖Configuration

❖ Set up database mail


❖E-mail profile
❖ SMTP accounts
Database mail configuration
Database mail configuration
❖ SQL Server Agent – Enable mail profile
Adding operators to jobs and alerts
Quiz
Manage and configure databases
Autoclose and Autoshrink
❖ Autoclose
ALTER DATABASE [AdventureWorks2014] SET AUTO_CLOSE ON

❖ Autoshrink
ALTER DATABASE [AdventureWorks2014] SET AUTO_SHRINK ON
Autoclose and Autoshrink
Design multiple file groups
❖Big Database: one filegroup ?
❖Primary data file (.mdf)
❖ Secondary data file (.ndf)

❖ Filegroups
❖ Data Files on different filegroups
Creating database with multiple
filegroups
Creating database with multiple
filegroups
Creating database with multiple
filegroups
CREATE DATABASE [DBAdatabase]

CONTAINMENT = NONE

ON PRIMARY

( NAME = N'DBAdatabase', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\DBAdatabase.mdf' ,

SIZE = 102400KB , FILEGROWTH = 65536KB ),

FILEGROUP [Secondary]

( NAME = N'DBAdatabase2', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\DBAdatabase2.ndf' ,

SIZE = 102400KB , FILEGROWTH = 65536KB )

LOG ON

( NAME = N'DBAdatabase_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\DBAdatabase_log.ldf'


,

SIZE = 8192KB , FILEGROWTH = 65536KB )

GO

IF NOT EXISTS (SELECT name FROM sys.filegroups WHERE is_default=1 AND name = N'Secondary')

ALTER DATABASE [DBAdatabase] MODIFY FILEGROUP [Secondary] DEFAULT


Manage file space including adding new
filegroups
Manage file space including adding new
filegroups
ALTER DATABASE [DBAdatabase] ADD FILEGROUP [third]

ALTER DATABASE [DBAdatabase] ADD FILE ( NAME = N'DBAdatabase3',


FILENAME = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\DBAdatabase3.ndf' , SIZE = 8192KB ,
FILEGROWTH = 65536KB )
TO FILEGROUP [third]
Manage file space - moving objects
CREATE CLUSTERED INDEX [ClusteredIndex-
20220407-111813] ON [dbo].[NewTable]
(
[heading1] ASC, [heading2] ASC
)
ON [third]
Manage file space - moving objects
CREATE TABLE [dbo].[NewTable2]
(
Heading1 int, heading2 int
)
ON [third]
Partitionning
❖ Create filegroups

❖ Create partition function

❖Create scheme partition (uses partion function and filegroups)

❖Create/modify tables/indexes using partition scheme


Partitionning
Partitionning
Partitionning
BEGIN TRANSACTION

CREATE PARTITION FUNCTION [PartitionFunctionPartition](date) AS RANGE RIGHT FOR VALUES (N'2018-01-01', N'2022-01-01’)

CREATE PARTITION SCHEME [PartitionSchemeParttition] AS PARTITION [PartitionFunctionPartition] TO ([PRIMARY], [Secondary], [third])

CREATE CLUSTERED INDEX [ClusteredIndex_on_PartitionSchemeParttition_637849306408154072] ON [dbo].[partitionTable]

[dateOfEntry]

) ON [PartitionSchemeParttition]([dateOfEntry])

DROP INDEX [ClusteredIndex_on_PartitionSchemeParttition_637849306408154072] ON [dbo].[partitionTable]

COMMIT TRANSACTION
Partitionning
select *, $PARTITION.PartitionFunctionPartition(dateOfEntry) as PartitionNumber
from [dbo].[partitionTable]

select $PARTITION.PartitionFunctionPartition('2018-01-01')
Filegroup backup
❖ How can you manage a VERY BIG database ?
❖ How do you back that up ? It is huge (hours, days)
❖Not to backup the entirety
BACKUP DATABASE [DBAdatabase]
FILEGROUP = N'Secondary' TO
DISK = N'C:\Program Files\
Microsoft SQL Server\MSSQL15.MSSQLSERVER
\MSSQL\Backup\DBAdatabase.bak'
Filegroup and Page restore
RESTORE DATABASE [DBAdatabase] FILE = N'DBAdatabase2' FROM DISK = N'C:\Program
Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\Backup\DBAdatabase.bak'
WITH FILE = 1, NOUNLOAD, STATS = 10

RESTORE DATABASE [AdventureWorks2014] PAGE='1:12’


FROM DISK = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\Backup\AdventureWorks2014_LogBackup_2022-02-
28_07-58-53.bak'
Manage log file growth
select * from sys.dm_db_log_space_usage
❖ Add additional log files
❖ Do a transaction log backup
❖ Shrinking the file
dbcc shrinkfile(DBAdatabase_log,4)

❖ Enable Autogrowth
DBCC
dbcc shrinkdatabase(DBAdatabase,20)

❖ File Id
◦ select * from sys.database_files

dbcc shrinkfile(3,truncateonly)

dbcc shrinkfile(DBAdatabase3,emptyfile)
Implement and configure contained
databases and logins
❖ Moving database from one particular instance of sql server to another

❖ A contained database
❖ A database that is isolated from the instance of SQL Server

❖ Contained database users


❖Configured directly at the database level and don’t require an associated login
❖ Authenticate users by passwords
Implement and configure contained
databases and logins
Implement and configure contained
databases and logins
EXEC sys.sp_configure N'contained database authentication', N'1'
GO
RECONFIGURE WITH OVERRIDE

ALTER DATABASE [DBAdatabase] SET CONTAINMENT = PARTIAL WITH NO_WAIT


Implement and configure contained
databases and logins
❖ SQL users with password

CREATE USER [ContainedUser] WITH PASSWORD=N'ContainedUser'


Quiz
Data Compression
❖ Page compression
❖ Row compression
✓ Reduce metadata overhead
✓ Uses variable-length storage for numeric-based types
✓ Uses variable-length character strings

❖Prefix compression
✓ Stores commonly used prefixes elsewhere
✓ Prefix values are replaced by a reference to the prefix

❖Dictionary compression
❖ Replaces commonly used values
Data Compression
Data Compression
ALTER TABLE [HumanResources].[Employee] REBUILD PARTITION = ALL
WITH
(DATA_COMPRESSION = PAGE
)
ALTER INDEX [IX_Employee_OrganizationNode] ON
[HumanResources].[Employee] REBUILD PARTITION = ALL WITH
(DATA_COMPRESSION = PAGE)

exec sp_estimate_data_compression_savings [HumanResources], [Employee], 1,


null, 'PAGE'
Sparse columns
❖ Optimized space for null values
❖Reduce the space requirements for null values

❖ Sparse columns require more storage space for non-NULL values than the space required for
identical data that is not marked SPARSE

❖what percent of the data must be NULL for a net space savings ?
❖Estimated space savings by data type

https://docs.microsoft.com/en-us/sql/relational-databases/tables/use-sparse-columns?view=sql-
server-ver15
Sparse columns
create table sparsetable (heading1 nvarchar(10) sparse null)
Columnstore Indexes
❖ Clustered and nonclustered columnstore index

CREATE NONCLUSTERED COLUMNSTORE INDEX [NonClusteredColumnStoreIndex-20220414-


122043] ON [dbo].[NewTable]
(
[newcolumn]
)

CREATE CLUSTERED COLUMNSTORE INDEX [ClusteredColumnStoreIndex-20220414-


122043] ON [dbo].[NewTable]
Quiz
Identify and resolve concurrency problems
Diagnose blocking, live locking and
deadlocking
❖ Blocking – the second connection is blocked

❖Live locking- Shared locks prevent another process from acquiring exclusive locks (but one
process wins then the next process wins)

❖Deadlocking – two processes compete for the same resource


Diagnose deadlocking - practise
❖Transaction 1 –Q-58 ❖Transaction 2 – Q-59
begin transaction begin transaction
1
update [dbo].[Table1] update [dbo].[Table2]
2
set column1=column1+1 set ColorName='Brown2'
where ColorName='Brown'
select * from [dbo].[Table2]
4 select * from [dbo].[Table1] 3
Diagnose deadlocking - practise
exec sp_who2
Diagnose deadlocking - practise
❖ Activity Monitor
Monitor via DMV (Dynamic management
view)
select resource_type, request_status, request_mode, request_session_id from
sys.dm_tran_locks
Monitor via DMV (Dynamic management
view)
Transaction (Process ID 58) was deadlocked on lock resources with
another process and has been chosen as the deadlock victim
Monitor via DMV (Dynamic management
view)
select * from sys.dm_os_waiting_tasks
where session_id in(58,59)

select * from sys.dm_exec_requests


Examine deadlocking issues using the
SQL server logs
❖ Trace flags
❖ Flag 1222 returns deadlock information
❖ Flag 1204 provides information about the nodes involved in the deadlock

dbcc traceon(1204,-1)
dbcc traceon(1222,-1)
Examine deadlocking issues using the
SQL server logs
Examine deadlocking issues using the
SQL server logs
Quiz
Collect and analyse troubleshooting data
Collect trace data by using SQL Server
Profiler
❖ SQL Server Profiler

❖ Finding problem slow queries

❖ Capturing a series of T-SQL statements that lead to a problem

❖Analyzing the performance of SQL server

❖ Correlating performance counters to diagnose problems


Collect trace data by using SQL Server
Profiler
Collect trace data by using SQL Server
Profiler
Collect trace data by using SQL Server
Profiler
Use XEvents (Extended Events)
Use XEvents (Extended Events)
Use XEvents (Extended Events)
Use XEvents (Extended Events)
Use XEvents (Extended Events)
Know what affects performance
❖ Blocking, deadlocking and locking

❖ DMVs

❖ Performance monitor
Diagnose performance problems with
DMVs
❖CPU usage
select current_workers_count, work_queue_count, pending_disk_io_count
from sys.dm_os_schedulers
where scheduler_id <=255

❖ Buffer Pool/ Data cache


select count(database_id)*8/1024.0 as [cache in MB], database_id
from sys.dm_os_buffer_descriptors
group by database_id
Diagnose performance problems with
DMVs
select * from sys.sysperfinfo
where object_name like
'SQLServer:Buffer Manager%'
order by counter_name
Collect performance data by using
Performance Monitor
Collect performance data by using
Performance Monitor
Collect performance data by using
Performance Monitor
❖ Processor: % Privileged Time
❖The amount of time the processor spends on processing of input/output requests from SQL Server

❖ Processor: % User Time


❖ The percentage of time the processor spends on executing things like sql server

❖ System: Processor queue length


❖ The number of threads waiting for processing time (what is being the bottleneck)
Collect performance data by using
Performance Monitor
❖ Data collector sets
IO, Memory and CPU bottlenecks
❖ Memory
❖Memory: Available bytes
❖Memory: Pages/sec
❖ Process: Working Set
❖SQL Server: Buffer Manager: Buffer Cache Hit Ratio
❖SQL Server: Buffer Manager: Databases Pages
❖SQL Server: Memory Manager: Total Server Memory

❖ Processor
❖Processor : % Privildged Time
❖Processor : % User Time
❖ System: Processor queue length
IO, Memory and CPU bottlenecks
❖ IO Primary
❖PhysicalDisk: Avg Disk sec/Write
❖PhysicalDisk: Avg Disk sec/Read

❖ IO Secondary
❖PhysicalDisk: Avg Disk queue length
❖PhysicalDisk: Disk Bytes/sec
❖ PhysicalDisk: Disk Transfer/sec
Quiz
Audit SQL Server Instances
Implement a security strategy for
auditing and controlling the instance
❖ Server-level audits

❖ Database-level audits

❖Components of audits
❖ Audit itself
❖ Server audit specification
❖ Database audit specification
❖ Target
Configure server audits
Configure server audits – monitor the
attemps to connect
Configure server audits – log file
Monitor elevated privileges
❖A fixed list of what the privileges currently are:
select princ.name, perm.permission_name
from sys.server_permissions as perm join
sys.server_principals as princ on
perm.grantee_principal_id =
princ.principal_id

❖ Audit action type (examples for privileges)


❖Database object permission change
❖ Database object access group
❖ Database role member change group
❖Database change group
Configure database-level audit – track
who modified an object
Additional SQL server components
Full-text indexing
▪ Additional Features: Full text and semantic extraction for search

▪ Define a full-text index on a column or columns


Full-text indexing
select *
from [Person].[Address]
where CONTAINS(AddressLine1, 'Drive’)

select *
from [Person].[Address]
where CONTAINS(AddressLine1, 'Drive NEAR Glaze')
Filestream
▪ Allows to store unstructed data like documents and images on the file system.
▪ Filestream is not automatically enabled
Filestream
exec sp_configure filestream_access_level, 2
reconfigure

▪ Restart SQL server service

▪Create a filestream database


Filestream
Filestream
CREATE DATABASE [filestramdatabase]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'filestramdatabase', FILENAME = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\filestramdatabase.mdf' , SIZE = 8192KB , FILEGROWTH =
65536KB ),
FILEGROUP [filestreamdata] CONTAINS FILESTREAM
( NAME = N'filestreamdata', FILENAME = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\filestreamdata' )
LOG ON
( NAME = N'filestramdatabase_log', FILENAME = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\filestramdatabase_log.ldf' , SIZE = 8192KB , FILEGROWTH =
65536KB )
GO
FileTable
▪FileTables remove a significant barrier to the use of SQL Server for the storage and management
of unstructured data

▪Store files and documents in special tables in SQL Server called FileTables

▪ Every row in a FileTable represents a file or a directory

▪ Require a non-transactional access


FileTable
ALTER DATABASE [filestramdatabase]
SET FILESTREAM(NON_TRANSACTED_ACCESS = FULL, DIRECTORY_NAME = 'MyFiles')

create table dbo.myfiles as FILETABLE


WITH(FileTable_Directory='MyFiles', FileTable_Collate_Filename=database_default);

INSERT INTO dbo.myfiles(name,file_stream)


SELECT 'mytxtfile.txt', x.* from OPENROWSET (BULK 'c:\mytxtfile.txt', SINGLE_BLOB) AS x

You might also like