Cours BD2
Cours BD2
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
AdventureWorks (AdventureWorks.bak)
https://learn.microsoft.com/en-us/sql/samples/adventureworks-install-configure?view=sql-
server-ver16&tabs=ssms
Backup and Restore
Restoring AdventureWorks with SSMS
T-SQL (Transact-SQL)
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
Go
Mirrored Media
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)
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 permissions for example: view any column
master key definition and select permission on many individual system tables)
Owernership chains
Protect objects from being modified
use [AdventureWorks2014]
Non-clustred indexes
Non-unique
Implement indexes
CREATE CLUSTERED INDEX [IX_NewTable_ID] ON [dbo].[NewTable]
(
[ID] ASC
)
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
Table Gold 9
Book Green 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 9
Printer Black 4 C D
ObjectName ColorName ID ObjectName ColorName ID
Printer Red 5
Bookcase Brown 6 Book White 8 Book Green 10
Computer Black 7 Bookcase Brown 6
Book White 8 Computer Black 7
Table Gold 9 Book (Green) D
Book Green 10 Book (White), Bookcase, 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
Table Gold 9
Book (Green) D
Book Green 10
Book (White), Bookcase, 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
Table Gold 9 Computer Black 7
Book Green 10
Book (Brown) Book (Green) D
Book Brown 11
Book (White), Bookcase, 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
Table Gold 9
Book (Brown) Book (Green) D
Book Green 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
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
Rebuild
Import data
Export data
Go
https://chatgpt.com/c/6828eba8-a66c-8001-9cec-70b6183cf113
Key Components
Big Database: one filegroup ?
Primary Filegroup:
Primary data file (.mdf) Contains the primary data file (.mdf)
Contains system tables by default
Created automatically with every database
Secondary data file (.ndf)
Secondary Filegroups:
Contain secondary data files (.ndf)
Can be created for specific purposes
Filegroups Can be set as the default filegroup
CONTAINMENT = NONE
ON PRIMARY
FILEGROUP [Secondary]
LOG ON
GO
IF NOT EXISTS (SELECT name FROM sys.filegroups WHERE is_default=1 AND name = N'Secondary')
Heading1 int, heading2 int All data for this table will be stored in the DBAdatabase3.ndf file
)
ON [third]
Partitionning
Partitioning is a database process that divides large tables into smaller, more manageable
pieces while maintaining a single logical view of the data.
Create filegroups
Partitionning before this, you should first have had created your filegroups
BEGIN TRANSACTION
Defines how to
CREATE PARTITION FUNCTION [PartitionFunctionPartition](date) AS RANGE RIGHT FOR VALUES (N'2018-01-01', N'2022-01-01’)
split the data by
date ranges
CREATE PARTITION SCHEME [PartitionSchemeParttition] AS PARTITION [PartitionFunctionPartition] TO ([PRIMARY], [Secondary], [third])
[dateOfEntry]
Purpose: Physically reorganizes the table according to the partition scheme
) ON [PartitionSchemeParttition]([dateOfEntry])
COMMIT TRANSACTION
Partitionning
select *, $PARTITION.PartitionFunctionPartition(dateOfEntry) as PartitionNumber
from [dbo].[partitionTable] Querying Partitioned Data
(VIEWING PARTITION DISTRIBUTION)
select $PARTITION.PartitionFunctionPartition('2018-01-01')
Returns which partition a specific value would go into (returns 2 in this case)
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'
File/Filegroup Restore: Physical corruption in specific files/groups.
Transaction Log Restore: Recover from logical errors (e.g., DROP TABLE).
Manage log file growth When log space used exceeds 70-80%, consider expanding
If log reuse wait is not "NOTHING", investigate why logs aren't
truncating
DBCC
Operates dbcc shrinkdatabase(DBAdatabase,20) Shrinks all database files (data and log)
on all
database Target Specification:Percentage of free space 20 = target percentage of free space to leave after shrink
files at once
A contained database
A database that is isolated from the instance of SQL Server
Values <= 1
Requires
Binary Configuration Option: RECONFIGURE to take
effect:
0 = Disabled (default)
sql
1 = Enabled RECONFIGURE;
Page compression
Row compression Typically provides moderate space savings
Reduce metadata overhead
Data Compression Options
Uses variable-length storage for numeric-based types 1. Row Compression
Uses variable-length character strings Eliminates unused space in fixed-length data types
Best for: Tables with many fixed-length columns (int, char, etc.)
Compression ratio: Typically 20-40% space savings
Prefix compression 2. Page Compression (Includes Row Compression plus additional
Stores commonly used prefixes elsewhere techniques)
Prefix values are replaced by a reference to the prefix +++Provides higher compression than row alone
Best for: Read-heavy tables with repetitive data
Compression ratio: Typically 40-60% space savings
Dictionary compression A/Prefix compression:
Replaces commonly used values Stores common/repeating prefixes in page header separately
++++Replaces values with references to prefixes
B/Dictionary compression:
Identifies repeated values across columns
Stores them in a dictionary
Type Storage SavingsBest Use Cases
Row Compression 20-40%OLTP with fixed-length columns
Page Compression 40-60%Read-heavy tables with repeats
Columnstore 90%+Analytical workloads
Backup Compression50-80%All backup operations
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)
Sparse columns require more storage space for non-NULL values than the space required for
identical data that is not marked SPARSE
Best when: High percentage of NULLs (typically >60%)
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)
Types of Columnstore Indexes
1. Clustered Columnstore Index: Fundamental structure of the entire table (replaces traditional row storage) Best for: Operational
analytics (combining OLTP and analytics)
2. Nonclustered Columnstore Index: Secondary index on a traditional rowstore table: Best for: Operational analytics (combining
OLTP and analytics) Columnstore indexes are a specialized type of index that stores
data column-wise (vertically) rather than row-wise (horizontally),
Columnstore Indexes offering significant performance benefits for analytical queries and
data warehousing workloads.
Blocking – the second connection is blocked One session holds a lock and another is waiting for it to be released.
Live locking- Shared locks prevent another process from acquiring exclusive locks (but one
process wins then the next process wins) Transactions are not blocked, but continue to interfere with each other and no
progress is made.
Transactions keep retrying but none succeed; . Processes repeatedly block each other while competing for
Example: Two processes keep yielding to each other in a loop. resources, but no progress is made
SQL Server picks one as the deadlock victim. Symptoms: "Deadlock victim" errors in logs
-- Or use sp_who2
EXEC sp_who2;
Diagnose deadlocking - practise
Transaction 1 –Q-58 Transaction 2 – Q-59
begin transaction begin transaction
1
update [dbo].[Table1] update [dbo].[Table2] -- Acquires lock on Table2
2
set column1=column1+1 -- Acquires lock on Table1 set ColorName='Brown2'
where ColorName='Brown'
select * from [dbo].[Table2]
-- Tries to acquire lock on Table2 4 select * from [dbo].[Table1] 3
Deadlock Occurs Because: -- Tries to acquire lock on Table1
Each transaction holds an exclusive (X) lock the other needs
The SQL Server instance does not shut down—only the victim
transaction fails.
-1 makes it global
Collect and analyse troubleshooting data
Collect trace data by using SQL Server
Profiler
SQL Server Profiler
+ to diagnose sql profiler trace
-- Start it
Use XEvents (Extended Events)
ALTER EVENT SESSION [Deadlocks] ON SERVER
STATE = START;
-- Query results
SELECT CONVERT(xml, event_data) AS DeadlockGraph
FROM
sys.fn_xe_file_target_read_file('DeadlockLogs*.xel',
NULL, NULL, NULL);
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 current_workers_count, -- Number of active workers
where scheduler_id <=255 work_queue_count, -- Tasks waiting for worker threads
pending_disk_io_count -- Pending I/O operations
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
Core Audit Components
Server-level audits Component Description Example
Audit Container for audit specificationsCREATE SERVER AUDIT
Server Audit Specification What to audit at instance levelLogins, role changes
Database Audit SpecificationWhat to audit within a databaseTable access,
Database-level audits schema changes
Target Where audit data is storedFile, Windows Event Log,
Security Log
Components of audits
1. Audit Container (The "Recorder")
Audit itself
What it is: The master configuration that defines WHERE audit data gets stored
Server audit specification
Database audit specification
Target Storage Targets
Configure server audits
Configure server audits – monitor the
attemps to connect
Configure server audits – log file
Monitor elevated privileges
View A fixed list of what the privileges currently are:
Current select princ.name, perm.permission_name
Privileges
from sys.server_permissions as perm join
sys.server_principals as princ on
perm.grantee_principal_id =
princ.principal_id
This gives you:Who has what server-level privileges
(e.g., ALTER ANY LOGIN, VIEW SERVER STATE, etc.)
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 Allows you to perform advanced text searches on string
data using language-aware searching.
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
Built on top of FILESTREAM —
FileTable lets you access files in SQL Server through a Windows file share, with SQL
metadata.
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
create table dbo.myfiles as FILETABLE create filetable here called dbo.myfiles in the
dbo schema
WITH(FileTable_Directory='MyFiles', FileTable_Collate_Filename=database_default);