28
Module 3 Designing and Implementing Tables

Module 3 design and implementing tables

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Module 3 design and implementing tables

Module 3

Designing and Implementing Tables

Page 2: Module 3 design and implementing tables

Module Overview

•Designing Tables

•Working with Schemas

•Creating and Altering Tables

Page 3: Module 3 design and implementing 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

Page 4: Module 3 design and implementing 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

Page 5: Module 3 design and implementing tables

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

Page 6: Module 3 design and implementing tables

Common Normalization Forms

• 1st 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.

• 2nd Form

Create separate tables for sets of values that apply to multiple records.

Relate these tables with a foreign key.

• 3rd Form

Eliminate fields that do not depend on the key.

Page 7: Module 3 design and implementing tables

Demonstration 1A: Normalization

• In this demonstration, you will see the common normalization errors.

Page 8: Module 3 design and implementing tables

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

Page 9: Module 3 design and implementing tables

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

•Multiple foreign keys might exist in a table

These can even reference the same table

Page 10: Module 3 design and implementing tables

Working with System Tables

•SQL Server provides a set of system tables

Should not be directly modified

• In SQL Server 2005, most 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

Page 11: Module 3 design and implementing tables

Lesson 2: Working with Schemas

•What is a Schema?

•Object Name Resolution

•Creating Schemas

•Demonstration 2A: Schemas

Page 12: Module 3 design and implementing tables

What is a Schema?

•Schemas are containers for objects

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

Page 13: Module 3 design and implementing tables

Object Name Resolution

• If the schema name is omitted, rules apply to how the name will be resolved

Each user has a default schema (does not apply to Windows groups)

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

Page 14: Module 3 design and implementing tables

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 SCHEMA ReportingAUTHORIZATION Terry;

CREATE SCHEMA KnowledgeBaseAUTHORIZATION PaulCREATE TABLE Article (ArticleID int IDENTITY(1,1)

PRIMARY KEY,ArticleContents xml)

GRANT SELECT TO Salespeople;

Page 15: Module 3 design and implementing tables

Demonstration 2A: Schemas

• In this demonstration you will see how to:

Create a schema

Create a schema with an included object

Drop a schema

Page 16: Module 3 design and implementing tables

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

Page 17: Module 3 design and implementing tables

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 TABLE PetStore.Owner( OwnerID int IDENTITY(1,1) PRIMARY KEY,OwnerName nvarchar(30) NOT NULL,HairColor nvarchar(10) NULL

);

Page 18: Module 3 design and implementing tables

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 TABLE PetStore.Owner;GO

Page 19: Module 3 design and implementing tables

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 TABLE PetStore.OwnerADD PreferredName nvarchar(30) NULL;

GO

ALTER TABLE PetStore.OwnerDROP COLUMN PreferredName;

GO

Page 20: Module 3 design and implementing tables

Demonstration 3A: Working with Tables

• In this demonstration, you will see how to:

Create tables

Alter tables

Drop tables

Page 21: Module 3 design and implementing 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 when all users referencing the table disconnectCREATE TABLE #Squares( Number int PRIMARY KEY,NumberSquared int

);GO

Page 22: Module 3 design and implementing tables

Demonstration 3B: Temporary Tables

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

Page 23: Module 3 design and implementing 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 TABLE PetStore.Pet(PetID int IDENTITY(1,1) PRIMARY KEY,PetName nvarchar(30) NOT NULL,DateOfBirth date NOT NULL,YearOfBirth AS DATEPART(year,DateOfBirth) PERSISTED);GO

Page 24: Module 3 design and implementing tables

Demonstration 3C: Computed Columns

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

Page 25: Module 3 design and implementing tables

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

Estimated time: 45 minutes

Virtual machine 623XB-MIA-SQL

User name AdventureWorks\Administrator

Password Pa$$w0rd

Page 26: Module 3 design and implementing tables

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.

Page 27: Module 3 design and implementing tables

Lab Review

•When should a table 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?

Page 28: Module 3 design and implementing tables

Module Review and Takeaways

•Review Questions

•Best Practices