Você está na página 1de 40

Module 2

Designing and Implementing


Tables
Module Overview

• Designing Tables
• Data Types
• Working with Schemas
• Creating and Altering Tables
Lesson 1: Designing Tables

• What Is a Table?
• Normalizing Data
• Common Normalization Forms
• Demonstration: Working with Normalization
• Primary Keys
• Foreign Keys
• Working with System Tables
• Designing for Concurrency
• Implementing Surrogate Keys
What Is a Table?

• Relational databases store data in tables (relations)


• Defined by a collection of columns (identified by name)
• Contain zero or more rows

• Tables typically represent a type of object or entity


• Employees, purchase orders, customers, and sales orders
are examples of entities
• Consistent naming convention for tables is important

• Tables are a security boundary


• Each row usually represents a single instance of the
object or entity
• One employee, or one purchase order, for example
• 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 to the degrees of normalization as forms

• Database designs should initially be normalized


• Denormalization might be applied later to improve
performance or to make analysis of data more
straightforward
Common Normalization Forms

• First Normal Form


• Eliminate repeating groups in individual tables
• Create a separate table for each set of related data
• Identify each set of related data by using a primary key

• Second Normal Form


• Non-key columns should not be dependent on only
part of a primary key
• These columns should be in a separate table and
related by using a foreign key
• Third Normal Form
• Eliminate fields that do not depend on the key
Demonstration: Working with Normalization

• In this demonstration, you will see how to alter a


table to conform to third normal form
Primary Keys

• The primary key uniquely identifies each row within a


table
• Candidate key could be used to uniquely identify a
row
• Must be unique and cannot be NULL (unknown)
• Can involve multiple columns
• Should not change
• Primary key is one candidate key
• Most tables will only have a single candidate key

• 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 the primary key from
another table
• Self-references are permitted

• Rows that do not exist in the referenced table


cannot be inserted in a referencing table
• Rows cannot be deleted or updated without
cascading options
• Multiple foreign keys can exist in one 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
Designing for Concurrency

• SQL Server uses locking to manage concurrency:


• Locks can be made at the row, page, or table level
• Row locking increases concurrency, but there is an
overhead of maintaining many locks
• OLTP databases should be normalized to
increase concurrency:
• Transactions should be small and fast
• Smaller tables (fewer columns) less likely to cause
locking issues
• Data warehouse tables should be
denormalized—no modifications to create
locking problems
Implementing Surrogate Keys

• Use IDENTITY with CREATE or ALTER TABLE to create a


unique, sequentially numbered column
• SET IDENTITY_INSERT ON allows explicit values to be inserted
into a column with IDENTITY
• @@IDENTITY returns the last value created by the IDENTITY
column across all sessions
• SCOPE_IDENTITY() returns the last value created by the IDENTITY
column for the current session
• SEQUENCE creates a numbered list that can be used by
all tables in the database
• The value increments each time the next value is requested
• Can be restarted
• MINVALUE and MAXVALUE set boundaries
Lesson 2: Data Types

• Introduction to Data Types


• Exact Numeric Data Types
• Approximate Numeric Data Types
• Date and Time Data Types
• Unique Identifiers
• NULL and NOT NULL
• Alias Data Types
• Converting Data Between Data Types
• Working with International Character Data
Introduction to Data Types

• Data types determine what can be stored


• Constrain the type of data that an object can hold and the
permitted operations
• Provide limits on the range of values
• Data types apply to database columns, variables,
expressions, and parameters
• Critical to choose appropriate data types
• Assist with query optimization
• Provide a level of self-documentation
• Three basic sets of data types
• System data types
• Alias data types
• User-defined data types
Exact Numeric Data Types

• Numeric types: range, precision, and accuracy


• tinyint: 8 bits (0 to 255)
• smallint: 16-bit integer (-32,768 to 32,767)
• int: 32-bit integer (-2,147,483,648 to 2,147,483,647)
• bigint: 64-bit integer (-2^63 to 2^63 - 1)
• decimal: fixed precision and scale (-10^38+1 to I0^38-1)
• numeric: functionally equivalent to decimal
• smallmoney: fixed scale of four decimal places in 32 bits—
avoid
• money: fixed scale of four decimal places in 64 bits—avoid
• bit values of 1, 0, or NULL
Approximate Numeric Data Types

• Two approximate numeric types are supported:


• float is from float(1) to float(53)
• float defaults to float(53)
• real is fixed 4-byte storage

• float and real are not regularly used in business


applications because they are not precise
Date and Time Data Types

• Rich set of options is available for storing date


and time data
• ISO standard date formats remove ambiguity in
date formats, for example 2016-06-01
• Large set of functions available for processing
date and time data types
Unique Identifiers

• uniqueidentifier data type is typically used for


storing GUID values
• GUID stands for globally unique identifier
• Storage is essentially a 128-bit integer, but
standard integer arithmetic is not supported
• =, <>, <, >, <=, >= are supported along with
NULL and NOT NULL checking
• IDENTITY cannot be used
• New values from NEWID() function
• Common error is to store GUIDs as strings
NULL and NOT NULL

• NULL or NOT NULL determines whether or not a


value must be provided
• NULL indicates the absence of a value
• Can be defined on columns and parameters
• Cannot be defined on variables
• SET ANSI_NULL_DFLT_ON—may be set on or off
Alias Data Types

• An alias data type is created using the CREATE


TYPE command
• The alias data type is created in the context of
the current database
• Create alias data types in the model database to
automatically create a user type in all future
databases
• Query sys.types to view alias data types for a
database
• Has same use as system types: set column,
variable, and parameter data types with alias
Converting Data Between Data Types
Working with International Character Data

• Unicode
• Is a worldwide character-encoding standard
• Simplifies software localization
• Improves multilingual character processing
• Is implemented in SQL Server as double-byte for
Unicode types
• Requires N prefix
• Uses LEN() to return number of characters
• Uses DATALENGTH() to return the number of bytes
Lesson 3: Working with Schemas

• What Is a Schema?
• Object Name Resolution
• Creating Schemas
• Demonstration: Working with 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 for name


resolution
• Users can have a default schema assigned
• Users who have no default schema will have dbo as their
default schema
• Initially, the user’s default schema is searched
• If the object is not found in the default schema, the dbo
schema is also searched
• When 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 by using the CREATE


SCHEMA command
• Schemas have owners
• Objects contained within schemas also have owners
• Specify objects and permissions when the
schema is created
Demonstration: Working with Schemas

In this demonstration, you will see how to:


• Create a schema
• Create a schema with an included object
• Drop a schema
Lesson 4: Creating and Altering Tables

• Creating Tables
• Dropping Tables
• Altering Tables
• Demonstration: Working with Tables
• Temporary Tables
• Demonstration: Working with Temporary Tables
• Computed Columns
• Demonstration: Working with Computed Columns
Creating Tables

• Tables are created using the CREATE TABLE


statement
• Specify column names and data types
• Specify NULL or NOT NULL
• Specify the primary key
Dropping Tables

• Tables are removed by using the DROP TABLE


statement
• Reference tables (via foreign keys) cannot be
dropped
• All permissions, constraints, indexes, and triggers
are also dropped
• Code that references the table, such as a stored
procedure, is not dropped
Altering Tables

• Use the ALTER TABLE statement to modify tables


• ALTER TABLE retains permissions to the table
• ALTER TABLE retains the data in the table
• ALTER TABLE is used to:
• Add or drop columns and constraints
• Enable or disable constraints and triggers
Demonstration: Working with Tables

In this demonstration, you will see how to:


• Create tables and alter tables
• Drop tables
Temporary Tables

• Session temporary tables are only visible to their


creators in the same session and same scope or
subscope
• Created with # prefix
• Dropped when the user disconnects or when out of
scope
• Should be deleted in code rather than depending on
automatic drop
• Often created by using SELECT INTO statements

• Global temporary tables are visible to all users


• Created with ## prefix
• Deleted when all users referencing the table disconnect
Demonstration: Working with Temporary Tables

In this demonstration, you will see how to:


• Create local temporary tables
• Create global temporary tables
• Access a global temporary table from another
session
Computed Columns

• Computed columns are derived from other


columns or 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
Demonstration: Working with Computed
Columns

In this demonstration, you will see how to:


• Work with computed columns
• Use PERSISTED columns
Lab: Designing and Implementing Tables

• Exercise 1: Designing Tables


• Exercise 2: Creating Schemas
• Exercise 3: Creating Tables

Logon Information
Virtual machine: 20762C-MIA-SQL
User name: ADVENTUREWORKS\Student
Password: Pa55w.rd

Estimated Time: 45 minutes


Lab Scenario

A business analyst from your organization has


given you a draft design for some new tables
being added to a database. You need to provide
an improved schema design, based on good
design practices. After you have designed the
schema and tables, you need to implement them
in the TSQL database.
Lab Review

• When should a column be declared as nullable?


Module Review and Takeaways

• Best Practice

Você também pode gostar