You are on page 1of 28

Module 3

Designing and
Implementing Tables

Module Overview
Designing Tables
Working with Schemas
Creating and Altering Tables

Lesson 1: Designing Tables


What is a Table?
Normalizing Data
Common Normalization Forms
Demonstration 1A: Normalization
Primary Keys
Foreign Keys
Working with System Tables

What is a Table?
Relational databases store data in tables (relation)

Defined by a collection of columns (identified by name)

Contain zero or more rows

Tables typically represent a type of object or entity

Employees, PurchaseOrders, Customers, SalesOrders

Consistent naming convention for tables is important

Tables are a security boundary

Each row usually represents a single object or entity

One customer, one purchase order, one employee

Rows of Tables have no order

Normalizing Data
Normalization is a process

Ensures that database structures are appropriate

Ensures that poor design characteristics are avoided

Edgar F. Codd invented the relational model

Introduced the concept of normalization

Referred the degrees of normalization as "forms"

Database designs should start normalized

Denormalization might be applied later to improve


performance or to make analysis of data easier

Common Normalization Forms


First Form

Eliminate repeating groups in individual tables

Create a separate table for each set of related data

Identify each set of related data with a primary key

Second Form

Create separate tables for sets of values that apply to multiple


records

Relate these tables with a foreign key

Third Form

Eliminate fields that do not depend on the key

Demonstration 1A: Normalization


In this demonstration, you will see the common
normalization errors

Primary Keys
Candidate key can be used to uniquely identify a row

Must be unique and cannot be unknown

Can involve multiple columns

Should not change

Primary key is one candidate key

Most tables will only have a single candidate key

Substantial ongoing debate surrounding natural vs.

surrogate keys

Natural key formed from data related to the entity

Surrogate key usually codes or numbers

Foreign Keys
Foreign keys are references between tables

Foreign key in one table holds a candidate key for another table

Usually the primary key for consistency

Self-references are permitted such as an employee table that


references a manager who is also an employee

Rows cannot be inserted in a referencing table that do not exist

in the referenced table

CustomerOrders cannot be entered for non-existent customers

A referenced key cannot be deleted or updated without cascading


options

Multiple foreign keys might exist in a table

These can even reference the same table

Working with System Tables


SQL Server provides a set of system tables

Should not be directly modified or queried

In SQL Server 2005, most system tables were replaced by

a set of permission-based system views

Some system tables in the msdb database are still useful

dbo.backupset

dbo.restorehistory

dbo.sysjobhistory

Lesson 2: Working with Schemas


What is a Schema?
Object Name Resolution
Creating Schemas
Demonstration 2A: Schemas

What is a Schema?
Schemas are containers for objects such as

Tables

Stored Procedures

Functions

Types

Views

Schemas are security boundaries

Permissions can be granted at the schema level to apply to all


objects within a schema

Simplifies security configuration

Object Name Resolution


If the schema name is omitted, rules apply to how the

name will be resolved

Users can have a default schema assigned

Users with no defined default schema will have dbo as their


default schema

First search is in the user's default schema

If not found, the dbo schema is searched also

Whenever referencing an object in a statement, users

should specify both the schema and the object name

SELECT ProductID FROM Production.Product

Creating Schemas
Schemas are created using the CREATE SCHEMA command
Schemas have owners

Objects contained within schemas also have owners

Schema objects and permissions can be created in the same

statement as the creation of the schema


CREATE
CREATE SCHEMA
SCHEMA Reporting
Reporting
AUTHORIZATION
AUTHORIZATION Terry;
Terry;

CREATE
CREATE SCHEMA
SCHEMA KnowledgeBase
KnowledgeBase
AUTHORIZATION
AUTHORIZATION Paul
Paul
CREATE
CREATE TABLE
TABLE Article
Article (ArticleID
(ArticleID int IDENTITY(1,1)
IDENTITY(1,1)
PRIMARY
PRIMARY KEY,
KEY,
ArticleContents
ArticleContents xml)
xml)
GRANT
GRANT SELECT
SELECT TO
TO Salespeople;
Salespeople;

Demonstration 2A: Schemas


In this demonstration you will see how to:

Create a schema

Create a schema with an included object

Drop a schema

Lesson 3: Creating and Altering Tables


Creating Tables
Dropping Tables
Altering Tables
Demonstration 3A: Working with Tables
Temporary Tables
Demonstration 3B: Temporary Tables
Computed Columns
Demonstration 3C: Computed Columns

Creating Tables
Tables are created with the CREATE TABLE statement
Columns need to be specified
Nullability should be specified
Primary Key should be identified

CREATE
CREATE TABLE
TABLE PetStore.Owner
PetStore.Owner
( OwnerID
OwnerID int
int IDENTITY(1,1)
IDENTITY(1,1) NOT
NOT NULL
NULL PRIMARY
PRIMARY KEY,
KEY,
OwnerName
OwnerName nvarchar(50)
nvarchar(50) NOT
NOT NULL,
NULL,
HairColor
HairColor nvarchar(10)
nvarchar(10) NULL
NULL
);
);

Dropping Tables
Tables are removed by the DROP TABLE statement
Referenced tables (via foreign keys) cannot be dropped
All permissions, constraints, indexes, and triggers are also

dropped

Code that references the table is not dropped

Stored procedures

Functions

DROP
DROP TABLE
TABLE PetStore.Owner;
PetStore.Owner;
GO
GO

Altering Tables
Tables are modified using the ALTER TABLE statement
ALTER TABLE retains permissions on the table
ALTER TABLE retains the data in the table
Add/Drop columns and constraints
Enable/Disable constraints and triggers

ALTER
ALTER
ADD
ADD
GO
GO

TABLE
TABLE PetStore.Owner
PetStore.Owner
PreferredName
PreferredName nvarchar(30)
nvarchar(30) NULL;
NULL;

ALTER
ALTER TABLE
TABLE PetStore.Owner
PetStore.Owner
DROP
DROP COLUMN
COLUMN PreferredName;
PreferredName;
GO
GO

Demonstration 3A: Working with Tables


In this demonstration, you will see how to:

Create tables

Alter tables

Drop tables

Temporary Tables
Session temporary tables are only visible to their creators in the

same session and same scope or sub-scope

Created with a # prefix

Dropped when the user disconnects or when out of scope

Should be deleted in code rather than depending on automatic


drop

Are often created using SELECT INTO statements

Global temporary tables are visible to all users

Created with a ## prefix

Deleted
CREATE
TABLE
when#Squares
all users referencing the table disconnect
CREATE
TABLE
#Squares
(
( Number
Number int
int PRIMARY
PRIMARY KEY,
KEY,
NumberSquared int
int
);
);
GO
GO

Demonstration 3B: Temporary Tables


In this demonstration, you will see how to work with
temporary tables

Computed Columns
Computed columns are derived from other columns or from

functions

Computed columns are often used to provide easier access to

data without denormalizing it

Persisted computed columns improve SELECT performance of

computed columns in some situations

CREATE
CREATE TABLE
TABLE PetStore.Pet
PetStore.Pet
(PetID
(PetID int
int IDENTITY(1,1)
IDENTITY(1,1) PRIMARY
PRIMARY KEY,
KEY,
PetName
PetName nvarchar(30)
nvarchar(30) NOT
NOT NULL,
NULL,
DateOfBirth
DateOfBirth date
date NOT
NOT NULL,
NULL,
YearOfBirth
YearOfBirth AS
AS DATEPART(year,DateOfBirth)
DATEPART(year,DateOfBirth) PERSISTED
PERSISTED
);
);
GO
GO

Demonstration 3C: Computed Columns


In this demonstration, you will see how to work with
computed columns

Lab 3: Designing and Implementing Tables


Exercise 1: Improve the Design of Tables
Exercise 2: Create a Schema
Challenge Exercise 3: Create the Tables (Only if time

permits)

Logon information

Virtual machine

10776A-MIA-SQL1

User name

AdventureWorks\Administrator

Password

Pa$$w0rd

Estimated time: 45 minutes

Lab Scenario
A business analyst from your organization has provided you
with a first-pass at a schema design for some new tables
being added to the MarketDev database. You need to
provide an improved schema design based on good design
practices and an appropriate level of normalization. The
business analyst was also confused about when data should
be nullable. You need to decide about nullability for each
column in your improved design.
The new tables need to be isolated in their own schema.
You need to create the required schema DirectMarketing.
The owner of the schema should be dbo.
When the schema has been created, if you have available
time, you need to create the tables that have been
designed.

Lab Review
When should a column be declared as nullable?
Could columns such as AddressLine1, AddressLine2,

AddressLine3 be reasonable in a normalized design?

How would this differ from fields called PhoneNumber1,

PhoneNumber2, PhoneNumber3?

Module Review and Takeaways


Review Questions
Best Practices

You might also like