SQL Progrmming
SQL Progrmming
Programming Microsoft
SQL server Databases
Content
• Components
• Database Engine
• SQL Server Analysis Services, Reporting Services, and
Integration Services.
• Master Data Services and Data Quality Services
• Tools
• SQL Server Management Studio and Data Tools
• Configuration Manager
• Profiler
• Tuning Advisor
• DQS Client
SQL Server Instances
Page: 8 KB
Extent: eight
contiguous 8 KB pages
Considerations for Disk Storage Devices
RAID 0 RAID 1
ACEGIK ABCDEF
BDFHJL ABCDEF
RAID 5 RAID 10
A#EG#K ACEGIK
BC#HI# BDFHJL
#DF#JL ACEGIK
BDFHJL
Determining File Placement and Number of Files
System
Description
Database
master Stores all system-level configuration
• Create databases:
• In SQL Server Management
Studio
• By using the CREATE
DATABASE statement
• Designing Tables
• Data Types
• Working with Schemas
• Creating and Altering Tables
What Is a Table?
• Normalization is a process
• Ensures that database structures are appropriate
• Ensures that poor design characteristics are avoided
• Unicode
• Is a worldwide character-encoding standard
• Simplifies software localization
• Improves multilingual character processing
• Is implemented in SQL Server as double-byte for
Unicode types
• Requires N prefix
• Uses LEN() to return number of characters
• Uses DATALENGTH() to return the number of bytes
Working with Schemas
• What Is a Schema?
• Object Name Resolution
• Creating Schemas
• Demonstration: Working with Schemas
What Is a Schema?
• Creating Tables
• Dropping Tables
• Altering Tables
• Demonstration: Working with Tables
• Temporary Tables
• Demonstration: Working with Temporary Tables
• Computed Columns
• Demonstration: Working with Computed Columns
Creating Tables
• Domain Integrity
• Defines the allowed values in columns
• Entity Integrity
• Primary key uniquely identifies each row within a table
• Referential integrity
• Defines the relationship between tables
Options for Enforcing Data Integrity
• Data Types
• DEFAULT Constraints
• CHECK Constraints
• Demonstration: Data and Domain Integrity
Data Types
• Default constraints
• Provide default values for columns
• Used if INSERT provides no column value
• Must produce data compatible with the data type for
the column
CHECK Constraints
• Check constraints
• Limit the values that are accepted in a column
• Only rejects FALSE outcomes
• NULL evaluates to UNKNOWN and not FALSE
• Can be defined at table level to refer to multiple
columns
Demonstration: Data and Domain Integrity
• Primary keys
• Are used to uniquely identify a row in a table
• Must be unique and not NULL
• May involve multiple columns that form a composite
key
UNIQUE Constraints
• Unique constraints
• Ensure that values in a column are unique
• One row may have a NULL value
• You can have multiple unique columns
IDENTITY Constraints
• IDENTITY property
• Automatically generates column values
• You can specify a seed (starting number) and an
increment
• Default seed and increment are both 1
• SCOPE IDENTITY(), @@IDENTITY return current value
Working with Sequences
• Sequence objects:
• Are user-defined, schema-bound objects
• Are not tied to any particular table
• Can be used to ease migration from other database
engines
Demonstration: Sequences Demonstration
• Table Scan
• SQL Server reads all table pages
• Any query can be satisfied by a table scan
• Will result in the slowest response to a query
• A table without indexes is called a heap
• Index
• SQL Server uses index pages to find the desired rows
• Different types
• Clustered and nonclustered
• Rowstore and columnstore
The Need for Indexes
Index Structures
Selectivity, Density and Index Depth
• Selectivity
• A measure of how many rows are returned compared to the total
number of rows
• High selectivity means a small number of rows when related to the
total number of rows
• Density
• A measure of the lack of uniqueness of data in the table
• High density indicates a large number of duplicates
• Index Depth
• Number of levels within the index
• Common misconception that indexes are deep
Index Fragmentation
• Types of fragmentation:
• Internal – pages are not full
• External – pages are out of logical sequence
• Detecting fragmentation
• SQL Server Management Studio – Index Properties
• System function – sys.dm_db_index_physical_stats
Demonstration: Viewing Index Fragmentation
• Negatives
• Small data types will be more dense
Character Index Data
• Negatives
• Slower to search than a numeric index
• Can become fragmented because data does not tend
to be sequential
Date-Related Index Data
• Negatives
• Small data types will be more dense
GUID Index Data
• Negatives
• Updates and deletes do not perform as well
BIT Index Data
• Negatives
• Frequent changes can impair performance
• Computed columns must be deterministic
Heaps, Clustered, and Nonclustered Indexes
• Heaps
• Operations on a Heap
• Clustered Indexes
• Operations on a Clustered Index
• Primary Keys and Clustering Keys
• Nonclustered Indexes
• Operations on Nonclustered Indexes
• Demonstration: Working with Clustered and
Nonclustered Indexes
Heaps
• INSERT
• Each new row can be placed in the first available page with
sufficient space
• UPDATE
• The row can remain on the same page if it still fits; otherwise, it
can be removed from the current page and placed on the first
available page with sufficient space
• DELETE
• Frees up space on the current page
• Data is not overwritten, space is just flagged as available for reuse
• SELECT
• Entire table needs to be scanned
Clustered Indexes
A clustered index:
• Has pages that are logically ordered
• INSERT
• Each new row must be placed into the correct logical position
• May involve splitting pages of the table
• UPDATE
• The row can remain in the same place if it still fits and if the clustering key
value is still the same
• If the row no longer fits on the page, the page needs to be split
• If the clustering key has changed, the row needs to be removed and
placed in the correct logical position within the table
• DELETE
• Frees up space by flagging the data as unused
• SELECT
• Queries related to the clustering key can seek
• Queries related to the clustering key can scan and avoid sorts
Primary Keys and Clustering Keys
• Primary key
• Must be unique
• Cannot contain NULL values
• Only one per table
• Implemented as a constraint
• Clustering key
• Must be unique
• Specifies the logical ordering of rows
• Only one per table
• Can be automatically created
Nonclustered Indexes
A nonclustered index :
• Can be on a heap or clustered index
• INSERT
• Each nonclustered index that is added to a table will decrease the
performance of inserts
• UPDATE
• The index will need to be kept up to date if the location of the
data changes
• DELETE
• Similar to updates, deleted data needs to be removed from the
index
• SELECT
• Performance improvements for queries that the index covers
Demonstration: Working with Clustered and
Nonclustered Indexes
• Index Strategies
• Managing Indexes
• Execution Plans
• The Database Engine Tuning Advisor
Index Strategies
• Covering Indexes
• Using the INCLUDE Clause
• Heap vs. Clustered Index
• Filtered Index
Covering Indexes
• Graphical plan
• Right-click and Save Execution Plan As
• Saved in XML format with a .sqlplan extension
• .slqplan is associated with SSMS
Live Query Statistics
• Introduction to Views
• Creating and Managing Views
• Performance Considerations for Views
What Is a View?
• User-defined views:
• Views (sometimes called standard views)
• Indexed views
• Partitioned views
• System views:
• System catalog views
• Dynamic management views (DMVs)
• Compatibility views
• Information schema views
Advantages of Views
• Catalog views:
• Views onto internal system metadata
• Organized into categories, such as object views,
schema views, or linked server views
• Compatibility views:
• Provide backward compatibility for SQL Server 2000
system tables
• Do not use for new development work
• Create a View
• Drop a View
• Alter a View
• Ownership Chains and Views
• Sources of Information About Views
• Updateable Views
• Hide View Definitions
• Demonstration: Creating, Altering, and Dropping a
View
Create a View
• Use Transact-SQL:
• sys.views – lists views in database
• OBJECT_DEFINITION() – returns the definition of non-
encrypted views
• sys.sql_expression_dependencies – lists objects,
including other views, that depend on an object
Updateable Views
• Advantages include:
• Once a view has been written, tested, and documented,
it can be used just like a table
Partitioned Views
• EXECUTE statement
• Used to execute stored procedures and other objects
such as dynamic SQL statements stored in a string
• Use two- or three-part naming when executing
stored procedures to avoid SQL Server having to
carry out unnecessary searches
Altering a Stored Procedure
• Types of Functions
• System Functions
Types of Functions
• Types of functions:
• Scalar functions
• Table-valued functions
• Inline and multistatement functions
• System functions
• Functions cannot modify data
System Functions
Scalar functions:
• Return a single data value
• Can return any data type except rowversion,
cursor, and table when implemented in
Transact-SQL
• Can return any data type except for rowversion,
cursor, table, text, ntext, and image when
implemented in managed code
Creating Scalar Functions
• Scalar UDFs:
• Return a single data type from a database
• Usually include parameters
• Use two-part naming
• Stop on error
• CREATE FUNCTION must be the only statement in a
batch
Deterministic and Nondeterministic Functions
• Deterministic functions
• Always return the same result given the same input
(and the same database state)
• Nondeterministic
• May return different results given a specific input
• Built-in functions
• Can be deterministic or nondeterministic
Demonstration: Working with Scalar Functions
• Table-valued functions
• TVFs return a TABLE data type
• Inline TVFs have a function body with only a single
SELECT statement
• Multistatement TVFs construct, populate, and return a
table within the function
• TVFs are queried like a table
• TVFs are often used like parameterized views
Inline Table-Valued Functions
• Constraints:
• Are preferred to triggers
• Avoid data modification overhead on violation
• Triggers:
• Are complex to debug
• Use a rowversion store in tempdb database
• Excessive usage can impact tempdb performance
• Can increase the duration of transactions
• INSTEAD OF Triggers
• Demonstration: Working with INSTEAD OF
Triggers
• How Nested Triggers Work
• Considerations for Recursive Triggers
• UPDATE Function
• Firing Order for Triggers
• Alternatives to Triggers
INSTEAD OF Triggers
• What Is an Assembly?
• Assembly Permission Sets
• SQL Server Data Tools
• Publishing a CLR Assembly
• Demonstration: Creating a User-Defined Function
What Is an Assembly?
• Concurrency Models
• Concurrency Problems
• Transaction Isolation Levels
• Working with Row Versioning Isolation Levels
• Transactions
• Working with Transactions
• Demonstration: Analyzing Concurrency Problems
Concurrency Models
• Pessimistic concurrency:
• Data integrity maintained using locks
• Only one user can access a data item at once
• Writers block readers and other writers; readers block
writers
• Optimistic concurrency:
• Data is checked for changes before update
• Minimal locking
Concurrency Problems
• Dirty read
• Uncommitted data is included in results
• Lost update
• Two concurrent updates; the first update is lost
• Non-repeatable read
• Data changes between two identical SELECT statements
within a transaction
• Phantom read
• Data is read, then deleted before reading completes
• Double read
• Data in a range is read twice because the range key
value changes
Transaction Isolation Levels
• READ UNCOMMITTED
• READ COMMITTED
• REPEATABLE READ
• SERIALIZABLE
• SNAPSHOT
Transactions
• Naming Transactions:
• Label only; no effect on code
• Nesting Transactions:
• Only the state of the outer transaction has any effect
• @@TRANCOUNT track transaction nesting
• Terminating Transactions:
• Resource error
• SET XACT_ABORT
• Connection closure
• RID, KEY
• PAGE
• TABLE
• DATABASE
Lock Escalation