SlideShare uma empresa Scribd logo
1 de 52
Creating Tables and Enforcing Data Integrity

Objectives
In this lesson, you will learn to:
 Create tables
 Insert rows into tables
 Delete tables
 Create user-defined datatype
 List various types of data integrity
 Add the following constraints to tables:
     PRIMARY KEY
     UNIQUE
     FOREIGN KEY
     CHECK
     DEFAULT
 ©NIIT                                       SQL/Lesson 5/Slide 1 of 52
Creating Tables and Enforcing Data Integrity

5.D.1 Creating a Table
 The details about a newspaper that publishes
  advertisements for Tebisco, Inc. have to be stored in the
  Recruitment database.
                  Attributes                Data
         Newspaper Code         0001
         Newspaper Name         Texas Times
         Region                 Texas
         Type of Newspaper      General
         Contact Person         Jackson Demello
         HO Address             4723 West Alabama
         City                   Houston
         State                  Texas
         Zip                    77015-4568
         Country Code           001
         Fax                    (713)451-6797
         Phone                  (713)451-6850

 ©NIIT                                              SQL/Lesson 5/Slide 2 of 52
Creating Tables and Enforcing Data Integrity

Task List
 Draft the statement to create a table
 Create the table in the database
 Check whether the table has been created
 Insert a row into the table




 ©NIIT                                       SQL/Lesson 5/Slide 3 of 52
Creating Tables and Enforcing Data Integrity

Draft the statement to create a table
 Tables: A table is a database object used to store data
    Data in a table is organized in rows and columns
    Each row in a table represents a unique record and each
     column represents an attribute of the record
 The CREATE TABLE Statement: Is used to create a table
    Syntax
     CREATE TABLE table_name
     (column_name datatype [NULL | NOT NULL]
     [IDENTITY (SEED,INCREMENT)],
     column_name datatype …)
     [ON {filegroup} | DEFAULT]

 Result:
    The name of the table to be created is Newspaper
 ©NIIT                                      SQL/Lesson 5/Slide 4 of 52
Creating Tables and Enforcing Data Integrity

Create the table in the database
 Action
    In the Query Analyzer window, type the given CREATE
     TABLE statement

         CREATE TABLE NewsPaper
         (cNewsPaperCode char(4) NOT NULL,
         cNewsPaperName char(20) NOT NULL,
         vRegion varchar(20),
         vTypeOfNewsPaper varchar(20),
         vContactPerson varchar(35),
         vHOAddress varchar(35),

 ©NIIT                                    SQL/Lesson 5/Slide 5 of 52
Creating Tables and Enforcing Data Integrity

Create the table in the database (Contd.)
         cCity char(20),
         cState char(20),
         cZip char(10),
         cCountryCode char(3),
         cFax char(15),
         cPhone char(15))
      Press F5 to execute the statement




 ©NIIT                                     SQL/Lesson 5/Slide 6 of 52
Creating Tables and Enforcing Data Integrity

Check whether the table has been created
 You can use the sp_help command to view the structure of
  the table

     Syntax
         sp_help table_name
     Action:
         ® In   the Query Analyzer window, type:
           sp_help Newspaper
         ® Press   F5 to execute



 ©NIIT                                             SQL/Lesson 5/Slide 7 of 52
Creating Tables and Enforcing Data Integrity

Insert a row into the table
 The INSERT Statement
    After the table structure has been created, data can be
     inserted into the table. You can insert data into the table
     by using the INSERT command

     Syntax
         INSERT [INTO] table_name [column_list]
         VALUES (values_list)




 ©NIIT                                         SQL/Lesson 5/Slide 8 of 52
Creating Tables and Enforcing Data Integrity

Insert a row into the table (Contd.)
 Action:
     In the Query Analyzer, type the INSERT statement given
      below:
         INSERT Newspaper
         VALUES('0001', 'Texas Times', 'Texas',
         'General', 'Jackson Demello',
         '4723 West Alabama', 'Houston', 'Texas',
         '77015-4568', '001', '(713)451-6797',
         '(713)451-6850')
     Press F5 to execute

 ©NIIT                                      SQL/Lesson 5/Slide 9 of 52
Creating Tables and Enforcing Data Integrity

5.P.1 Creating a Table
 You want to store the details about the colleges that
  Tebisco, Inc. visits for recruitment. A sample row is given
  below:
              Attribute           Data
          College Code      0002
          College Name      Cromwell College
          College Address   4010 Gartner Ave
          City              Abilene
          State             Texas
          Zip               79605-4123
          Phone             (915)692-6628



  The college code and name cannot be left blank.


 ©NIIT                                         SQL/Lesson 5/Slide 10 of 52
Creating Tables and Enforcing Data Integrity

5.D.2 Deleting a Table
 Remove the Newspaper table from the database.




 ©NIIT                                   SQL/Lesson 5/Slide 11 of 52
Creating Tables and Enforcing Data Integrity

Task List
 Draft the statement to remove a table from the database
 Remove the Newspaper table from the database
 Verify that the table has been removed from the database




 ©NIIT                                     SQL/Lesson 5/Slide 12 of 52
Creating Tables and Enforcing Data Integrity

Draft the statement to remove a table from the
database
 The DROP TABLE Statement
     Used to remove the table from the database
     Syntax
         DROP TABLE table_name
 Result:
     The statement to remove the Newspaper table is:
         DROP TABLE Newspaper


 ©NIIT                                     SQL/Lesson 5/Slide 13 of 52
Creating Tables and Enforcing Data Integrity

Remove the Newspaper table from the database
 Action
     In the Query Analyzer window, type:
         DROP TABLE Newspaper
     Press F5 to execute




 ©NIIT                                      SQL/Lesson 5/Slide 14 of 52
Creating Tables and Enforcing Data Integrity

Verify that the table has been removed from the
database
 Type the following command to view the table structure:
   sp_help Newspaper
 Action
     In the Query Analyzer window, type:
         sp_help Newspaper
     Press F5 to execute




 ©NIIT                                      SQL/Lesson 5/Slide 15 of 52
Creating Tables and Enforcing Data Integrity

Just a Minute…
 Draft the statement to remove the College table from the
  database.




 ©NIIT                                      SQL/Lesson 5/Slide 16 of 52
Creating Tables and Enforcing Data Integrity

User-Defined Datatypes
 Creating a User-Defined Datatype
     A user-defined datatype is created using the sp_addtype
      system stored procedure
     Syntax
         sp_addtype name, [system_data_type]
         [, 'null_type']




 ©NIIT                                      SQL/Lesson 5/Slide 17 of 52
Creating Tables and Enforcing Data Integrity

User-Defined Datatypes (Contd.)
 Dropping a User-Defined Datatype
      A user-defined datatype can be dropped using the
       sp_droptype system stored procedure
      Syntax
         sp_droptype type




 ©NIIT                                      SQL/Lesson 5/Slide 18 of 52
Creating Tables and Enforcing Data Integrity

5.D.3 Creating User-defined Datatypes
 The NewsAd and the Newspaper tables do not have the
  same datatype for the cNewspaperCode attribute. Create a
  user-defined datatype called typNewspaperCode that can be
  used to create the NewsAd and the Newspaper table. Create
  the NewsAd table in which the newspaper code is of
  typNewspaperCode datatype.




 ©NIIT                                    SQL/Lesson 5/Slide 19 of 52
Creating Tables and Enforcing Data Integrity

Task List
 Identify the inconsistency in the table structures
 Identify the system-defined datatype that can be converted
  to a user-defined datatype
 Identify the name for the user-defined datatype
 Create a user-defined datatype
 Verify that the datatype has been created
 Create the NewsAd table with the new datatype




 ©NIIT                                        SQL/Lesson 5/Slide 20 of 52
Creating Tables and Enforcing Data Integrity

Identify the inconsistency in the table structures
 User-defined datatypes
     Can be used to remove the inconsistency in table
      structures which arises when two attributes that should
      have the same system datatype use different system
      datatypes.
 Result:
     The cNewspaperCode attribute in the Newspaper table is
      of datatype char(4). The cNewspaperCode attribute in the
      NewsAd table is of datatype varchar(2). The datatype and
      the length of both these attributes are different. This gives
      rise to inconsistency in the table structure.

 ©NIIT                                         SQL/Lesson 5/Slide 21 of 52
Creating Tables and Enforcing Data Integrity

Identify the system-defined datatype that can be
converted to a user-defined datatype
 Result:
     The system-defined datatype of both attributes should be
      char(4)




 ©NIIT                                      SQL/Lesson 5/Slide 22 of 52
Creating Tables and Enforcing Data Integrity

Identify the name for the user-defined datatype
 The name of the datatype can be prefixed with the letters 'typ'
  for identifying the user-defined datatype
 Result:
     Name for the user-defined datatype is typNewspaperCode




 ©NIIT                                       SQL/Lesson 5/Slide 23 of 52
Creating Tables and Enforcing Data Integrity

Create a user-defined datatype
 Action:
     In the Query Analyzer window, type:
         sp_addtype typNewspaperCode, 'char(4)'
     Execute the query by clicking the Execute Query button




 ©NIIT                                      SQL/Lesson 5/Slide 24 of 52
Creating Tables and Enforcing Data Integrity

Verify that the datatype has been created
 The sp_help system stored procedure gives specific
  information about the object specified

     Syntax
         sp_help datatype_name
 Action:
     In the Query Analyzer window, type:
         sp_help typNewspaperCode
     Press F5 to execute



 ©NIIT                                      SQL/Lesson 5/Slide 25 of 52
Creating Tables and Enforcing Data Integrity

Create the table NewsAd with the new datatype
 Action:
     In the Query Analyzer window, type:
      CREATE TABLE NewsAd
      (
        cNewsAdNo char(4) NOT NULL,
        cNewspaperCode typNewspaperCode NOT NULL,
        dAdStartDate datetime,
        dDeadline datetime
      )
     Press F5 to execute


 ©NIIT                               SQL/Lesson 5/Slide 26 of 52
Creating Tables and Enforcing Data Integrity

Data Integrity
 Data integrity ensures the consistency and correctness of
  data stored in a database. It is broadly classified into the
  following four categories:
     Entity integrity
     Domain integrity
     Referential integrity
     User-defined integrity
 Entity Integrity
     Ensures that each row can be uniquely identified by an
      attribute called the primary key


 ©NIIT                                        SQL/Lesson 5/Slide 27 of 52
Creating Tables and Enforcing Data Integrity

Data Integrity (Contd.)
 Domain Integrity
     Ensures that only a valid range of values is allowed to be
      stored in a column
 Referential Integrity
     Ensures that the values of the foreign key match with the
      value of the corresponding primary key
 User-Defined Integrity
     Refers to a set of rules specified by a user, which do not
      belong to the entity, domain, and referential integrity
      categories

 ©NIIT                                        SQL/Lesson 5/Slide 28 of 52
Creating Tables and Enforcing Data Integrity

Just a Minute...
 Which integrity ensures that the values in the foreign key
  match with the value of the corresponding primary key?




 ©NIIT                                       SQL/Lesson 5/Slide 29 of 52
Creating Tables and Enforcing Data Integrity

Creating Constraints
 Constraints are created to ensure data integrity
 Constraints define rules that must be followed to maintain
  consistency and correctness of data
 A constraint can either be created at the time of creating a
  table or can be added later
 Constraints can be enforced at two levels:
     Column level
     Table level



 ©NIIT                                         SQL/Lesson 5/Slide 30 of 52
Creating Tables and Enforcing Data Integrity

Creating Constraints (Contd.)
 A constraint can be created using either of the following
  statements:
    CREATE TABLE statement
     CREATE TABLE table_name
     column_name CONSTRAINT constraint_name
     constraint_type [,CONSTRAINT
     constraint_name constraint_type]
     ALTER TABLE statement
      ALTER TABLE table_name
      [WITH CHECK | WITH NOCHECK]
      ADD CONSTRAINT constraint_name
      constraint_type

 ©NIIT                                       SQL/Lesson 5/Slide 31 of 52
Creating Tables and Enforcing Data Integrity

Creating Constraints (Contd.)
 Dropping Constraints
    A constraint can be dropped using the ALTER TABLE
     statement in the Query Analyzer
     Syntax
         ALTER TABLE table_name
         DROP CONSTRAINT constraint_name




 ©NIIT                                   SQL/Lesson 5/Slide 32 of 52
Creating Tables and Enforcing Data Integrity

Creating Constraints (Contd.)
 Types of Constraints
     The PRIMARY KEY Constraint
         ® Isdefined on a column or a set of columns whose
           values uniquely identify rows in a table
         ® Ensures   entity integrity
     Syntax
         [CONSTRAINT constraint_name PRIMARY KEY
         [CLUSTERED|NONCLUSTERED](col_name [, col_name
         [, col_name [, …]]])]




 ©NIIT                                       SQL/Lesson 5/Slide 33 of 52
Creating Tables and Enforcing Data Integrity

Creating Constraints (Contd.)
     The UNIQUE Constraint
       ® Is used to enforce uniqueness on non-primary key
         columns
       ® Multiple UNIQUE constraints can be created on a table
     Syntax
      [CONSTRAINT constraint_name UNIQUE
      [CLUSTERED | NONCLUSTERED](col_name [,
      col_name [, col_name [, …]]])




 ©NIIT                                      SQL/Lesson 5/Slide 34 of 52
Creating Tables and Enforcing Data Integrity

Creating Constraints (Contd.)
     The FOREIGN KEY Constraint
       ® Is used to remove the inconsistency in two tables
         when data in one table depends on data in another
         table
     Syntax
      [CONSTRAINT constraint_name FOREIGN KEY
      (col_name [, col_name [, …]])
      REFERENCES table_name (column_name [,
      column_name [, …]])]




 ©NIIT                                      SQL/Lesson 5/Slide 35 of 52
Creating Tables and Enforcing Data Integrity

Creating Constraints (Contd.)
     The CHECK Constraint
       ® Enforces domain integrity by restricting the values to be
         inserted in a column
     Syntax
      [CONSTRAINT constraint name] CHECK
      (expression)




 ©NIIT                                        SQL/Lesson 5/Slide 36 of 52
Creating Tables and Enforcing Data Integrity

Creating Constraints (Contd.)
     The DEFAULT Constraint
         ® It   is used to assign a constant value to a column
         ® Only one DEFAULT constraint can be created for a
           column
         ® The    column cannot be an IDENTITY column
     Syntax
         [CONSTRAINT constraint_name] DEFAULT
         (constant_expression | NULL)



 ©NIIT                                            SQL/Lesson 5/Slide 37 of 52
Creating Tables and Enforcing Data Integrity

Just a Minute…
 Which constraint enforces domain integrity by restricting the
  value to be inserted in a column?




 ©NIIT                                       SQL/Lesson 5/Slide 38 of 52
Creating Tables and Enforcing Data Integrity

5.D.4 Using Constraints
 The Newspaper and NewsAd tables have been finalized.
  Create the Newspaper table with the following data integrity
  rules:
    The cNewspaperCode attribute should be the primary key
    The cPhone attribute should be of the format ([0-9][0-9]
             [0-9])[0-9][0-9][0-9][0-9][0-9][0-9][0-9])
    The cCountryCode attribute should be 001 by default
 Modify the NewsAd table as specified below:
     cNewsAdNo should be the primary key
     cNewspaperCode should be the foreign key


 ©NIIT                                      SQL/Lesson 5/Slide 39 of 52
Creating Tables and Enforcing Data Integrity

Task List
 Identify how to enforce data integrity
 Draft the statement to create a table
 Create the table with constraints
 Verify constraints by inserting data




 ©NIIT                                     SQL/Lesson 5/Slide 40 of 52
Creating Tables and Enforcing Data Integrity

Identify how to enforce data integrity
 You can enforce data integrity by using constraints
 Result:
     For the Newspaper table:
         ® The
             phone number format can be given using the
          CHECK constraint
         ® Thecountry code can be given using the DEFAULT
          constraint
         ® Thenewspaper code can be made the primary key
          using the PRIMARY KEY constraint



 ©NIIT                                       SQL/Lesson 5/Slide 41 of 52
Creating Tables and Enforcing Data Integrity

Identify how to enforce data integrity (Contd.)
      For the NewsAd table:
         ® ThecNewsAdNo column can be made the primary key
          using the PRIMARY KEY constraint
         ® The cNewspaperCode attribute can be made the
          foreign key using the FOREIGN KEY constraint




 ©NIIT                                     SQL/Lesson 5/Slide 42 of 52
Creating Tables and Enforcing Data Integrity

Draft the statement to create a table
 Result:
     The command to create the Newspaper table would be as
      follows:
    CREATE TABLE Newspaper
    (cNewspaperCode typNewspaperCode CONSTRAINT
    pkNewspaperCode PRIMARY KEY,
    cNewspaperName char(20) NOT NULL,
    vRegion varchar(20),
    vTypeOfNewspaper varchar(20),
    vContactPerson varchar(35),
    vHOAddress varchar(35),

 ©NIIT                                    SQL/Lesson 5/Slide 43 of 52
Creating Tables and Enforcing Data Integrity

Draft the statement to create a table (Contd.)
     cCity char(20),
     cState char(20),
     cZip char(10),
     cCountryCode char(3) CONSTRAINT defCountryCode
     DEFAULT(‘001’),
     cFax char(15),
     cPhone char(15) CONSTRAINT chkPhone
     CHECK(cPhone
     LIKE('([0-9][0-9][0-9])[0-9][0-9][0-9]-[0-9][0-
     9][0-9][0-9]')))


 ©NIIT                                 SQL/Lesson 5/Slide 44 of 52
Creating Tables and Enforcing Data Integrity

Draft the statement to create a table(Contd.)
     The commands to modify the NewsAd table would be as
      follows:
    ALTER TABLE NewsAd
    ADD CONSTRAINT pkNewsAdNo PRIMARY KEY
    (cNewsAdNo)
    ALTER TABLE NewsAd
    ADD CONSTRAINT fkNewspaperCode
    FOREIGN KEY (cNewspaperCode)
    REFERENCES Newspaper(cNewspaperCode)

 ©NIIT                                   SQL/Lesson 5/Slide 45 of 52
Creating Tables and Enforcing Data Integrity

Create the table with the constraints
 Action:
     In the Query Analyzer window, type the query
     Execute the commands by clicking the Execute Query
      button




 ©NIIT                                      SQL/Lesson 5/Slide 46 of 52
Creating Tables and Enforcing Data Integrity

Verify the constraints by inserting data
 Verify the constraint by inserting data (into the Newspaper
  table)
                                                    Action
         Test   Attribute        Value in the INSERT     Result
         case                    statement.

         1      cPhone           3445AB323               The row would not be inserted, as the
                                                         telephone number contains character data

         2      cPhone           (212)345-2467           The row would be inserted, as this is a valid
                                                         format for a telephone number

         4      cCountrycode     005                     The row would be inserted with 005 in the
                                                         cCountryCode attribute

         5      cNewspaperCode   0001 (Already           The row when inserted would give an error,
                                 present in              since 0001 already exists for
                                 Newspaper table)        cNewspaperCode in the Newspaper table

         6      cNewspaperCode   0090 (not present in    The row would be inserted, as 0090 for
                                 the Newspaper           cNewspaperCode does not exist in the
                                 table)                  Newspaper table




 ©NIIT                                                                            SQL/Lesson 5/Slide 47 of 52
Creating Tables and Enforcing Data Integrity

Verify the constraints by inserting data (Contd.)
 Verify the constraint by inserting data (into the NewsAd
  table)
                                             Action
   Test   Attribute        Value in the INSERT    Result
   case                    statement.

   1      cNewsAdNo        0001 (Already          The row when inserted would give an error
                           present in the         since 0001 is already present for the
                           NewsAd table)          cNewsAdNo attribute in the NewsAd table

   2      cNewsAdNo        0035 (Not present in   The row would be inserted, since 0035 does
                           the NewsAd table)      not exist in the NewsAd table

   3      cNewspaperCode   0045 (Not present in   The row,when inserted would give an error, as
                           Newspaper table)       0045 does not exist for cNewspaperCode in
                                                  the Newspaper table

   4      cNewspaperCode   0001(Present in the    The row would be inserted, since 0001 for
                           Newspaper table)       cNewspaperCode does not exist in the
                                                  Newspaper table



 ©NIIT                                                               SQL/Lesson 5/Slide 48 of 52
Creating Tables and Enforcing Data Integrity

5.P.2 Using Constraints
 Create the College table with the following data integrity rules:
     cCollegeCode should be the primary key
     The phone number should be of the format ([0-9][0-9][0-9])
      [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]
     cCity should be “New Orleans” by default
 Create the CampusRecruitment table so that it satisfies the
  following data integrity rules:
     The cCampusRecruitmentCode column should be the
      primary key
     The cCollegeCode column should be the foreign key

 ©NIIT                                        SQL/Lesson 5/Slide 49 of 52
Creating Tables and Enforcing Data Integrity

Summary
In this lesson, you learned that:
 A table is a database object used to store data
 A table can be created using the CREATE TABLE statement
 The INSERT statement is used to insert data into the table
 The DROP TABLE statement is used to delete the table
 A user-defined datatype is created by a user and is based on
  a system datatype
 A user-defined datatype is created using the sp_addtype
  system stored procedure


 ©NIIT                                       SQL/Lesson 5/Slide 50 of 52
Creating Tables and Enforcing Data Integrity

Summary (Contd.)
 A user-defined datatype can be dropped using the sp_droptype
  system stored procedure
 sp_help provides information about a database object or a user-
  defined datatype
 Data integrity ensures the completeness, accuracy, and
  reliability of data contained in the database
 Data integrity can be classified as entity integrity, domain
   integrity, referential integrity, and user-defined integrity
 Data integrity can be enforced through constraints
 Constraints are rules that can be specified at either the table-
  level or the column-level

 ©NIIT                                        SQL/Lesson 5/Slide 51 of 52
Creating Tables and Enforcing Data Integrity

Summary (Contd.)
 A constraint can be created using either the CREATE TABLE
  or the ALTER TABLE statements
 A constraint can be dropped with the ALTER TABLE
  statement or by dropping the table
 Constraints are classified as PRIMARY, FOREIGN, UNIQUE,
  CHECK, and DEFAULT




 ©NIIT                                   SQL/Lesson 5/Slide 52 of 52

Mais conteúdo relacionado

Mais procurados

S1 relational database pdf
S1 relational database pdfS1 relational database pdf
S1 relational database pdf
aviy1966
 
Unit 42 Assignment 2
Unit 42 Assignment 2Unit 42 Assignment 2
Unit 42 Assignment 2
Alex Dennis
 
Topic 4 intro spss_stata 30032012 sy_srini
Topic 4 intro spss_stata 30032012 sy_sriniTopic 4 intro spss_stata 30032012 sy_srini
Topic 4 intro spss_stata 30032012 sy_srini
SM Lalon
 

Mais procurados (20)

S1 relational database pdf
S1 relational database pdfS1 relational database pdf
S1 relational database pdf
 
Teradata imp
Teradata impTeradata imp
Teradata imp
 
MS EXCEL PPT PRESENTATION
MS EXCEL PPT PRESENTATIONMS EXCEL PPT PRESENTATION
MS EXCEL PPT PRESENTATION
 
Partitioning tables and indexing them
Partitioning tables and indexing them Partitioning tables and indexing them
Partitioning tables and indexing them
 
Using Microsoft Excel7 Advanced
Using Microsoft Excel7 AdvancedUsing Microsoft Excel7 Advanced
Using Microsoft Excel7 Advanced
 
Partitioning Tables and Indexing Them --- Article
Partitioning Tables and Indexing Them --- ArticlePartitioning Tables and Indexing Them --- Article
Partitioning Tables and Indexing Them --- Article
 
MICROSOFT ACCESS (ICTL)
MICROSOFT ACCESS (ICTL)MICROSOFT ACCESS (ICTL)
MICROSOFT ACCESS (ICTL)
 
SPSS GUIDE
SPSS GUIDESPSS GUIDE
SPSS GUIDE
 
Introtosqltuning
IntrotosqltuningIntrotosqltuning
Introtosqltuning
 
Sql ch 4
Sql ch 4Sql ch 4
Sql ch 4
 
Pivot tableinfo
Pivot tableinfoPivot tableinfo
Pivot tableinfo
 
Database concepts
Database conceptsDatabase concepts
Database concepts
 
Excel 2007 Unit P
Excel 2007 Unit PExcel 2007 Unit P
Excel 2007 Unit P
 
New Perspectives: Access.02
New Perspectives: Access.02New Perspectives: Access.02
New Perspectives: Access.02
 
Unit 42 Assignment 2
Unit 42 Assignment 2Unit 42 Assignment 2
Unit 42 Assignment 2
 
Excel tips and tricks you should try
Excel tips and tricks you should tryExcel tips and tricks you should try
Excel tips and tricks you should try
 
Gd401 1 p autocad tables-doc
Gd401 1 p autocad tables-docGd401 1 p autocad tables-doc
Gd401 1 p autocad tables-doc
 
Sq lite module2
Sq lite module2Sq lite module2
Sq lite module2
 
Dynamic Chart Switcher
Dynamic Chart SwitcherDynamic Chart Switcher
Dynamic Chart Switcher
 
Topic 4 intro spss_stata 30032012 sy_srini
Topic 4 intro spss_stata 30032012 sy_sriniTopic 4 intro spss_stata 30032012 sy_srini
Topic 4 intro spss_stata 30032012 sy_srini
 

Destaque (8)

Relational databe
Relational databeRelational databe
Relational databe
 
SQL: Unique IDs, Primary Keys and Archiving Inactive Rows Without Violating C...
SQL: Unique IDs, Primary Keys and Archiving Inactive Rows Without Violating C...SQL: Unique IDs, Primary Keys and Archiving Inactive Rows Without Violating C...
SQL: Unique IDs, Primary Keys and Archiving Inactive Rows Without Violating C...
 
8. sql
8. sql8. sql
8. sql
 
oracle Sql constraint
oracle  Sql constraint oracle  Sql constraint
oracle Sql constraint
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
SQL Tutorial - Table Constraints
SQL Tutorial - Table ConstraintsSQL Tutorial - Table Constraints
SQL Tutorial - Table Constraints
 
Sql database object
Sql database objectSql database object
Sql database object
 
Error localization
Error localizationError localization
Error localization
 

Semelhante a Sql xp 05

Charles WilliamsCS362Unit 3 Discussion BoardStructured Query Langu.docx
Charles WilliamsCS362Unit 3 Discussion BoardStructured Query Langu.docxCharles WilliamsCS362Unit 3 Discussion BoardStructured Query Langu.docx
Charles WilliamsCS362Unit 3 Discussion BoardStructured Query Langu.docx
christinemaritza
 
Structured Query Language for Data Management 2 Sructu.docx
Structured Query Language for Data Management      2 Sructu.docxStructured Query Language for Data Management      2 Sructu.docx
Structured Query Language for Data Management 2 Sructu.docx
johniemcm5zt
 
INTRODUCTION TO ACCESSOBJECTIVESDefine th.docx
INTRODUCTION TO ACCESSOBJECTIVESDefine th.docxINTRODUCTION TO ACCESSOBJECTIVESDefine th.docx
INTRODUCTION TO ACCESSOBJECTIVESDefine th.docx
mariuse18nolet
 
Lab 2 Work with Dictionary and Create Relational Database (60 pts.).docx
Lab 2 Work with Dictionary and Create Relational Database (60 pts.).docxLab 2 Work with Dictionary and Create Relational Database (60 pts.).docx
Lab 2 Work with Dictionary and Create Relational Database (60 pts.).docx
VinaOconner450
 

Semelhante a Sql xp 05 (20)

Sql xp 01
Sql xp 01Sql xp 01
Sql xp 01
 
T6
T6T6
T6
 
Tufte Sample Bi Portfolio
Tufte Sample Bi PortfolioTufte Sample Bi Portfolio
Tufte Sample Bi Portfolio
 
Basics of Microsoft Business Intelligence and Data Integration Techniques
Basics of Microsoft Business Intelligence and Data Integration TechniquesBasics of Microsoft Business Intelligence and Data Integration Techniques
Basics of Microsoft Business Intelligence and Data Integration Techniques
 
Advanced database
Advanced databaseAdvanced database
Advanced database
 
Sql xp 02
Sql xp 02Sql xp 02
Sql xp 02
 
chap 7.ppt(sql).ppt
chap 7.ppt(sql).pptchap 7.ppt(sql).ppt
chap 7.ppt(sql).ppt
 
Access Basics 01
Access Basics 01Access Basics 01
Access Basics 01
 
Charles WilliamsCS362Unit 3 Discussion BoardStructured Query Langu.docx
Charles WilliamsCS362Unit 3 Discussion BoardStructured Query Langu.docxCharles WilliamsCS362Unit 3 Discussion BoardStructured Query Langu.docx
Charles WilliamsCS362Unit 3 Discussion BoardStructured Query Langu.docx
 
Structured Query Language for Data Management 2 Sructu.docx
Structured Query Language for Data Management      2 Sructu.docxStructured Query Language for Data Management      2 Sructu.docx
Structured Query Language for Data Management 2 Sructu.docx
 
7. SQL.pptx
7. SQL.pptx7. SQL.pptx
7. SQL.pptx
 
SQL
SQLSQL
SQL
 
The Database Environment Chapter 7
The Database Environment Chapter 7The Database Environment Chapter 7
The Database Environment Chapter 7
 
U-SQL Partitioned Data and Tables (SQLBits 2016)
U-SQL Partitioned Data and Tables (SQLBits 2016)U-SQL Partitioned Data and Tables (SQLBits 2016)
U-SQL Partitioned Data and Tables (SQLBits 2016)
 
Database use
Database useDatabase use
Database use
 
Chap 7
Chap 7Chap 7
Chap 7
 
INTRODUCTION TO ACCESSOBJECTIVESDefine th.docx
INTRODUCTION TO ACCESSOBJECTIVESDefine th.docxINTRODUCTION TO ACCESSOBJECTIVESDefine th.docx
INTRODUCTION TO ACCESSOBJECTIVESDefine th.docx
 
Lab 2 Work with Dictionary and Create Relational Database (60 pts.).docx
Lab 2 Work with Dictionary and Create Relational Database (60 pts.).docxLab 2 Work with Dictionary and Create Relational Database (60 pts.).docx
Lab 2 Work with Dictionary and Create Relational Database (60 pts.).docx
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
 
Bank mangement system
Bank mangement systemBank mangement system
Bank mangement system
 

Mais de Niit Care (20)

Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
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
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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...
 
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...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 

Sql xp 05

  • 1. Creating Tables and Enforcing Data Integrity Objectives In this lesson, you will learn to: Create tables Insert rows into tables Delete tables Create user-defined datatype List various types of data integrity Add the following constraints to tables: PRIMARY KEY UNIQUE FOREIGN KEY CHECK DEFAULT ©NIIT SQL/Lesson 5/Slide 1 of 52
  • 2. Creating Tables and Enforcing Data Integrity 5.D.1 Creating a Table The details about a newspaper that publishes advertisements for Tebisco, Inc. have to be stored in the Recruitment database. Attributes Data Newspaper Code 0001 Newspaper Name Texas Times Region Texas Type of Newspaper General Contact Person Jackson Demello HO Address 4723 West Alabama City Houston State Texas Zip 77015-4568 Country Code 001 Fax (713)451-6797 Phone (713)451-6850 ©NIIT SQL/Lesson 5/Slide 2 of 52
  • 3. Creating Tables and Enforcing Data Integrity Task List Draft the statement to create a table Create the table in the database Check whether the table has been created Insert a row into the table ©NIIT SQL/Lesson 5/Slide 3 of 52
  • 4. Creating Tables and Enforcing Data Integrity Draft the statement to create a table Tables: A table is a database object used to store data Data in a table is organized in rows and columns Each row in a table represents a unique record and each column represents an attribute of the record The CREATE TABLE Statement: Is used to create a table Syntax CREATE TABLE table_name (column_name datatype [NULL | NOT NULL] [IDENTITY (SEED,INCREMENT)], column_name datatype …) [ON {filegroup} | DEFAULT] Result: The name of the table to be created is Newspaper ©NIIT SQL/Lesson 5/Slide 4 of 52
  • 5. Creating Tables and Enforcing Data Integrity Create the table in the database Action In the Query Analyzer window, type the given CREATE TABLE statement CREATE TABLE NewsPaper (cNewsPaperCode char(4) NOT NULL, cNewsPaperName char(20) NOT NULL, vRegion varchar(20), vTypeOfNewsPaper varchar(20), vContactPerson varchar(35), vHOAddress varchar(35), ©NIIT SQL/Lesson 5/Slide 5 of 52
  • 6. Creating Tables and Enforcing Data Integrity Create the table in the database (Contd.) cCity char(20), cState char(20), cZip char(10), cCountryCode char(3), cFax char(15), cPhone char(15)) Press F5 to execute the statement ©NIIT SQL/Lesson 5/Slide 6 of 52
  • 7. Creating Tables and Enforcing Data Integrity Check whether the table has been created You can use the sp_help command to view the structure of the table Syntax sp_help table_name Action: ® In the Query Analyzer window, type: sp_help Newspaper ® Press F5 to execute ©NIIT SQL/Lesson 5/Slide 7 of 52
  • 8. Creating Tables and Enforcing Data Integrity Insert a row into the table The INSERT Statement After the table structure has been created, data can be inserted into the table. You can insert data into the table by using the INSERT command Syntax INSERT [INTO] table_name [column_list] VALUES (values_list) ©NIIT SQL/Lesson 5/Slide 8 of 52
  • 9. Creating Tables and Enforcing Data Integrity Insert a row into the table (Contd.) Action: In the Query Analyzer, type the INSERT statement given below: INSERT Newspaper VALUES('0001', 'Texas Times', 'Texas', 'General', 'Jackson Demello', '4723 West Alabama', 'Houston', 'Texas', '77015-4568', '001', '(713)451-6797', '(713)451-6850') Press F5 to execute ©NIIT SQL/Lesson 5/Slide 9 of 52
  • 10. Creating Tables and Enforcing Data Integrity 5.P.1 Creating a Table You want to store the details about the colleges that Tebisco, Inc. visits for recruitment. A sample row is given below: Attribute Data College Code 0002 College Name Cromwell College College Address 4010 Gartner Ave City Abilene State Texas Zip 79605-4123 Phone (915)692-6628 The college code and name cannot be left blank. ©NIIT SQL/Lesson 5/Slide 10 of 52
  • 11. Creating Tables and Enforcing Data Integrity 5.D.2 Deleting a Table Remove the Newspaper table from the database. ©NIIT SQL/Lesson 5/Slide 11 of 52
  • 12. Creating Tables and Enforcing Data Integrity Task List Draft the statement to remove a table from the database Remove the Newspaper table from the database Verify that the table has been removed from the database ©NIIT SQL/Lesson 5/Slide 12 of 52
  • 13. Creating Tables and Enforcing Data Integrity Draft the statement to remove a table from the database The DROP TABLE Statement Used to remove the table from the database Syntax DROP TABLE table_name Result: The statement to remove the Newspaper table is: DROP TABLE Newspaper ©NIIT SQL/Lesson 5/Slide 13 of 52
  • 14. Creating Tables and Enforcing Data Integrity Remove the Newspaper table from the database Action In the Query Analyzer window, type: DROP TABLE Newspaper Press F5 to execute ©NIIT SQL/Lesson 5/Slide 14 of 52
  • 15. Creating Tables and Enforcing Data Integrity Verify that the table has been removed from the database Type the following command to view the table structure: sp_help Newspaper Action In the Query Analyzer window, type: sp_help Newspaper Press F5 to execute ©NIIT SQL/Lesson 5/Slide 15 of 52
  • 16. Creating Tables and Enforcing Data Integrity Just a Minute… Draft the statement to remove the College table from the database. ©NIIT SQL/Lesson 5/Slide 16 of 52
  • 17. Creating Tables and Enforcing Data Integrity User-Defined Datatypes Creating a User-Defined Datatype A user-defined datatype is created using the sp_addtype system stored procedure Syntax sp_addtype name, [system_data_type] [, 'null_type'] ©NIIT SQL/Lesson 5/Slide 17 of 52
  • 18. Creating Tables and Enforcing Data Integrity User-Defined Datatypes (Contd.) Dropping a User-Defined Datatype A user-defined datatype can be dropped using the sp_droptype system stored procedure Syntax sp_droptype type ©NIIT SQL/Lesson 5/Slide 18 of 52
  • 19. Creating Tables and Enforcing Data Integrity 5.D.3 Creating User-defined Datatypes The NewsAd and the Newspaper tables do not have the same datatype for the cNewspaperCode attribute. Create a user-defined datatype called typNewspaperCode that can be used to create the NewsAd and the Newspaper table. Create the NewsAd table in which the newspaper code is of typNewspaperCode datatype. ©NIIT SQL/Lesson 5/Slide 19 of 52
  • 20. Creating Tables and Enforcing Data Integrity Task List Identify the inconsistency in the table structures Identify the system-defined datatype that can be converted to a user-defined datatype Identify the name for the user-defined datatype Create a user-defined datatype Verify that the datatype has been created Create the NewsAd table with the new datatype ©NIIT SQL/Lesson 5/Slide 20 of 52
  • 21. Creating Tables and Enforcing Data Integrity Identify the inconsistency in the table structures User-defined datatypes Can be used to remove the inconsistency in table structures which arises when two attributes that should have the same system datatype use different system datatypes. Result: The cNewspaperCode attribute in the Newspaper table is of datatype char(4). The cNewspaperCode attribute in the NewsAd table is of datatype varchar(2). The datatype and the length of both these attributes are different. This gives rise to inconsistency in the table structure. ©NIIT SQL/Lesson 5/Slide 21 of 52
  • 22. Creating Tables and Enforcing Data Integrity Identify the system-defined datatype that can be converted to a user-defined datatype Result: The system-defined datatype of both attributes should be char(4) ©NIIT SQL/Lesson 5/Slide 22 of 52
  • 23. Creating Tables and Enforcing Data Integrity Identify the name for the user-defined datatype The name of the datatype can be prefixed with the letters 'typ' for identifying the user-defined datatype Result: Name for the user-defined datatype is typNewspaperCode ©NIIT SQL/Lesson 5/Slide 23 of 52
  • 24. Creating Tables and Enforcing Data Integrity Create a user-defined datatype Action: In the Query Analyzer window, type: sp_addtype typNewspaperCode, 'char(4)' Execute the query by clicking the Execute Query button ©NIIT SQL/Lesson 5/Slide 24 of 52
  • 25. Creating Tables and Enforcing Data Integrity Verify that the datatype has been created The sp_help system stored procedure gives specific information about the object specified Syntax sp_help datatype_name Action: In the Query Analyzer window, type: sp_help typNewspaperCode Press F5 to execute ©NIIT SQL/Lesson 5/Slide 25 of 52
  • 26. Creating Tables and Enforcing Data Integrity Create the table NewsAd with the new datatype Action: In the Query Analyzer window, type: CREATE TABLE NewsAd ( cNewsAdNo char(4) NOT NULL, cNewspaperCode typNewspaperCode NOT NULL, dAdStartDate datetime, dDeadline datetime ) Press F5 to execute ©NIIT SQL/Lesson 5/Slide 26 of 52
  • 27. Creating Tables and Enforcing Data Integrity Data Integrity Data integrity ensures the consistency and correctness of data stored in a database. It is broadly classified into the following four categories: Entity integrity Domain integrity Referential integrity User-defined integrity Entity Integrity Ensures that each row can be uniquely identified by an attribute called the primary key ©NIIT SQL/Lesson 5/Slide 27 of 52
  • 28. Creating Tables and Enforcing Data Integrity Data Integrity (Contd.) Domain Integrity Ensures that only a valid range of values is allowed to be stored in a column Referential Integrity Ensures that the values of the foreign key match with the value of the corresponding primary key User-Defined Integrity Refers to a set of rules specified by a user, which do not belong to the entity, domain, and referential integrity categories ©NIIT SQL/Lesson 5/Slide 28 of 52
  • 29. Creating Tables and Enforcing Data Integrity Just a Minute... Which integrity ensures that the values in the foreign key match with the value of the corresponding primary key? ©NIIT SQL/Lesson 5/Slide 29 of 52
  • 30. Creating Tables and Enforcing Data Integrity Creating Constraints Constraints are created to ensure data integrity Constraints define rules that must be followed to maintain consistency and correctness of data A constraint can either be created at the time of creating a table or can be added later Constraints can be enforced at two levels: Column level Table level ©NIIT SQL/Lesson 5/Slide 30 of 52
  • 31. Creating Tables and Enforcing Data Integrity Creating Constraints (Contd.) A constraint can be created using either of the following statements: CREATE TABLE statement CREATE TABLE table_name column_name CONSTRAINT constraint_name constraint_type [,CONSTRAINT constraint_name constraint_type] ALTER TABLE statement ALTER TABLE table_name [WITH CHECK | WITH NOCHECK] ADD CONSTRAINT constraint_name constraint_type ©NIIT SQL/Lesson 5/Slide 31 of 52
  • 32. Creating Tables and Enforcing Data Integrity Creating Constraints (Contd.) Dropping Constraints A constraint can be dropped using the ALTER TABLE statement in the Query Analyzer Syntax ALTER TABLE table_name DROP CONSTRAINT constraint_name ©NIIT SQL/Lesson 5/Slide 32 of 52
  • 33. Creating Tables and Enforcing Data Integrity Creating Constraints (Contd.) Types of Constraints The PRIMARY KEY Constraint ® Isdefined on a column or a set of columns whose values uniquely identify rows in a table ® Ensures entity integrity Syntax [CONSTRAINT constraint_name PRIMARY KEY [CLUSTERED|NONCLUSTERED](col_name [, col_name [, col_name [, …]]])] ©NIIT SQL/Lesson 5/Slide 33 of 52
  • 34. Creating Tables and Enforcing Data Integrity Creating Constraints (Contd.) The UNIQUE Constraint ® Is used to enforce uniqueness on non-primary key columns ® Multiple UNIQUE constraints can be created on a table Syntax [CONSTRAINT constraint_name UNIQUE [CLUSTERED | NONCLUSTERED](col_name [, col_name [, col_name [, …]]]) ©NIIT SQL/Lesson 5/Slide 34 of 52
  • 35. Creating Tables and Enforcing Data Integrity Creating Constraints (Contd.) The FOREIGN KEY Constraint ® Is used to remove the inconsistency in two tables when data in one table depends on data in another table Syntax [CONSTRAINT constraint_name FOREIGN KEY (col_name [, col_name [, …]]) REFERENCES table_name (column_name [, column_name [, …]])] ©NIIT SQL/Lesson 5/Slide 35 of 52
  • 36. Creating Tables and Enforcing Data Integrity Creating Constraints (Contd.) The CHECK Constraint ® Enforces domain integrity by restricting the values to be inserted in a column Syntax [CONSTRAINT constraint name] CHECK (expression) ©NIIT SQL/Lesson 5/Slide 36 of 52
  • 37. Creating Tables and Enforcing Data Integrity Creating Constraints (Contd.) The DEFAULT Constraint ® It is used to assign a constant value to a column ® Only one DEFAULT constraint can be created for a column ® The column cannot be an IDENTITY column Syntax [CONSTRAINT constraint_name] DEFAULT (constant_expression | NULL) ©NIIT SQL/Lesson 5/Slide 37 of 52
  • 38. Creating Tables and Enforcing Data Integrity Just a Minute… Which constraint enforces domain integrity by restricting the value to be inserted in a column? ©NIIT SQL/Lesson 5/Slide 38 of 52
  • 39. Creating Tables and Enforcing Data Integrity 5.D.4 Using Constraints The Newspaper and NewsAd tables have been finalized. Create the Newspaper table with the following data integrity rules: The cNewspaperCode attribute should be the primary key The cPhone attribute should be of the format ([0-9][0-9] [0-9])[0-9][0-9][0-9][0-9][0-9][0-9][0-9]) The cCountryCode attribute should be 001 by default Modify the NewsAd table as specified below: cNewsAdNo should be the primary key cNewspaperCode should be the foreign key ©NIIT SQL/Lesson 5/Slide 39 of 52
  • 40. Creating Tables and Enforcing Data Integrity Task List Identify how to enforce data integrity Draft the statement to create a table Create the table with constraints Verify constraints by inserting data ©NIIT SQL/Lesson 5/Slide 40 of 52
  • 41. Creating Tables and Enforcing Data Integrity Identify how to enforce data integrity You can enforce data integrity by using constraints Result: For the Newspaper table: ® The phone number format can be given using the CHECK constraint ® Thecountry code can be given using the DEFAULT constraint ® Thenewspaper code can be made the primary key using the PRIMARY KEY constraint ©NIIT SQL/Lesson 5/Slide 41 of 52
  • 42. Creating Tables and Enforcing Data Integrity Identify how to enforce data integrity (Contd.) For the NewsAd table: ® ThecNewsAdNo column can be made the primary key using the PRIMARY KEY constraint ® The cNewspaperCode attribute can be made the foreign key using the FOREIGN KEY constraint ©NIIT SQL/Lesson 5/Slide 42 of 52
  • 43. Creating Tables and Enforcing Data Integrity Draft the statement to create a table Result: The command to create the Newspaper table would be as follows: CREATE TABLE Newspaper (cNewspaperCode typNewspaperCode CONSTRAINT pkNewspaperCode PRIMARY KEY, cNewspaperName char(20) NOT NULL, vRegion varchar(20), vTypeOfNewspaper varchar(20), vContactPerson varchar(35), vHOAddress varchar(35), ©NIIT SQL/Lesson 5/Slide 43 of 52
  • 44. Creating Tables and Enforcing Data Integrity Draft the statement to create a table (Contd.) cCity char(20), cState char(20), cZip char(10), cCountryCode char(3) CONSTRAINT defCountryCode DEFAULT(‘001’), cFax char(15), cPhone char(15) CONSTRAINT chkPhone CHECK(cPhone LIKE('([0-9][0-9][0-9])[0-9][0-9][0-9]-[0-9][0- 9][0-9][0-9]'))) ©NIIT SQL/Lesson 5/Slide 44 of 52
  • 45. Creating Tables and Enforcing Data Integrity Draft the statement to create a table(Contd.) The commands to modify the NewsAd table would be as follows: ALTER TABLE NewsAd ADD CONSTRAINT pkNewsAdNo PRIMARY KEY (cNewsAdNo) ALTER TABLE NewsAd ADD CONSTRAINT fkNewspaperCode FOREIGN KEY (cNewspaperCode) REFERENCES Newspaper(cNewspaperCode) ©NIIT SQL/Lesson 5/Slide 45 of 52
  • 46. Creating Tables and Enforcing Data Integrity Create the table with the constraints Action: In the Query Analyzer window, type the query Execute the commands by clicking the Execute Query button ©NIIT SQL/Lesson 5/Slide 46 of 52
  • 47. Creating Tables and Enforcing Data Integrity Verify the constraints by inserting data Verify the constraint by inserting data (into the Newspaper table) Action Test Attribute Value in the INSERT Result case statement. 1 cPhone 3445AB323 The row would not be inserted, as the telephone number contains character data 2 cPhone (212)345-2467 The row would be inserted, as this is a valid format for a telephone number 4 cCountrycode 005 The row would be inserted with 005 in the cCountryCode attribute 5 cNewspaperCode 0001 (Already The row when inserted would give an error, present in since 0001 already exists for Newspaper table) cNewspaperCode in the Newspaper table 6 cNewspaperCode 0090 (not present in The row would be inserted, as 0090 for the Newspaper cNewspaperCode does not exist in the table) Newspaper table ©NIIT SQL/Lesson 5/Slide 47 of 52
  • 48. Creating Tables and Enforcing Data Integrity Verify the constraints by inserting data (Contd.) Verify the constraint by inserting data (into the NewsAd table) Action Test Attribute Value in the INSERT Result case statement. 1 cNewsAdNo 0001 (Already The row when inserted would give an error present in the since 0001 is already present for the NewsAd table) cNewsAdNo attribute in the NewsAd table 2 cNewsAdNo 0035 (Not present in The row would be inserted, since 0035 does the NewsAd table) not exist in the NewsAd table 3 cNewspaperCode 0045 (Not present in The row,when inserted would give an error, as Newspaper table) 0045 does not exist for cNewspaperCode in the Newspaper table 4 cNewspaperCode 0001(Present in the The row would be inserted, since 0001 for Newspaper table) cNewspaperCode does not exist in the Newspaper table ©NIIT SQL/Lesson 5/Slide 48 of 52
  • 49. Creating Tables and Enforcing Data Integrity 5.P.2 Using Constraints Create the College table with the following data integrity rules: cCollegeCode should be the primary key The phone number should be of the format ([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9] cCity should be “New Orleans” by default Create the CampusRecruitment table so that it satisfies the following data integrity rules: The cCampusRecruitmentCode column should be the primary key The cCollegeCode column should be the foreign key ©NIIT SQL/Lesson 5/Slide 49 of 52
  • 50. Creating Tables and Enforcing Data Integrity Summary In this lesson, you learned that: A table is a database object used to store data A table can be created using the CREATE TABLE statement The INSERT statement is used to insert data into the table The DROP TABLE statement is used to delete the table A user-defined datatype is created by a user and is based on a system datatype A user-defined datatype is created using the sp_addtype system stored procedure ©NIIT SQL/Lesson 5/Slide 50 of 52
  • 51. Creating Tables and Enforcing Data Integrity Summary (Contd.) A user-defined datatype can be dropped using the sp_droptype system stored procedure sp_help provides information about a database object or a user- defined datatype Data integrity ensures the completeness, accuracy, and reliability of data contained in the database Data integrity can be classified as entity integrity, domain integrity, referential integrity, and user-defined integrity Data integrity can be enforced through constraints Constraints are rules that can be specified at either the table- level or the column-level ©NIIT SQL/Lesson 5/Slide 51 of 52
  • 52. Creating Tables and Enforcing Data Integrity Summary (Contd.) A constraint can be created using either the CREATE TABLE or the ALTER TABLE statements A constraint can be dropped with the ALTER TABLE statement or by dropping the table Constraints are classified as PRIMARY, FOREIGN, UNIQUE, CHECK, and DEFAULT ©NIIT SQL/Lesson 5/Slide 52 of 52