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• 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.
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• 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• 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
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 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 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 users 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 SCHEMA Reporting AUTHORIZATION Terry; CREATE SCHEMA KnowledgeBase AUTHORIZATION Paul CREATE TABLE Article (ArticleID int IDENTITY(1,1) PRIMARY KEY, ArticleContents xml) GRANT SELECT TO 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 TABLE PetStore.Owner ( OwnerID int IDENTITY(1,1) PRIMARY KEY, OwnerName nvarchar(30) NOT NULL, HairColor nvarchar(10) 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 TABLE PetStore.Owner; 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 TABLE PetStore.Owner ADD PreferredName nvarchar(30) NULL; GO ALTER TABLE PetStore.Owner DROP COLUMN PreferredName; 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 when all users referencing the table disconnect CREATE TABLE #Squares ( Number int PRIMARY KEY, NumberSquared int ); 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 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
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 informationVirtual machine 623XB-MIA-SQLUser name AdventureWorksAdministratorPassword Pa$$w0rdEstimated time: 45 minutes
Lab ScenarioA business analyst from your organization has provided youwith a first-pass at a schema design for some new tablesbeing added to the MarketDev database. You need toprovide an improved schema design based on good designpractices and an appropriate level of normalization. Thebusiness analyst was also confused about when data shouldbe nullable. You need to decide about nullability for eachcolumn 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 availabletime, you need to create the tables that have beendesigned.
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?
Module Review and Takeaways• Review Questions• Best Practices