Вы находитесь на странице: 1из 114

Database Fundamentals

Brian Alderman | MCT, CEO / Founder of MicroTechPoint


Pete Harris | Microsoft Senior Content Publisher
Course Modules

Database Fundamentals
01 | Introducing core database concepts (50 minutes)
Define databases, example of relational database tables, and introduce common database terminology

02 | Relational Concepts (50 minutes)


Normalization, referential integrity, and constraints

03 | Creating databases and database objects (50 minutes)


Data types, database objects, DDL statements, and creating scripts

04 | Using DML statements (50 minutes)


DML statements, using the SELECT statement; using INSERT, UPDATE, and DELETE to manage data; indexes and triggers

05 | SQL Server Administration Fundamentals (50 minutes)


SQL Server security; securing database and objects; performing database backups and database restores
Click to edit Master
subtitle style

01 | Introducing Core
Database Concepts

Brian Alderman | MCT, CEO / Founder of MicroTechPoint


Pete Harris | Microsoft Senior Content Publisher
Module Overview

Introduce relational databases


Introduce common database components and terms
Discuss the three types of commands used to
manage SQL Server
Database Introduction
Database

A database (db) is an organized collection of data,


typically stored in electronic format
It allows you to input, manage, organize, and
retrieve data quickly
Traditional databases are organized by records
(rows), fields (columns) stored in tables which are
stored in the database files
Excel ‘tables’
The idea of a table shouldn’t be new to you if you have used Excel, as that
has rows and columns of information and the structure of a SQL Server
table is similar to that of an Excel spreadsheet
Tables
A database table is a collection of rows and columns that is used to
organize information about a single topic. Each row within a table
corresponds to a single record and contains several attributes that describe
the row.
These tables are stored in databases
EmployeeID LastName FirstName Department

100 Smith Bob IT

101 Jones Susan Marketing

102 Adams John Finance


Relational databases

A relational database a collection of tables of data all


of which are formally described and organized
according to the relational model. Each table must
identify a column or group of columns, called the
PRIMARY KEY, to uniquely identify each row
Sample relational structure
Common Terms
Database Management System (DBMS)
Database Management System (DBMS) is used by the users to access the
data stored in database files. A DBMS is also used to perform
administrative tasks on the databases and objects contained within the
database.

DBMS is a collection of applications that allows users and other programs


to capture and analyze data by providing additional functionality like
reporting services to help you create, deploy, and manage reports for your
organization.

A RDBMS is a software system designed to allow the definition, creation,


querying, and updating of data stored in relational databases.

A few examples of RDBMS include; Microsoft SQL Server, Microsoft Access,


and MySQL
Database servers
Databases are stored on database servers which are dedicated physical or
virtual servers that host the database files and provide high-level
performance for users who are accessing the data.

Database servers contain the DBMS used to manage the data and
administer the SQL Server environment.

A database server can have one default instance and several named
instances of SQL Server. A SQL Server instance is a copy of the sqlservr.exe
program that runs as a Windows operating system service.

Often multiple database servers are deployed to provide high availability


and improve performance
SQL Server Management Studio (SSMS)
A graphical user interface (GUI) used to browse, select, and manage the
SQL Server instance and any of the objects within that SQL Server instance.
Demo
Exploring SSMS
Summary

A database (db) is an organized collection of


data, typically stored in electronic format.

Microsoft SQL Server and MySQL are examples


of relational databases

DBMS is application used to perform


administrative tasks on databases and used to
interact with data stored in databases.
Summary

Database server hosts DBMS system and one or


more instances of SQL Server

SQL Server Management Studio (SSMS) is the


GUI used to manage SQL Server, its databases,
and the content contained within the databases
Click to edit Master
subtitle style

02 | Relational Concepts

Brian Alderman | MCT, CEO / Founder of MicroTechPoint


Pete Harris | Microsoft Senior Content Publisher
Module Overview

Normalization
Referential integrity
Constraints
Normalization
Normalizing a database

Normalization the process of organizing data in


a database that includes creating tables and
establishing relationships between the tables
Process is used to help eliminate redundant
data
Five normalization forms (NFs)
1NF: Eliminate Repeating Groups
2NF: Eliminate Redundant Data
3NF: Eliminate Columns Not Dependent on
Key
4NF: Isolate Independent Multiple
Relationships
5NF: Isolate Semantically Related Multiple
Relationships
First
The normal form (1NF)
first normal form means the data is in an
entity format, which means the following
conditions have been met:
Eliminate repeating groups in individual
tables
Create separate table for each set of related
data
Identify each set of related data with primary
key

Do not use multiple fields in a single table to


store similar data
Second normal form
The second (2NF) form ensures each
normal
attribute describes the entity
Create separate tables for sets of values that
apply to multiple records
Relate these tables with a foreign key

Records should not depend on anything other


than a table’s primary key, including a
compound key if necessary.
The third normal form checks for transitive
dependencies.
Eliminate fields that do not depend on the
key

Values that are not part of the record’s key do


not belong in the table
In general if the contents of a group of fields
apply to more than a single record, put those
fields in a separate table
The fourth normal form is also called the Boyce
Codd Normal Form (BCNF) and fifth normal
form exists, but are rarely considered in
practical design

Disregarding these two additional normalization


rules may result in a less than perfect database
design but shouldn’t affect functionality
Example of normalization
Un-normalized table
Student# Advisor Adv-Room Class1 Class2 Class3

1022 Jones 412 101-07 143-01 159-02

4123 Smith 216 201-01 211-02 214-01

First Normal Form: No Repeating Groups


Student# Advisor Adv-Room Class#

1022 Jones 412 101-07

1022 Jones 412 143-01

1022 Jones 412 159-02

4123 Smith 216 201-01

4123 Smith 216 211-02

4123 Smith 216 214-01


Example of normalization
Second Normal Form: eliminate redundant data
Students:
Student# Advisor Adv-Room
1022 Jones 412
4123 Smith 216

Registration:
Student# Class#

1022 101-07

1022 143-01

1022 159-02

4123 201-01

4123 211-02

4123 214-01
Example of normalization

Third Normal Form: eliminate data not dependent


on the key
Students: Faculty: Registration:

Student# Advisor Name Room Dept Student# Class#

1022 Jones Jones 412 42 1022 101-07

4123 Smith Smith 216 42 1022 143-01

1022 159-02

4123 201-01

4123 211-02

4123 214-01
Referential Integrity
Referential integrity
Referential Integrity (RI) is a database concept used to ensure that the
relationships between your database tables remains synchronized during
data modifications.

RI can be used to ensure the data is clean, may be helpful in optimizing


your database environment and can assist in early detection of errors.

A combination of PRIMARY KEY and FOREIGN KEY constraints can be


used to help enforce referential integrity of your database. In addition to a
foreign key referencing a primary key constraint, a foreign key can also
reference a UNIQUE constraint to help maintain referential integrity.

Triggers can also be used to enforce referential integrity, however being


triggers require code they don’t execute as quickly as table properties such
as a primary key constraint.
Methods for enforcing referential integrity
There are several methods available in SQL Server
to help maintain database integrity:
Primary key constraint
Foreign key constraint
Unique constraint
Indexes
Triggers

Any of these methods can be created as a


composite key which is an index or constraint
created using more than one column. It may be
necessary to use more than one column to create a
unique value for each row in a table.
Constraints
PRIMARY KEY constraint

An important concept of designing a database


table is the use of a PRIMARY KEY — an
attribute or set of attributes used to uniquely
identify each row
A table can only have one primary key which is
created using a primary key constraint and
enforced by creating a unique index on the
primary key columns
A column that participates in the primary key
constraint cannot accept null values
FOREIGN KEY constraint

A FOREIGN KEY is a column or combination of


columns that are used to establish a link between
data in two tables. The columns used to create the
primary key in one table are also used to create the
foreign key constraint and can be used to
reference data in the same table or in another
table

A foreign key does not have to reference a primary


key, it can be defined to reference a unique
constraint in either the same table or in another
table
A column that participates in the foreign key
constraint can accept null values, but if it contains
a null value, the verification process is skipped.
Relational structure with keys

Foreign Key
Primary Key
Summary

Normalization is the process of organizing data


in a database that includes establishing
relationships between the tables
First normal form – no repeating groups
Second normal form – eliminate redundant data
Third normal form – eliminate data not dependent
on the key
Disregarding the fourth and fifth
normalization rules may not result in a
perfect database design but shouldn’t
affect functionality
Summary

Referential Integrity is used to ensure the data


contained in the database remains consistent.

Tools that can be used to help with referential


integrity include
Primary key constraint
Foreign key constraint
Unique constraint
Unique Indexes
Triggers
Summary

Primary key constraint— an attribute or set of


attributes used to uniquely identify each row
Foreign key constraint – a column or
combination of columns used to establish a link
between data in two tables
Unique constraint - allows you to enforce
uniqueness in columns other than the primary
key
Unique Index - ensures the index key contains
no duplicate values and that every row in the
table or view is unique in someway
Triggers - complex T-SQL statements used to
provide data integrity when table data modified
Click to edit Master
subtitle style

03 | Creating Databases and Database


Objects

Brian Alderman | MCT, CEO / Founder of MicroTechPoint


Pete Harris | Microsoft Senior Content Publisher
Module Overview

Data types
Database objects
DDL statements
Data types
Data types

A data type is an attribute that specifies the type of data that an object
can hold as well as the number of bytes of information that can be
stored in the object

If you have similar data types to choose from but they only differ in
byte size, use the data type that has a larger range of values and/or has
increased precision

Exact numeric data types (int, tinyint) are the most common SQL Server
data types used to store numeric information.

Approximate Numerics include precision (p) which is the total number


of decimal digits that could be stored, both to the left and right of the
decimal point.
Data types

Unicode data types provide storage of international characters, such as


Japanese and Chinese, to allow worldwide businesses to use big vendor
database products to store their data.

Unicode data types takes more bytes to store the data in the database

If you have similar data types to choose from but they only differ in
byte size, use the data type that has a larger range of values and/or has
increased precision

Exact numeric data types (int, tinyint) are the most common SQL Server
data types used to store numeric information.

Approximate Numerics include precision (p) which is the total number


of decimal digits that could be stored, both to the left and right of the
decimal point.
Built-in data type categories

SQL Server 2012’s built-in data types are organized into the
following categories:

Exact numerics – (bigint, bit, decimal, int, money, numeric, smallint)


Approximate numerics (float, real)
Date and time (date, datetime2, datetime, datetimeoffset, time)
Character strings (char, varchar, text)
Unicode character strings (nchar, ntext, nvarchar)
Binary strings (binary, varbinary, image)
Other data types (cursor, timestamp, uniqueidentifier, table)
Large valued data types (varchar(max), nvarchar(max))
Large object data types (text, ntext, image, xml)
Data types

Money - used where you’ll store money or


currency values
Int - used to store whole numbers and when
performing mathematical computations
Float - commonly used in the scientific
community and is considered an approximate-
number data type
Datetime - used to store date and time values
in one of many different formats
Data types

Char – fixed length non-unicode string data


type where n defines the string length
Varchar – variable length non-unicode
string data type that indicates the actual
storage size of the data
Bit (Boolean) – integer that can have a null,
0 (False), or 1 (True) value
Datetimeoffset – a date combined with
time of day that has time zone awareness
Data types storage size

Data Type Use/Description Storage Size


Money Monetary or currency values -922,337,203,685,477.5808 to 8 bytes
922,337,203,685,477.5807
Int Integer data from -2^31 (-2,147,483,648) to 2^31-1 4 bytes
(2,147,483,647)
Float Approximate number - 1.79E+308 to -2.23E-308, 0 and 2.23E- Depends on the
308 to 1.79E+308 value of n
Datetime Date Range January 1, 1753, through December 31, 9999 8 bytes
Time Range 00:00:00 through 23:59:59.997
Char Fixed-length, non-Unicode string data. Can be a value from 1 n bytes
through 8,000
Varchar Variable-length non-Unicode string. Can be a value from 1 Actual length +
through 8,000 2 bytes
Bit Integer with a value of 0 or 1. 1 byte for every
8 bit columns
Datetimeoffset Date range January 1,1 A.D. through December 31, 9999 A.D. 10 Bytes
Time range 00:00:00 through 23:59:59.9999999
Time zone offset range -14:00 through +14:00
Implicit and explicit conversions

Implicit data type conversions occurs when the SQL Server


expression evaluator automatically converts data from one data
type to another to complete an operation like a comparison of two
values

Explicit data type conversions require the use of the CONVERT or


CAST function to convert data from one data type to another
before an operation like a comparison can be completed.

To convert a numeric value into a character string


CAST ( $157.27 AS VARCHAR(10) )

Not all data types conversions are supported


nchar cannot be converted to image

Use CAST instead of CONVERT to adhere to ISO


Use CONVERT instead of CAST to take advantage of the style functionality
Database objects
Tables
A table is a collection of rows and columns that is used to organize
information about a single topic. Each row within a table corresponds to a
single record and contains several attributes that describe the row.

EmployeeID LastName FirstName Department

100 Smith Bob IT

101 Jones Susan Marketing

102 Adams John Finance


Views
A view is simply a virtual table consisting of different columns from one or
more tables.

Unlike a table, a view is stored in the database as a query object; therefore,


a view is an object that obtains its data from one or more underlying
tables.
Stored procedures
A stored procedure is a group of Transact-SQL statements that have been
compiled and saved so it can be run several times.

Parameters can be passed to and returned from a stored procedure so


they can be reused with different values.

IF (@QuantityOrdered < (SELECT QuantityOnHand


FROM Inventory
WHERE PartID = @PartOrdered) )
BEGIN
-- SQL statements to update tables and process order.
END
ELSE
BEGIN
-- SELECT statement to retrieve the IDs of alternate items
-- to suggest as replacements to the customer.
END
User-Defined functions
User-defined functions (udf) are routines that takes zero or more
parameters, completes an operation, and return the result of the operation
as a value.

There are three types of functions


Scalar – returns a single data value
Table-valued – returns a table data type
System – Provided by SQL Server, cannot be modified
Primary differences between stored procedures and user-defined
functions

Stored Procedures
Called independently using EXEC statement
Cannot JOIN stored procedures
Can be used to modify SQL Server configuration
Can use nondeterministic functions such as GETDATE()

User-defined Functions
Called from within another SQL statement
Can JOIN UDF’s
Cannot be used to modify SQL Server configuration
Always stops execution of T-SQL code if error occurs
Naming conventions for your objects

PascalCase - The first letter of the identifier and the first


letter of each subsequent concatenated word is
capitalized
EmployeeTable

camelCase - The first letter of the identifier is lowercase


and the first letter of each subsequent concatenated
word is capitalized
employeeTable

Tip: Pick a naming convention and use it consistently


throughout your database environment
DDL Statements
Common DDL statements

CREATE – define new entities


ALTER – modify existing entities
DROP – remove existing entities
CREATE statement

Used to create new entities in SQL Server including


some of the most common entities
Database Procedure
Table Trigger
Default View
Index User
Login Role

CREATE DATABASE Sales ON ( NAME = Sales_dat, FILENAME =


'C:\Program Files\Microsoft SQL
Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\sales.mdf', SIZE = 10,
MAXSIZE = 50, FILEGROWTH = 5 )
LOG ON ( NAME = Sales_log, FILENAME = 'C:\Program Files\Microsoft SQL
Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\salelog.ldf', SIZE = 5MB,
MAXSIZE = 25MB, FILEGROWTH = 5MB ) ;
Create new table
USE SALES
GO
 
--Create new table called Products
CREATE TABLE dbo.Products1
(
ProductID int NULL,
ProductName varchar(20) NULL,
UnitPrice money NULL,
ProductDescription varchar(50) NULL
);
ALTER statement

Used to modify existing entities in SQL Server including


Database Trigger
Table View
Index User
Login Role
Procedure Schema

ALTER DATABASE Sales


Modify Name = SalesForecast ;
DROP statement

Used to delete existing entities in SQL Server including


Database Trigger
Table View
Index User
Login Role
Procedure Schema

DROP DATABASE SalesForecast


Summary

A data type is an attribute that specifies the


type of data that an object can hold
The built-in data types fall into the following
categories:
Exact numerics
Approximate numerics
Date and time
Character strings
Unicode character strings
Binary strings
Other data types
Large valued data types
Large object data types
Summary

A database can be created using SSMS or using


the T-SQL CREATE DATABASE statement

Database objects such as tables, views, stored


procedures, and user-defined functions can be
created using SSMS or using a DDL CREATE
statement

Database objects should be consistently created


using either the PascalCase or camelCase
naming convention
Summary

The purpose of a table is to provide structure


for storing data within a relational database
A view is a virtual table consisting of columns
from one or more tables and is stored in the
database as a query object
A stored procedure is a group of Transact-SQL
statements that have been compiled and saved
so they can be run several times
Scripts can be created from existing objects
Meet Brian Alderman |
@brianalderman
Chief Executive Office, Founder MicroTechPoint
Industry-recognized consultant
Noted author and conference speaker
Brian’s expertise and designs range across Microsoft
operating systems
More than 25 years of industry experience
Brian has been focused on helping IT Pros and Database Administrators (DBAs) better
understand core Microsoft technologies for over 25 years.
A frequent presenter at SharePoint Conferences around the world, he has authored or
contributed to several SharePoint, SQL Server, and other technical books, and is a MCSE, MCT,
and MCITP: SharePoint and SQL Server Administrator.
Brian has a BS and MS in Computer Information Systems where he graduated summa cum laude
from Regis University of Colorado Springs and lives in Scottsdale, AZ where he enjoys playing
golf year round and traveling around the world.

LinkedIn Blog
/brianalderman http://brianalderman.wordpress.com
Meet Pete Harris | @SQLPete

Content Development Manager in Microsoft’s


Learning Experiences team
Focuses on SQL Server and Web training 

With Microsoft since 1995 


Part of the first team of developer training folks in the post-Microsoft
University era
Has built a variety of content and spoken to customers all over the world
Click to edit Master
subtitle style

04 | Using DML Statements

Brian Alderman | MCT, CEO / Founder of MicroTechPoint


Pete Harris | Microsoft Senior Content Publisher
Module Overview

Introducing DML statements


Using the SELECT statement
Modifying data using DML statements
Indexes and triggers
DML Statements
Common DML statements

SELECT – retrieve data


INSERT – add data
UPDATE – modify data
DELETE – remove data
BULK INSERT – Import a data file
The SELECT statement
Using the basic SELECT statement

The SELECT statement is used to retrieve rows and


columns from a table
SELECT * FROM tablename

The SELECT statement requires the name of the


table and either the * (retrieves all columns) or
specific column names

To limit the number of rows returned you can


include the WHERE clause in the SELECT statement
Sample SELECT statement
SELECT BusinessEntityID, JobTitle, Gender
FROM HumanResources.Employee
WHERE BusinessEntityID <= 50

Returns the following results:


BusinessEntityID Title Gender
------------------ -------------- ---------
1 Chief Executive Officer M
2 Vice President of Engineering F
3 Engineering Manager M
4 Senior Tool Designer M
 
Multiple WHERE clauses
You can combine several WHERE clauses in one query statement to create
more specific queries.
SELECT BusinessEntityID, Jobtitle, VacationHours
FROM HumanResources.Employee
WHERE JobTitle = ‘Design Engineer’ AND gender =
‘F’ AND HireDate >= ‘2000-JAN-01’

SELECT BusinessEntityID, Jobtitle, VacationHours


FROM HumanResources.Employee
WHERE VacationHours > 80 OR BusinessEntityID
<= 50
Using the BETWEEN clause

Retrieving rows within a date range using the BETWEEN clause

SELECT BusinessEntityID, Jobtitle, VacationHours


FROM HumanResources.Employee
WHERE VacationHours BETWEEN 75 AND 100
Sorting the result set using ORDER By

Sorting the result set by using the ORDER BY to specify what field
to sort by.
SELECT BusinessEntityID, Jobtitle, VacationHours
FROM HumanResources.Employee
WHERE VacationHours BETWEEN 75 AND 100
ORDER BY VacationHours

You can sort in descending order by using the DESC


clause.
SELECT BusinessEntityID, Jobtitle, VacationHours
FROM HumanResources.Employee
WHERE VacationHours BETWEEN 75 AND 100
ORDER BY VacationHours DESC
Using the NOT clause

Write a query to return data that specifies what you don’t want returned

SELECT BusinessEntityID, Jobtitle, Gender


FROM HumanResources.Employee
WHERE NOT Gender = ‘M’
UNION clause

The UNION clause allows you to combine the rows returned from multiple
SELECT statements into a single result set

SELECT BusinessEntityID, Jobtitle, HireDate


FROM HumanResources.Employee
WHERE JobTitle = 'Design Engineer'
UNION
SELECT BusinessEntityID, Jobtitle, HireDate
FROM HumanResources.Employee
WHERE HireDate BETWEEN '2005-01-01' AND '2005-12-
31'
EXCEPT and INTERSECT clauses
The EXCEPT clause returns distinct values from the left query that are not
found on the right query

SELECT ProductID
FROM Production.Product
EXCEPT
SELECT ProductID
FROM Production.WorkOrder ;

The INTERSECT clause returns any distinct values returned by both the
query on the left and right sides of intersect operand

SELECT ProductID
FROM Production.Product
INTERSECT
SELECT ProductID
FROM Production.WorkOrder ;
JOIN clause

The JOIN clause allows you to combine related data


from multiple tables into one result set

INNER JOINS uses a comparison operator to match


rows from two tables based on values in a common
column that exists in both tables

OUTER JOINS (left, right, or full) includes rows from


one or both tables even if they don’t have matching
values

CROSS JOINS return all rows from the left table with
all rows from the right table. WHERE conditions
should always be included.
Aggregate sample

SQL Server provides aggregate functions to


assist with the summarization of large volumes
of data
SELECT COUNT (DISTINCT SalesOrderID) AS UniqueOrders,
AVG(UnitPrice) AS Avg_UnitPrice,
MIN(OrderQty)AS Min_OrderQty,
MAX(LineTotal) AS Max_LineTotal
FROM Sales.SalesOrderDetail;

Demo query generator


Inserting data
You can add a new row to a table using the INSERT statement

INSERT INTO Production.UnitMeasure


VALUES (N'FT', N'Feet', '20080414')

You can add multiple rows to a table using the following INSERT statement

INSERT INTO Production.UnitMeasure


VALUES (N'FT2', N'Square Feet ', '20080923'),
(N'Y', N'Yards', '20080923'),
(N'Y3', N'Cubic Yards', '20080923'

BULK INSERT can be used to import a data file into a table with a user-
specified format.
Update statement
The UPDATE statement is used to modify the data that is already stored in
a table

UPDATE Sales.SalesPerson
SET Bonus = 6000, CommissionPct = .10, SalesQuota = NULL
WHERE sales.SalesPerson.BusinessEntityID = 289
DELETE statement

The DELETE statement is used to delete rows from a


table

DELETE FROM Production.UnitMeasure


WHERE Production.UnitMeasure.Name = ‘Feet’

A DELETE statement without a WHERE clause will cause


all rows to be deleted
DELETE FROM Sales.SalesPersonQuotaHistory;
Indexes and triggers
SQL Server indexes

Indexes allow you to speed up the retrieval of


data stored within a table or view

The SQL Server query optimizer evaluates each


method for retrieving the data and selects the
most efficient method which may be a table
scan or using one or more indexes if they exist.

The most commonly used indexes include


clustered
nonclustered
unique
Creating a DML trigger

Triggers are used to enforce business rules


when data is modified
This DML trigger displays a message to the user
when they try to add or change data in the
customer table
CREATE TRIGGER Reminder1
ON Sales.Customer
AFTER INSERT, UPDATE
AS RAISERROR ('Notify Customer Relations', 16, 10);
GO
Summary

The SELECT statement is use to retrieve data


from one or more tables stored in a database

The SELECT command must indicate what


columns and what table you want to retrieve
data from when executing the query.

Optionally the SELECT statement can include


the WHERE clause to define the conditions used
to determine what rows will be returned
Summary

Other arguments that can be used to control


what data is returned include;
BETWEEN
NOT
UNION
EXCEPT
INTERSECT
JOIN (INNER, OUTER, CROSS)
Summary

DML commands that can be used to manage


table and view data include
INSERT
BULK INSERT
UPDATE
DELETE
Indexes are used to speed up the retrieval of
data from tables and views
Triggers are used to enforce business rules
when data is modified
Click to edit Master
subtitle style

05 | SQL Server Administration


Fundamentals

Brian Alderman | MCT, CEO / Founder of MicroTechPoint


Pete Harris | Microsoft Senior Content Publisher
Module Overview

Understanding SQL Server Security


Securing SQL Server databases and objects
Using SSMS to backup SQL Server databases
Using SSMS to restore SQL Server databases
SQL Server security
Database security

Securing your database content is a critical part of


a DBA’s job. The design, testing, and
implementation of security is necessary to ensure
that confidentiality is not compromised

Securables are the server, database, and objects a


database contains
Principals are the individuals, groups, and
processes granted access to SQL Server
Permissions are granted to a principal for every
SQL Server securable
Logins and accounts

Three tiered approach to accessing content


1. SQL Server access - a login is a security
principal that can be authenticated by a secure
system to provide a user access to SQL Server
2. Database access - a database user is
mapped to a SQL login and provides a user or
group access to a database
3. Object access – permissions are applied at
the object level to provide the appropriate
access to the objects within the database
Server-level security

Authentication is the act of verifying a user or


system identity and allowing them to login using:
Windows Authentication
Windows user account
Windows security group
Mixed-Mode (Windows and SQL logins)
SQL Server-specific login
sa account (built-in SQL administrator)

Logins can be populated into the fixed server


roles or in user-defined server roles
Fixed server roles

SQL Server includes several fixed server roles:


Sysadmin – perform any activity on the server
Dbcreator – create, alter, drop, restore databases
Securityadmin –manage logins and their properties

You can also create user-defined server roles


that have specific permissions applied to the
roles
Securing SQL Server
databases and objects
Database-level security

A database user is a database level security


principal that must be mapped to a login at the
server level in order for the user to connect to
the database
A login can be mapped to different databases
as different users but can only be mapped as
one user in each database
Database users can be populated into the fixed
database roles or in a user-defined database
role
All users are automatically members of the
public database role and cannot be removed
Fixed database roles

SQL Server includes several fixed database roles

db_owner – perform all configuration activities


db_datareader – read all data from all user tables
db_datawriter – add, delete, or change data

You can also create user-defined database roles


that have specific permissions applied to the roles
Demo
Creating and assigning permissions
to a login
Guest logon accounts

The guest user account is included in every


database and is used by any user who accesses
the database but does not have a user account
within the database
The guest user account cannot be dropped but
it can be disabled by revoking it’s connect
permission
REVOKE connect FROM guest
Managing object permissions

Permissions to an object can be managed by


using the following commands
Grant - provides a level of access to the
object Deny - overrides any grant permission
Revoke - removes the previously assigned
permission, regardless of whether it was a
deny or grant permission
Object permissions

Object permissions are the permissions that


allow a user to perform actions on database
objects (such as tables, stored procedures, and
views):
SELECT
INSERT
UPDATE
DELETE
DRI (Data Referential Integrity)
EXECUTE (stored procedures)
Databases backups
Database backups

A database backup is performed so you


can restore data if it is corrupted or lost
A user may accidentally delete a table
requiring the DBA to restore the table to
the point it was when the last backup was
performed
Database backups can also be used to
restore content on another SQL Server so
you generate reports from that server
Common types of backups

Full backup - contains all the data in a specific


database, or set of filegroups or files, and also
the portion of the transaction log necessary to
recover all the data
Differential backup - contains all the data that
has changed since the differential base
Incremental backup (transaction log) -
contains only the data that has changed since
the last full or incremental backup
Other backup types
Databases restores
Database restore options

Restore scenarios include the following:


Complete database restore – restore full database backup
Differential restore – restore all changes contained in the
differential backup
Transaction log restore – restores a transaction log
backup
Summary

Security terminology

Securables are the server, database, and objects a


database contains

Principals are the individuals, groups, and processes


granted access to SQL Server

Permissions are granted to a principal for every SQL


Server securable
Summary

Three tiered approach to accessing content


1. Login – provides access to SQL Server access
2. Database user – provides access to a database
access
3. Permissions provide access to database objects
Grant - provides access to the object
Deny - overrides any grant permission
Revoke - removes the previously assigned permission

Logins can be populated into fixed server roles or in user-


defined server roles
Database users can be populated into fixed database roles
or in user-defined database roles
Summary

Full backups contain all the data in a specific


database or set of filegroups or files
Differential backups only backs-up data since
the last full backup
Incremental backups only backs-up up data
since the last full or incremental backup
Summary

Complete database restore – restores full


database backup
Differential restore – restores all changes
contained in the differential backup
Transaction log restore – restores a transaction
log backup

Вам также может понравиться