SlideShare une entreprise Scribd logo
1  sur  28
Télécharger pour lire hors ligne
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
• 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 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 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 information
Virtual machine      623XB-MIA-SQL

User name            AdventureWorksAdministrator
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 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

Contenu connexe

Tendances

Views and security
Views and securityViews and security
Views and securityfarhan amjad
 
Oracle Data Redaction
Oracle Data RedactionOracle Data Redaction
Oracle Data RedactionIvica Arsov
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...Jürgen Ambrosi
 
SQL302 Intermediate SQL Workshop 3
SQL302 Intermediate SQL Workshop 3SQL302 Intermediate SQL Workshop 3
SQL302 Intermediate SQL Workshop 3Dan D'Urso
 
Managing SQLserver for the reluctant DBA
Managing SQLserver for the reluctant DBAManaging SQLserver for the reluctant DBA
Managing SQLserver for the reluctant DBAConcentrated Technology
 
Create column store index on all supported tables in sql server 2014 copy
Create column store index on all supported tables in sql server 2014    copyCreate column store index on all supported tables in sql server 2014    copy
Create column store index on all supported tables in sql server 2014 copyMustafa EL-Masry
 
Copy Of Mysql Datadictionary
Copy Of Mysql DatadictionaryCopy Of Mysql Datadictionary
Copy Of Mysql DatadictionaryGolak Sarangi
 
Query Store and live Query Statistics
Query Store and live Query StatisticsQuery Store and live Query Statistics
Query Store and live Query StatisticsSolidQ
 
01 qmds2005 session01
01 qmds2005 session0101 qmds2005 session01
01 qmds2005 session01Niit Care
 
SQL302 Intermediate SQL Workshop 2
SQL302 Intermediate SQL Workshop 2SQL302 Intermediate SQL Workshop 2
SQL302 Intermediate SQL Workshop 2Dan D'Urso
 
SQL302 Intermediate SQL Workshop 1
SQL302 Intermediate SQL Workshop 1SQL302 Intermediate SQL Workshop 1
SQL302 Intermediate SQL Workshop 1Dan D'Urso
 
AppSense EM 8.5 Deep Dive
AppSense EM 8.5 Deep DiveAppSense EM 8.5 Deep Dive
AppSense EM 8.5 Deep DiveDave Allen
 
AppSense Environment Manager 8.5 Beta
AppSense Environment Manager 8.5 BetaAppSense Environment Manager 8.5 Beta
AppSense Environment Manager 8.5 BetaDave Allen
 
Controlling User Access -Data base
Controlling User Access -Data baseControlling User Access -Data base
Controlling User Access -Data baseSalman Memon
 

Tendances (18)

Views and security
Views and securityViews and security
Views and security
 
Oracle Data Redaction
Oracle Data RedactionOracle Data Redaction
Oracle Data Redaction
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
 
SQL302 Intermediate SQL Workshop 3
SQL302 Intermediate SQL Workshop 3SQL302 Intermediate SQL Workshop 3
SQL302 Intermediate SQL Workshop 3
 
Managing SQLserver for the reluctant DBA
Managing SQLserver for the reluctant DBAManaging SQLserver for the reluctant DBA
Managing SQLserver for the reluctant DBA
 
Create column store index on all supported tables in sql server 2014 copy
Create column store index on all supported tables in sql server 2014    copyCreate column store index on all supported tables in sql server 2014    copy
Create column store index on all supported tables in sql server 2014 copy
 
Oracle SQL Training in Chennai, Tambaram
Oracle SQL Training in Chennai, TambaramOracle SQL Training in Chennai, Tambaram
Oracle SQL Training in Chennai, Tambaram
 
MYSQL.ppt
MYSQL.pptMYSQL.ppt
MYSQL.ppt
 
FREE Sql Server syllabus
FREE Sql Server syllabusFREE Sql Server syllabus
FREE Sql Server syllabus
 
Copy Of Mysql Datadictionary
Copy Of Mysql DatadictionaryCopy Of Mysql Datadictionary
Copy Of Mysql Datadictionary
 
Query Store and live Query Statistics
Query Store and live Query StatisticsQuery Store and live Query Statistics
Query Store and live Query Statistics
 
01 qmds2005 session01
01 qmds2005 session0101 qmds2005 session01
01 qmds2005 session01
 
DB2 LUW Auditing
DB2 LUW AuditingDB2 LUW Auditing
DB2 LUW Auditing
 
SQL302 Intermediate SQL Workshop 2
SQL302 Intermediate SQL Workshop 2SQL302 Intermediate SQL Workshop 2
SQL302 Intermediate SQL Workshop 2
 
SQL302 Intermediate SQL Workshop 1
SQL302 Intermediate SQL Workshop 1SQL302 Intermediate SQL Workshop 1
SQL302 Intermediate SQL Workshop 1
 
AppSense EM 8.5 Deep Dive
AppSense EM 8.5 Deep DiveAppSense EM 8.5 Deep Dive
AppSense EM 8.5 Deep Dive
 
AppSense Environment Manager 8.5 Beta
AppSense Environment Manager 8.5 BetaAppSense Environment Manager 8.5 Beta
AppSense Environment Manager 8.5 Beta
 
Controlling User Access -Data base
Controlling User Access -Data baseControlling User Access -Data base
Controlling User Access -Data base
 

En vedette

En vedette (9)

Database Management Systems Project Report
Database Management Systems Project ReportDatabase Management Systems Project Report
Database Management Systems Project Report
 
2 designing tables
2 designing tables2 designing tables
2 designing tables
 
Criação e configuração de base de dados
Criação e configuração de base de dadosCriação e configuração de base de dados
Criação e configuração de base de dados
 
Operating Systems & Applications
Operating Systems & ApplicationsOperating Systems & Applications
Operating Systems & Applications
 
MS PowerPoint for Begninners
MS PowerPoint for BegninnersMS PowerPoint for Begninners
MS PowerPoint for Begninners
 
How to create MS PowerPoint
How to create MS PowerPointHow to create MS PowerPoint
How to create MS PowerPoint
 
MS powerpoint 2007 complete
MS powerpoint 2007 completeMS powerpoint 2007 complete
MS powerpoint 2007 complete
 
Operating Systems 1: Introduction
Operating Systems 1: IntroductionOperating Systems 1: Introduction
Operating Systems 1: Introduction
 
Ms word 2010 by sachin sharma
Ms word 2010 by sachin sharmaMs word 2010 by sachin sharma
Ms word 2010 by sachin sharma
 

Similaire à Module 3 design and implementing tables

•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdfjyothimuppasani1
 
Amazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and OptimizationAmazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and OptimizationAmazon Web Services
 
Implementing Tables and Views.pptx
Implementing Tables and Views.pptxImplementing Tables and Views.pptx
Implementing Tables and Views.pptxLuisManuelUrbinaAmad
 
Geek Sync | Why Did My Clever Index Change Backfire?
Geek Sync | Why Did My Clever Index Change Backfire?Geek Sync | Why Did My Clever Index Change Backfire?
Geek Sync | Why Did My Clever Index Change Backfire?IDERA Software
 
Obiee metadata development
Obiee metadata developmentObiee metadata development
Obiee metadata developmentdils4u
 
Data Modeling, Normalization, and Denormalisation | FOSDEM '19 | Dimitri Font...
Data Modeling, Normalization, and Denormalisation | FOSDEM '19 | Dimitri Font...Data Modeling, Normalization, and Denormalisation | FOSDEM '19 | Dimitri Font...
Data Modeling, Normalization, and Denormalisation | FOSDEM '19 | Dimitri Font...Citus Data
 
How Clean is your Database? Data Scrubbing for all Skill Sets
How Clean is your Database? Data Scrubbing for all Skill SetsHow Clean is your Database? Data Scrubbing for all Skill Sets
How Clean is your Database? Data Scrubbing for all Skill SetsChad Petrovay
 
Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)Guy Harrison
 
AWS (Amazon Redshift) presentation
AWS (Amazon Redshift) presentationAWS (Amazon Redshift) presentation
AWS (Amazon Redshift) presentationVolodymyr Rovetskiy
 
Geek Sync I Consolidating Indexes in SQL Server
Geek Sync I Consolidating Indexes in SQL ServerGeek Sync I Consolidating Indexes in SQL Server
Geek Sync I Consolidating Indexes in SQL ServerIDERA Software
 
Query Optimization in SQL Server
Query Optimization in SQL ServerQuery Optimization in SQL Server
Query Optimization in SQL ServerRajesh Gunasundaram
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server DatabasesColdFusionConference
 

Similaire à Module 3 design and implementing tables (20)

•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf
 
Amazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and OptimizationAmazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and Optimization
 
Access 03
Access 03Access 03
Access 03
 
Implementing Tables and Views.pptx
Implementing Tables and Views.pptxImplementing Tables and Views.pptx
Implementing Tables and Views.pptx
 
Geek Sync | Why Did My Clever Index Change Backfire?
Geek Sync | Why Did My Clever Index Change Backfire?Geek Sync | Why Did My Clever Index Change Backfire?
Geek Sync | Why Did My Clever Index Change Backfire?
 
Obiee metadata development
Obiee metadata developmentObiee metadata development
Obiee metadata development
 
Week3 to-design
Week3 to-designWeek3 to-design
Week3 to-design
 
SQL_Part1
SQL_Part1SQL_Part1
SQL_Part1
 
Database intro
Database introDatabase intro
Database intro
 
Data Modeling, Normalization, and Denormalisation | FOSDEM '19 | Dimitri Font...
Data Modeling, Normalization, and Denormalisation | FOSDEM '19 | Dimitri Font...Data Modeling, Normalization, and Denormalisation | FOSDEM '19 | Dimitri Font...
Data Modeling, Normalization, and Denormalisation | FOSDEM '19 | Dimitri Font...
 
How Clean is your Database? Data Scrubbing for all Skill Sets
How Clean is your Database? Data Scrubbing for all Skill SetsHow Clean is your Database? Data Scrubbing for all Skill Sets
How Clean is your Database? Data Scrubbing for all Skill Sets
 
Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)
 
AWS (Amazon Redshift) presentation
AWS (Amazon Redshift) presentationAWS (Amazon Redshift) presentation
AWS (Amazon Redshift) presentation
 
MS ACCESS.pptx
MS ACCESS.pptxMS ACCESS.pptx
MS ACCESS.pptx
 
Geek Sync I Consolidating Indexes in SQL Server
Geek Sync I Consolidating Indexes in SQL ServerGeek Sync I Consolidating Indexes in SQL Server
Geek Sync I Consolidating Indexes in SQL Server
 
Query Optimization in SQL Server
Query Optimization in SQL ServerQuery Optimization in SQL Server
Query Optimization in SQL Server
 
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
Views, Triggers, Functions, Stored Procedures,  Indexing and JoinsViews, Triggers, Functions, Stored Procedures,  Indexing and Joins
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
 
demo2.ppt
demo2.pptdemo2.ppt
demo2.ppt
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server Databases
 
MS-ACCESS.pptx
MS-ACCESS.pptxMS-ACCESS.pptx
MS-ACCESS.pptx
 

Module 3 design and implementing tables

  • 1. Module 3 Designing and Implementing Tables
  • 2. Module Overview • Designing Tables • Working with Schemas • Creating and Altering Tables
  • 3. Lesson 1: Designing Tables • What is a Table? • Normalizing Data • Common Normalization Forms • Demonstration 1A: Normalization • Primary Keys • Foreign Keys • Working with System Tables
  • 4. 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
  • 5. 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
  • 6. 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.
  • 7. Demonstration 1A: Normalization • In this demonstration, you will see the common normalization errors.
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. Lesson 2: Working with Schemas • What is a Schema? • Object Name Resolution • Creating Schemas • Demonstration 2A: Schemas
  • 12. 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
  • 13. 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
  • 14. 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;
  • 15. Demonstration 2A: Schemas • In this demonstration you will see how to:  Create a schema  Create a schema with an included object  Drop a schema
  • 16. 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
  • 17. 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 );
  • 18. 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
  • 19. 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
  • 20. Demonstration 3A: Working with Tables • In this demonstration, you will see how to:  Create tables  Alter tables  Drop tables
  • 21. 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
  • 22. Demonstration 3B: Temporary Tables • In this demonstration, you will see how to work with temporary tables
  • 23. 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
  • 24. Demonstration 3C: Computed Columns • In this demonstration, you will see how to work with computed columns
  • 25. 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 623XB-MIA-SQL User name AdventureWorksAdministrator Password Pa$$w0rd Estimated time: 45 minutes
  • 26. 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.
  • 27. 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?
  • 28. Module Review and Takeaways • Review Questions • Best Practices