This module covers implementing and working with tables, schemas, views, temporary tables, common table expressions, and partitioned tables in SQL Server. It discusses best practices for designing tables, using schemas to logically group and secure objects, and how views allow querying results without persisting data. Temporary tables and table variables are compared for holding temporary result sets. Common table expressions and partitioned tables are introduced as mechanisms for reusing queries and improving management of large tables respectively.
2. Meet Graeme Malcolm | @graeme_malcolm
• Senior Content Developer, Microsoft
– Responsible for data platform training at Microsoft
Learning Experiences (LeX)
• Background
– Consultant, trainer, and author on data platform and
BI technologies since SQL Server 4.2
3. Meet Christian Bolton | @christianbolton
• Technical Director at Coeo in the UK
– SQL Server Consulting and Managed Services
– Responsible for service delivery and technical readiness
• SQL Server Expert
– First person outside Microsoft to achieve Microsoft Certified Architect
for SQL Server
– Written a number of popular SQL Server books and frequent speaker
at industry events
– 6 years as a SQL Server MVP
– MCM, MCSM and MCT
5. Setting Expectations
• Target Audience
– Developers who need to create database applications with SQL Server
– Anyone pursuing MCSE: Data Platform certification
• Suggested Prerequisites/Supporting Material
– Microsoft Official Curriculum
• 20461C: Querying Microsoft SQL Server
• 20464C: Developing Microsoft SQL Server Databases
– Microsoft Virtual Academy
• Database Fundamentals
• Querying Microsoft SQL Server 2012 Databases Jump Start
• Designing Database Solutions for SQL Server
6. SQL Server Books Online
• Product documentation and guidance
• Published on both TechNet and MSDN
• Downloadable local version also available
7. • Microsoft Virtual Academy
– Free online learning tailored for IT Pros and Developers
– Over 1M registered users
– Up-to-date, relevant training on variety of Microsoft products
Join the MVA Community!
8. 01 | Implementing Tables & Views
Christian Bolton | Technical Director, Coeo
Graeme Malcolm | Microsoft
10. Designing Tables
• Avoid table names and column names that contain
spaces, keywords and symbols
• Plan data types for each column
• Plan whether to allow NULLs
• Plan primary key and foreign key constraints
• Plan indexes to optimize performance
12. Working with Schemas
• Naming boundary
– Logically group database objects
– Use the schema name when referencing database objects to aid name
resolution
• Security boundary
– Simplify security configuration
– Database objects inherit permissions set at the schema level
[Server.][Database.]Schema.Object
GRANT EXECUTE ON SCHEMA::Sales
13. Default Schema and Name Resolution
1. Try user’s default
schema (if defined)
2. If object is not in default
schema (or no default
schema defined), try
dbo schema
3. If object is not in dbo
schema, return object
not found error
SELECT * FROM Product
User 1
(Default Schema: Sales)
User 3
(No Default Schema)
Sales.Product dbo.Product
User 2
(Default Schema: Ops)
Sales Ops dbo
15. What Are Views?
• A view is a database object referenced in the same way as a table
• A view is essentially a named SELECT query
CREATE VIEW HumanResources.EmployeeList
(EmployeeID, FamilyName, GivenName)
AS
SELECT EmployeeID, LastName, FirstName
FROM HumanResources.Employee;
16. Introduction to Views
• A view does not persist the data unless you have an indexed view
• WITH SCHEMABINDING prevents schema changes to the
underlying table
• Adding a UNIQUE CLUSTERED INDEX to a view makes it an
Indexed View
– The data is persisted to disk in its own right, improving performance
• Enterprise Edition of SQL Server evaluates indexed views
• Inserts and updates to views can only affect one underlying table
18. Temporary Tables
• Temporary tables are used to hold temporary result sets within
a user’s session
• Created in tempdb and deleted automatically
• Created with a # prefix
• Global temporary tables are created with ## prefix
CREATE TABLE #tmpProducts
(ProductID INTEGER,
ProductName varchar(50));
19. Table Variables
• Introduced because temporary tables can cause recompilations
• Used similarly to temporary tables but scoped to the batch
• Has no statistics so changes doesn’t cause recompilations
– Always estimates 1 row
• Use only on very small datasets
DECLARE @tmpProducts table
(ProductID INTEGER,
ProductName varchar(50));
21. Common Table Expressions
• A mechanism for
defining a subquery
that may be used
elsewhere in a query
• Can be referenced
multiple times in the
same query with one
definition
• Supports recursion
WITH CTE_year AS
(
SELECT YEAR(orderdate) AS orderyear,
custid
FROM Sales.Orders
)
SELECT orderyear,
COUNT(DISTINCT custid) AS cust_count
FROM CTE_year
GROUP BY orderyear;
23. Partitioned Tables
• Table partitioning makes managing large tables more efficient
• Each partition can be stored on a specific filegroup
• Indexes are automatically aligned
Date Order Total
20000101 123 999.99
20000105 125 287.99
Date Order Total
20010101 258 199.99
20010105 259 257.99
Date Order Total
20020101 368 199.99
20020105 369 257.99
Date Order Total
20030101 547 129.99
Sales.Order
Filegroup 2000 Filegroup 2001 Filegroup 2002 Filegroup 2003
24. Creating a Partitioned Table
• A partition function defines:
– Boundary values for partitions
– How to handle values that are the
same as boundary values (right or left)
• A partition scheme defines:
– Mappings to filegroups for the
partitions created by a partition
function
– The next used filegroup
• A table is created on a partition
scheme using a specified
column
CREATE PARTITION FUNCTION PFYears (datetime)
AS RANGE RIGHT
FOR VALUES (20000101, 20010101, 20020101);
--creates 4 partitions:
-- <-2000, 2000-2001, 2001-2002, 2002->
CREATE PARTITION SCHEME PSYears
AS PARTITION PFYears
TO (FG0000, FG2000, FG2001, FG2002, FG2003);
-- FG2003 is marked as ‘next used’
CREATE TABLE Sales.Order
(OrderDate datetime,
OrderNo int,
Customer varchar(50),
OrderAmount money)
ON PSYears(OrderYear);
25. Managing Partitioned Tables
• Split Partitions
– Add a new boundary to split a
single partition into two partitions
• Merge Partitions
– Remove a boundary to merge two
partitions into a single partition
• Switch Partitions
– Switch a partition between
partitioned tables or between a
partitioned table and a non-
partitioned table
-- Create a new partition for 2003 orders
-- (created on next used filegroup)
ALTER PARTITION FUNCTION PFYears()
SPLIT RANGE (20030101);
-- Merge 2000 and pre-2000 orders
ALTER PARTITION FUNCTION PFYears()
MERGE RANGE (20000101);
-- Switch partition containing old orders
-- to a staging table for archiving
ALTER TABLE Sales.Order
SWITCH PARTITION $PARTITION.PFYears(20000101)
TO archive_staging_table;