SlideShare a Scribd company logo
1 of 34
Designing and Creating a
Database – Part 2
   http://www.LearnNowOnline.com




        Learn More @ http://www.learnnowonline.com
        Copyright © by Application Developers Training Company
Objectives
• Learn basic relational database design principles
• Create a SQL Server database based on sound design
  principles
• Build tables using the SQL Server Management Studio
  designers
• Learn about SQL Server data types
• Create constraints, triggers, and indexes
• Create a database diagram and define relationships to
  enforce referential integrity

               Learn More @ http://www.learnnowonline.com
               Copyright © by Application Developers Training Company
Agenda
• Relational Database Design Principles
• Implementing Database Design




             Learn More @ http://www.learnnowonline.com
             Copyright © by Application Developers Training Company
Database Storage
• Pages
  • The minimum unit of storage: 8 KB
  • Maximum size of a row
     • Except long values: text, ntext, image, varchar(max), nvarchar(max),
       varbinary(max)
     • 8060 bytes, after deducting space for overhead

• Extents
  • 8 pages per Extent
  • New objects at first stored in spare pages in existing extents



                  Learn More @ http://www.learnnowonline.com
                  Copyright © by Application Developers Training Company
Database Storage
• Files
  • .MDF, .NDF, .LDF
  • The transaction log ensures data integrity
• Filegroups
  • Can locate data or indexes in additional files and on
    separate devices (disks)
  • Databases have two file names
     • Logical file name
     • Physical file name

                Learn More @ http://www.learnnowonline.com
                Copyright © by Application Developers Training Company
Data Integrity
•   The Transaction Log
    •    Automatically created with a database
    •    Records all activity in a database
•   SQL Server uses write-ahead strategy
    1.   Data pages are loaded into a buffer cache
    2.   Any updates are made to the copy in the buffer
    3.   A log record is created in a log cache
    4.   Checkpoint process saves the log record to disk
    •    Only then is the data saved to disk

                   Learn More @ http://www.learnnowonline.com
                   Copyright © by Application Developers Training Company
Recovery Models
• Simple
   • Log is truncated at checkpoint
   • Recovery to the point of the last full or differential backup
• Full
   • All operations are fully logged
   • Recovery to any point in time
• Bulk-logged
   • Faster bulk-logged operations (indexing, bulk load)
   • Recovery limited to logged transactions after the last
     backup

                  Learn More @ http://www.learnnowonline.com
                  Copyright © by Application Developers Training Company
Creating Databases
• Use Management Studio or Transact-SQL
  • SSMS uses T-SQL behind the scenes
  • Almost all SSMS actions follow this pattern
  • Most of the time you can access that code




              Learn More @ http://www.learnnowonline.com
               Copyright © by Application Developers Training Company
Rules for SQL Server Identifiers
• All object names must meet these requirements
• Length: 1 – 128 characters
• First character: letter, @, #, _ (no numbers)
   • @ only for local variables and parameters in T-SQL
   • # only for local temporary objects (temp tables)
   • ## for global temporary tables (span connections)
• Additional characters: letters, numbers, #, $, _
• Use square brackets or double quotes if identifier has
  spaces or other special characters
• No use of reserved keywords as identifiers

                 Learn More @ http://www.learnnowonline.com
                  Copyright © by Application Developers Training Company
Modifying Database Options
• Once you create the database, can set
  additional options




             Learn More @ http://www.learnnowonline.com
             Copyright © by Application Developers Training Company
Creating Tables
• New database doesn’t contain tables
• Table names must be unique
  • General format:
    server.database.schema_name.object_name
  • Usually can simplify
    schema_name.object_name
• Most work is creating the columns
• Can also define constraints

             Learn More @ http://www.learnnowonline.com
              Copyright © by Application Developers Training Company
Schemas
• Before SQL Server 2005, schema names based
  on user names
  • Except for dbo
  • Close tie was inconvenient
  • Now conforms to SQL standard
• Use any valid identifier for schema names
  • Can assign same schema to multiple users
  • Assign permissions to schema

              Learn More @ http://www.learnnowonline.com
              Copyright © by Application Developers Training Company
SQL Server Data Types
• Character-based data types
  • Non-Unicode
     • char — fixed length, up to 8,000
     • varchar — variable length, can set max
     • text — long values, up to 2 billion bytes
     • varchar(max) — long values, up to 2 billion bytes
  • Unicode equivalents
     • nchar — fixed length, up to 4,000
     • nvarchar — variable length, can set max
     • ntext — long Unicode values
     • nvarchar(max) — long Unicode values

                Learn More @ http://www.learnnowonline.com
                Copyright © by Application Developers Training Company
SQL Server Data Types
• Numeric data types
  • Whole Numbers
     • bit — 1 or 0, one bit of storage
     • tinyint — 0 to 255, one byte
     • smallint — +/- 32 K, two bytes
     • int — +/- 2 billion, four bytes
     • bigint — +/- 9 quintillion, 8 bytes




                 Learn More @ http://www.learnnowonline.com
                 Copyright © by Application Developers Training Company
SQL Server Data Types
• Numeric data types
  • Fractional Numbers
     • real — floating point, 4 bytes
     • float — floating point, 8 bytes
     • decimal/numeric — scaled integer
             storage varies (5 to 17 bytes)
             precision: total number of digits
                              (maximum of 38)
             scale: digits to the right of decimal
             each combination is a different type

                Learn More @ http://www.learnnowonline.com
                 Copyright © by Application Developers Training Company
SQL Server Data Types
• Numeric data types
  • Fractional Numbers
     • money — scaled integer, 8 bytes
            +/- 900 trillion
            4 digits to the right of the decimal
     • smallmoney — scaled integer, 4 bytes
            +/- 200 thousand
            4 digits to the right of the decimal



                Learn More @ http://www.learnnowonline.com
                 Copyright © by Application Developers Training Company
SQL Server Data Types
• Date data types
  • datetime — 8 bytes
      4 bytes: days before or after 1/1/1900
            (range: 1/1/1753-12/31/9999)
      4 bytes: milliseconds after midnight
            (rounded to .000, .003, .007 sec.)
  • smalldatetime — 4 bytes
      2 bytes: days after 1/1/1900
            (range: 1/1/1900-6/6/2079)
      2 bytes: minutes after midnight

                Learn More @ http://www.learnnowonline.com
                Copyright © by Application Developers Training Company
SQL Server Data Types
• Date data types
  • date — 3 bytes
     • Range: 0001-01-01 to 9999-12-31
  • time — 3 to 5 bytes
     • Range: 00:00:00.0000000 to 23:59:59.9999999
     • Precision up to 100 nanoseconds
  • datetime2 — 6 to 8 bytes
     • Range and precision of date and time types
     • No time zone or daylight savings time information
  • datetimeoffset — 8 to 10 bytes
     • datetime2 with time zone information
     • YYYY-MM-DDThh:mm:ss[.nnnnnnn][{+|-}hh:mm]
     • YYYY-MM-DDThh:mm:ss[.nnnnnnn]Z

                   Learn More @ http://www.learnnowonline.com
                   Copyright © by Application Developers Training Company
SQL Server Data Types
• Binary data types
  • binary — up to 8000 bytes, fixed length
  • varbinary — variable length
  • image — long values, up to 2 billion bytes
  • varbinary(max) — long values, up to 2 billion bytes




              Learn More @ http://www.learnnowonline.com
               Copyright © by Application Developers Training Company
SQL Server Data Types
• Identifier data types
  • The identity property
     • Not really a separate data type
     • Can be set for: tinyint, smallint, int, bigint, decimal, or
       numeric
     • Configure seed and increment values




                 Learn More @ http://www.learnnowonline.com
                  Copyright © by Application Developers Training Company
SQL Server Data Types
• Identifier data types
  • uniqueidentifier — a 16-byte GUID
     {40700425-0080-11d2-851f-00c04fc21759}
      • Used by SQL Server for replication
      • newid() function as default generates random IDs
      • newsequentialid() better for indexing
  • timestamp/rowversion — 8-byte unique binary
      • Updated automatically when row is modified
      • Unrelated to time
      • Used to track data changes (compare old and current values to see
        if row has changed)

                   Learn More @ http://www.learnnowonline.com
                   Copyright © by Application Developers Training Company
SQL Server Data Types
• The sql_variant data type
  • Introduced in SQL Server 2000
  • Can hold any other type of value,
    except text, ntext, image, *(max), xml, and
    timestamp
  • Useful for name/value pairs where the data type
    for the values may vary
  • More overhead than any other data types
     • Stores meta data as well as data:base data type,
      maximum size, scale, precision, and collation

               Learn More @ http://www.learnnowonline.com
                Copyright © by Application Developers Training Company
SQL Server Data Types
• Variable-only data types (not used in tables)
  • table
     • Temporary storage of a result set
     • Local scope
     • Used like any table, e.g., in FROM clause
     • No indexing or transactions
     • Primarily used for results from table-valued user-defined
       functions
  • Cursor
     • Used for variables or output parameters
     • Reference to a cursor


                Learn More @ http://www.learnnowonline.com
                Copyright © by Application Developers Training Company
SQL Server Data Types
• xml data type
  • Up to 2 Gigabytes
  • Available for table columns or for variables
  • Can reference an XML schema collection (typed
    xml)
  • Special methods for querying and modifying xml
  • Special indexes store individual xml nodes and
    paths to the nodes from the root
  • T-SQL supports a subset of the emerging XQuery
    standard for querying xml data


              Learn More @ http://www.learnnowonline.com
              Copyright © by Application Developers Training Company
SQL Server Data Types
• System SQLCLR types
  • Geometry and Geography for spatial data
  • HierarchyID for hierarchical data




              Learn More @ http://www.learnnowonline.com
               Copyright © by Application Developers Training Company
SQL Server Data Types
• User-Defined Types
  • Composed of standard types with saved settings
  • Or based on .NET assemblies




              Learn More @ http://www.learnnowonline.com
              Copyright © by Application Developers Training Company
Computed Columns
• Let you create a column that automatically
  updates values
  • Based on expression that you define
  • Can include references to other columns




              Learn More @ http://www.learnnowonline.com
              Copyright © by Application Developers Training Company
Creating Constraints
• Can restrict data that users enter in columns
  • Set restrictions, or constraints
  • Can place on columns as part of creating tables
       • Or add them later

• Types
  •   Primary key
  •   Foreign key
  •   Not Null
  •   Default
  •   Check
  •   Unique

                    Learn More @ http://www.learnnowonline.com
                    Copyright © by Application Developers Training Company
Default Constraints
• Enables a value to be entered automatically
  into a new row
  • When no other data is explicitly entered in that
    column
  • Define one default constraint per column




              Learn More @ http://www.learnnowonline.com
               Copyright © by Application Developers Training Company
Check Constraints
• Checks the data before saving record
  • If incoming data violates constraint, record isn’t
    saved
  • If value of constraint expression is False, constraint
    is violated
  • If null, will save data




               Learn More @ http://www.learnnowonline.com
               Copyright © by Application Developers Training Company
Triggers
•   Available on INSERT, UPDATE, DELETE
•   Access to special views: deleted, inserted
•   Can access and alter values in other tables
•   Uses:
    • Business rules, Audit trails, roll back
    • Originally used for referential integrity
• Caution: Maintenance and perf headaches
• Instead, use stored procedures for data modification
  if possible

                   Learn More @ http://www.learnnowonline.com
                   Copyright © by Application Developers Training Company
Creating Indexes
• Indexes let users query data efficiently
  • SQL Server can use a shortcut to find data
  • Instead of scanning entire table




              Learn More @ http://www.learnnowonline.com
               Copyright © by Application Developers Training Company
Using Database Diagrams
• Uses
  • Define foreign key constrains
  • Get high-level structure view of database
  • Perform other design tasks




              Learn More @ http://www.learnnowonline.com
              Copyright © by Application Developers Training Company
Questions?

   http://www.LearnNowOnline.com




        Learn More @ http://www.learnnowonline.com
        Copyright © by Application Developers Training Company

More Related Content

More from LearnNowOnline

Object oriented techniques
Object oriented techniquesObject oriented techniques
Object oriented techniquesLearnNowOnline
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptLearnNowOnline
 
SharePoint Document Management
SharePoint Document ManagementSharePoint Document Management
SharePoint Document ManagementLearnNowOnline
 
SharePoint: Introduction to InfoPath
SharePoint: Introduction to InfoPathSharePoint: Introduction to InfoPath
SharePoint: Introduction to InfoPathLearnNowOnline
 
Managing site collections
Managing site collectionsManaging site collections
Managing site collectionsLearnNowOnline
 
Sql 2012 development and programming
Sql 2012  development and programmingSql 2012  development and programming
Sql 2012 development and programmingLearnNowOnline
 
What's new in Silverlight 5
What's new in Silverlight 5What's new in Silverlight 5
What's new in Silverlight 5LearnNowOnline
 
KnockOutJS with ASP.NET MVC
KnockOutJS with ASP.NET MVCKnockOutJS with ASP.NET MVC
KnockOutJS with ASP.NET MVCLearnNowOnline
 
Expression Blend Motion & Interaction Design
Expression Blend Motion & Interaction DesignExpression Blend Motion & Interaction Design
Expression Blend Motion & Interaction DesignLearnNowOnline
 
Introducing the Entity Framework
Introducing the Entity FrameworkIntroducing the Entity Framework
Introducing the Entity FrameworkLearnNowOnline
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVCLearnNowOnline
 
Working with Controllers and Actions in MVC
Working with Controllers and Actions in MVCWorking with Controllers and Actions in MVC
Working with Controllers and Actions in MVCLearnNowOnline
 
Creating a User Interface
Creating a User InterfaceCreating a User Interface
Creating a User InterfaceLearnNowOnline
 
Building Windows 8 Metro Style Applications Using JavaScript and HTML5
Building Windows 8 Metro Style Applications Using JavaScript and HTML5Building Windows 8 Metro Style Applications Using JavaScript and HTML5
Building Windows 8 Metro Style Applications Using JavaScript and HTML5LearnNowOnline
 

More from LearnNowOnline (20)

Introducing LINQ
Introducing LINQIntroducing LINQ
Introducing LINQ
 
Generics
GenericsGenerics
Generics
 
Object oriented techniques
Object oriented techniquesObject oriented techniques
Object oriented techniques
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
SharePoint Document Management
SharePoint Document ManagementSharePoint Document Management
SharePoint Document Management
 
SharePoint: Introduction to InfoPath
SharePoint: Introduction to InfoPathSharePoint: Introduction to InfoPath
SharePoint: Introduction to InfoPath
 
Managing site collections
Managing site collectionsManaging site collections
Managing site collections
 
Web API HTTP Pipeline
Web API HTTP PipelineWeb API HTTP Pipeline
Web API HTTP Pipeline
 
Web API Basics
Web API BasicsWeb API Basics
Web API Basics
 
SQL Server: Security
SQL Server: SecuritySQL Server: Security
SQL Server: Security
 
Sql 2012 development and programming
Sql 2012  development and programmingSql 2012  development and programming
Sql 2012 development and programming
 
What's new in Silverlight 5
What's new in Silverlight 5What's new in Silverlight 5
What's new in Silverlight 5
 
KnockOutJS with ASP.NET MVC
KnockOutJS with ASP.NET MVCKnockOutJS with ASP.NET MVC
KnockOutJS with ASP.NET MVC
 
Expression Blend Motion & Interaction Design
Expression Blend Motion & Interaction DesignExpression Blend Motion & Interaction Design
Expression Blend Motion & Interaction Design
 
The Entity Data Model
The Entity Data ModelThe Entity Data Model
The Entity Data Model
 
Introducing the Entity Framework
Introducing the Entity FrameworkIntroducing the Entity Framework
Introducing the Entity Framework
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
Working with Controllers and Actions in MVC
Working with Controllers and Actions in MVCWorking with Controllers and Actions in MVC
Working with Controllers and Actions in MVC
 
Creating a User Interface
Creating a User InterfaceCreating a User Interface
Creating a User Interface
 
Building Windows 8 Metro Style Applications Using JavaScript and HTML5
Building Windows 8 Metro Style Applications Using JavaScript and HTML5Building Windows 8 Metro Style Applications Using JavaScript and HTML5
Building Windows 8 Metro Style Applications Using JavaScript and HTML5
 

Recently uploaded

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 

Recently uploaded (20)

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 

Designing and Creating an SQL Server Database

  • 1. Designing and Creating a Database – Part 2 http://www.LearnNowOnline.com Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 2. Objectives • Learn basic relational database design principles • Create a SQL Server database based on sound design principles • Build tables using the SQL Server Management Studio designers • Learn about SQL Server data types • Create constraints, triggers, and indexes • Create a database diagram and define relationships to enforce referential integrity Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 3. Agenda • Relational Database Design Principles • Implementing Database Design Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 4. Database Storage • Pages • The minimum unit of storage: 8 KB • Maximum size of a row • Except long values: text, ntext, image, varchar(max), nvarchar(max), varbinary(max) • 8060 bytes, after deducting space for overhead • Extents • 8 pages per Extent • New objects at first stored in spare pages in existing extents Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 5. Database Storage • Files • .MDF, .NDF, .LDF • The transaction log ensures data integrity • Filegroups • Can locate data or indexes in additional files and on separate devices (disks) • Databases have two file names • Logical file name • Physical file name Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 6. Data Integrity • The Transaction Log • Automatically created with a database • Records all activity in a database • SQL Server uses write-ahead strategy 1. Data pages are loaded into a buffer cache 2. Any updates are made to the copy in the buffer 3. A log record is created in a log cache 4. Checkpoint process saves the log record to disk • Only then is the data saved to disk Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 7. Recovery Models • Simple • Log is truncated at checkpoint • Recovery to the point of the last full or differential backup • Full • All operations are fully logged • Recovery to any point in time • Bulk-logged • Faster bulk-logged operations (indexing, bulk load) • Recovery limited to logged transactions after the last backup Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 8. Creating Databases • Use Management Studio or Transact-SQL • SSMS uses T-SQL behind the scenes • Almost all SSMS actions follow this pattern • Most of the time you can access that code Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 9. Rules for SQL Server Identifiers • All object names must meet these requirements • Length: 1 – 128 characters • First character: letter, @, #, _ (no numbers) • @ only for local variables and parameters in T-SQL • # only for local temporary objects (temp tables) • ## for global temporary tables (span connections) • Additional characters: letters, numbers, #, $, _ • Use square brackets or double quotes if identifier has spaces or other special characters • No use of reserved keywords as identifiers Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 10. Modifying Database Options • Once you create the database, can set additional options Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 11. Creating Tables • New database doesn’t contain tables • Table names must be unique • General format: server.database.schema_name.object_name • Usually can simplify schema_name.object_name • Most work is creating the columns • Can also define constraints Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 12. Schemas • Before SQL Server 2005, schema names based on user names • Except for dbo • Close tie was inconvenient • Now conforms to SQL standard • Use any valid identifier for schema names • Can assign same schema to multiple users • Assign permissions to schema Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 13. SQL Server Data Types • Character-based data types • Non-Unicode • char — fixed length, up to 8,000 • varchar — variable length, can set max • text — long values, up to 2 billion bytes • varchar(max) — long values, up to 2 billion bytes • Unicode equivalents • nchar — fixed length, up to 4,000 • nvarchar — variable length, can set max • ntext — long Unicode values • nvarchar(max) — long Unicode values Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 14. SQL Server Data Types • Numeric data types • Whole Numbers • bit — 1 or 0, one bit of storage • tinyint — 0 to 255, one byte • smallint — +/- 32 K, two bytes • int — +/- 2 billion, four bytes • bigint — +/- 9 quintillion, 8 bytes Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 15. SQL Server Data Types • Numeric data types • Fractional Numbers • real — floating point, 4 bytes • float — floating point, 8 bytes • decimal/numeric — scaled integer storage varies (5 to 17 bytes) precision: total number of digits (maximum of 38) scale: digits to the right of decimal each combination is a different type Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 16. SQL Server Data Types • Numeric data types • Fractional Numbers • money — scaled integer, 8 bytes +/- 900 trillion 4 digits to the right of the decimal • smallmoney — scaled integer, 4 bytes +/- 200 thousand 4 digits to the right of the decimal Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 17. SQL Server Data Types • Date data types • datetime — 8 bytes 4 bytes: days before or after 1/1/1900 (range: 1/1/1753-12/31/9999) 4 bytes: milliseconds after midnight (rounded to .000, .003, .007 sec.) • smalldatetime — 4 bytes 2 bytes: days after 1/1/1900 (range: 1/1/1900-6/6/2079) 2 bytes: minutes after midnight Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 18. SQL Server Data Types • Date data types • date — 3 bytes • Range: 0001-01-01 to 9999-12-31 • time — 3 to 5 bytes • Range: 00:00:00.0000000 to 23:59:59.9999999 • Precision up to 100 nanoseconds • datetime2 — 6 to 8 bytes • Range and precision of date and time types • No time zone or daylight savings time information • datetimeoffset — 8 to 10 bytes • datetime2 with time zone information • YYYY-MM-DDThh:mm:ss[.nnnnnnn][{+|-}hh:mm] • YYYY-MM-DDThh:mm:ss[.nnnnnnn]Z Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 19. SQL Server Data Types • Binary data types • binary — up to 8000 bytes, fixed length • varbinary — variable length • image — long values, up to 2 billion bytes • varbinary(max) — long values, up to 2 billion bytes Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 20. SQL Server Data Types • Identifier data types • The identity property • Not really a separate data type • Can be set for: tinyint, smallint, int, bigint, decimal, or numeric • Configure seed and increment values Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 21. SQL Server Data Types • Identifier data types • uniqueidentifier — a 16-byte GUID {40700425-0080-11d2-851f-00c04fc21759} • Used by SQL Server for replication • newid() function as default generates random IDs • newsequentialid() better for indexing • timestamp/rowversion — 8-byte unique binary • Updated automatically when row is modified • Unrelated to time • Used to track data changes (compare old and current values to see if row has changed) Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 22. SQL Server Data Types • The sql_variant data type • Introduced in SQL Server 2000 • Can hold any other type of value, except text, ntext, image, *(max), xml, and timestamp • Useful for name/value pairs where the data type for the values may vary • More overhead than any other data types • Stores meta data as well as data:base data type, maximum size, scale, precision, and collation Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 23. SQL Server Data Types • Variable-only data types (not used in tables) • table • Temporary storage of a result set • Local scope • Used like any table, e.g., in FROM clause • No indexing or transactions • Primarily used for results from table-valued user-defined functions • Cursor • Used for variables or output parameters • Reference to a cursor Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 24. SQL Server Data Types • xml data type • Up to 2 Gigabytes • Available for table columns or for variables • Can reference an XML schema collection (typed xml) • Special methods for querying and modifying xml • Special indexes store individual xml nodes and paths to the nodes from the root • T-SQL supports a subset of the emerging XQuery standard for querying xml data Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 25. SQL Server Data Types • System SQLCLR types • Geometry and Geography for spatial data • HierarchyID for hierarchical data Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 26. SQL Server Data Types • User-Defined Types • Composed of standard types with saved settings • Or based on .NET assemblies Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 27. Computed Columns • Let you create a column that automatically updates values • Based on expression that you define • Can include references to other columns Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 28. Creating Constraints • Can restrict data that users enter in columns • Set restrictions, or constraints • Can place on columns as part of creating tables • Or add them later • Types • Primary key • Foreign key • Not Null • Default • Check • Unique Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 29. Default Constraints • Enables a value to be entered automatically into a new row • When no other data is explicitly entered in that column • Define one default constraint per column Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 30. Check Constraints • Checks the data before saving record • If incoming data violates constraint, record isn’t saved • If value of constraint expression is False, constraint is violated • If null, will save data Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 31. Triggers • Available on INSERT, UPDATE, DELETE • Access to special views: deleted, inserted • Can access and alter values in other tables • Uses: • Business rules, Audit trails, roll back • Originally used for referential integrity • Caution: Maintenance and perf headaches • Instead, use stored procedures for data modification if possible Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 32. Creating Indexes • Indexes let users query data efficiently • SQL Server can use a shortcut to find data • Instead of scanning entire table Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 33. Using Database Diagrams • Uses • Define foreign key constrains • Get high-level structure view of database • Perform other design tasks Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company
  • 34. Questions? http://www.LearnNowOnline.com Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company

Editor's Notes

  1. DEMO – rest of section
  2. DEMO – rest of section
  3. DEMO
  4. DEMO – Try It Out!
  5. DEMO – rest of section
  6. DEMO – rest of section
  7. DEMO – Try It Out!
  8. DEMO – rest of section
  9. DEMO – create diagram for main table sin School database, rest of section, Right-Click Options