SlideShare a Scribd company logo
Manage Data in Tables

Objectives
In this lesson, you will learn to:
 Create rules
 Create defaults
 Maintain data in a table by using
     INSERT statement
     UPDATE statement
     DELETE statement
 Truncate a table




©NIIT                                 SQL/Lesson 6/Slide 1 of 50
Manage Data in Tables

6.D.1 Creating a Rule
 The zip code in the Newspaper table should be of the
  character type and should have the following pattern:
    [0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]
  An example of such a pattern is: 42482-4353
  Without changing the table structure, how can you ensure
  that you can meet this requirement?




©NIIT                                            SQL/Lesson 6/Slide 2 of 50
Manage Data in Tables

Task List
 Identify how to implement the constraint without changing
  the table structure
 Draft the statement to create a rule
 Create the rule
 Bind the rule to the column
 Verify the constraint by inserting data in the table




©NIIT                                         SQL/Lesson 6/Slide 3 of 50
Manage Data in Tables

Identify how to implement the constraint without
changing the table structure
 A rule provides a mechanism for enforcing domain integrity
  for columns or user-defined datatypes. The rule is applied to
  the column or the user-defined datatype before an INSERT
  or UPDATE statement is issued.
 Result:
     The constraint can be implemented by using rules.




©NIIT                                       SQL/Lesson 6/Slide 4 of 50
Manage Data in Tables

Draft the statement to create a rule
 The CREATE RULE Statement: Is used to create a rule
    Syntax
   CREATE RULE rule_name
   AS conditional_expression
 Action:
    The rule would be applied on the cNewspaperCode
     attribute
     The condition to be applied is:
        @ZipCode LIKE '[0-9][0-9][0-9][0-9][0-9]-
        [0-9][0-9][0-9][0-9]'
     The name of the rule would be rulZipCode

©NIIT                                     SQL/Lesson 6/Slide 5 of 50
Manage Data in Tables

Draft the statement to create a rule (Contd.)
     The rule can be created as follows:
        CREATE RULE rulZipCode
        AS
        @ZipCode LIKE '[0-9][0-9][0-9][0-9][0-9]-
        [0-9][0-9][0-9][0-9]'




©NIIT                                       SQL/Lesson 6/Slide 6 of 50
Manage Data in Tables

Create the rule
 Action:
     In the Query Analyzer window, type the query
     Press F5 to execute the query




©NIIT                                      SQL/Lesson 6/Slide 7 of 50
Manage Data in Tables

Bind the rule to the column
 Binding Rules
     A rule can be bound using the sp_bindrule system
      store procedure
     Syntax
      sp_bindrule rule_name, object_name
      [,FUTUREONLY]
 Unbinding Rules
     A rule can be unbound from a column or user-defined
      datatype using the sp_unbindrule system stored procedure
     Syntax
      sp_unbindrule object_name [, FUTUREONLY]

©NIIT                                     SQL/Lesson 6/Slide 8 of 50
Manage Data in Tables

Bind the rule to the column (Contd.)
 Action:
     In the Query Analyzer, type:
        sp_bindrule rulZipCode,'Newspaper.cZip'
     Press F5 to execute the code




©NIIT                                  SQL/Lesson 6/Slide 9 of 50
Manage Data in Tables

Verify the constraint by inserting data in the table

                                Action

        Test case cZip to be   Result
                  inserted
        1         3452345      The row would not be inserted, as
                               the zip code is not in the valid
                               format
        2         34563-5678   The row would be inserted, as the
                               zip code is in the valid format




©NIIT                                              SQL/Lesson 6/Slide 10 of 50
Manage Data in Tables

Just a Minute…
 Which system stored procedure is used to bind and unbind a
  rule?




©NIIT                                     SQL/Lesson 6/Slide 11 of 50
Manage Data in Tables

6.D.2 Creating a Default
 The data entry operator complains that for most rows, he
  has to repeatedly enter the code 001 for the cCountryCode
  attribute of the Newspaper table. You need to simplify the
  data entry task without modifying the table structure.




©NIIT                                      SQL/Lesson 6/Slide 12 of 50
Manage Data in Tables

Task List
 Identify how the data entry task can be simplified
 Draft the statement to create a default
 Create the default
 Bind the default to the column
 Verify the default by adding a row with the DEFAULT value




©NIIT                                       SQL/Lesson 6/Slide 13 of 50
Manage Data in Tables

Identify how the data entry task can be simplified
 Default
     It is a constant value assigned to a column, into which the
      user need not insert values
 Result:
     The data entry task can be simplified by using defaults




©NIIT                                        SQL/Lesson 6/Slide 14 of 50
Manage Data in Tables

Draft the statement to create a default
 The CREATE DEFAULT Statement
     Syntax
        CREATE DEFAULT default_name
        AS constant_expression
 Action:
     The default would be applied on the Newspaper table
     The column on which the default would be applied is
      cCountryCode
     The default value is '001’

©NIIT                                      SQL/Lesson 6/Slide 15 of 50
Manage Data in Tables

Draft the statement to create a default (Contd.)
     The code for creating the default can be written as
        CREATE DEFAULT defCountry
        AS '001'




©NIIT                                        SQL/Lesson 6/Slide 16 of 50
Manage Data in Tables

Create the default
 Action:
     In the Query Analyzer window, type the query
     Press F5 to execute the code




©NIIT                                      SQL/Lesson 6/Slide 17 of 50
Manage Data in Tables

Bind the default to a column
 Binding Defaults - After a DEFAULT is created, it needs to
  be bound to a column or a user-defined datatype
     Syntax
        sp_bindefault default_name, object_name [,
        FUTUREONLY]
 Unbinding Defaults - Defaults can be unbound from a
  column or user-defined datatype using the sp_unbindefault
  system stored procedure
     Syntax
        sp_unbindefault object_name [, FUTUREONLY]

©NIIT                                      SQL/Lesson 6/Slide 18 of 50
Manage Data in Tables

Bind the default to a column (Contd.)
 Action:
     In the Query Analyzer, type:
        sp_bindefault
        defCountry,'Newspaper.cCountryCode'
     Press F5 to execute the code




©NIIT                                   SQL/Lesson 6/Slide 19 of 50
Manage Data in Tables

Verify the default by adding a row with the DEFAULT
value
 Action:
     In the Query Analyzer, type:
        INSERT INTO Newspaper
        VALUES('0008','Kansas
        Today','Kansas','Genral','Robin
        Paul','1925 Shawnee Dr ','Kansas
        City','Kansas','66106-3025',DEFAULT,'(913)
        362-9529','(913)362-9515')
     Press F5 to execute


©NIIT                                SQL/Lesson 6/Slide 20 of 50
Manage Data in Tables

Maintaining Databases
 Data Manipulation Language - Data manipulation involves
  inserting, modifying, and deleting data. The Data
  Manipulation Language (DML) of Transact–SQL is used to
  manipulate data
 The three operations that you will typically perform to
  maintain a database are:
     Insert Rows
     Update Rows
     Delete Rows



©NIIT                                        SQL/Lesson 6/Slide 21 of 50
Manage Data in Tables

6.D.3 Storing Details in a Table
 Recruitment of candidates is done through recruitment
  agencies. One of the new recruitment agencies is called
  ‘Head Hunters’. The details of the Head Hunters are:
              Attributes            Data
            Agency Code    0010
            Name           Head Hunters
            Address        223 Hill Street
            City           Cleveland
            State          Ohio
            Zip            44167-5943
            Phone          (440)345-8872
            Fax            (440)345-8943
            Charge         7
            Total Paid     1000
  The above details are required to be stored in the
  RecruitmentAgencies table


©NIIT                                        SQL/Lesson 6/Slide 22 of 50
Manage Data in Tables

Task List
 Decide in which table the information is to be added
 Identify the values to be inserted
 Insert rows into the table
 Query the table to verify that data has been inserted




©NIIT                                       SQL/Lesson 6/Slide 23 of 50
Manage Data in Tables

Decide in which table the information is to be added
 Result:
     The information is to be added in the
      RecruitmentAgencies table




©NIIT                                         SQL/Lesson 6/Slide 24 of 50
Manage Data in Tables

Identify the values to be inserted
 Result:
     In the RecruitmentAgencies table, the values to be inserted
      are:
       cAgencyCode = '0010'
       cName = ‘Head Hunters ',
       vAddress = ‘223 Hill Street ',
       cCity = 'Cleveland',
       cState = ‘Ohio’
       cZip = '44167-5943',
       cPhone = '(440)345-8872',
       cFax = '(440)345-8943',
       siPercentageCharge = 7,
       mTotalPaid = 1000

 ©NIIT                                       SQL/Lesson 6/Slide 25 of 50
Manage Data in Tables

Insert rows into the table
The INSERT Statement
     You must add data to the database to maintain the latest
      information about the organization and the transactions
      performed by it. This is done using the INSERT statement
     Syntax
      INSERT [INTO]{table_name}[(column_list)]
      VALUES {DEFAULT values_list|select_statement}




©NIIT                                      SQL/Lesson 6/Slide 26 of 50
Manage Data in Tables

Insert rows into the table (Contd.)
 Action:
     In the Query Analyzer Window, type:
        INSERT INTO RecruitmentAgencies
        VALUES('0010','Head Hunters','223 Hill
        Street','Cleveland', 'Ohio','44167-
        5943','(440)345-8872','(440)345-
        8943',7,1000)
     Press F5 to execute the query




©NIIT                                       SQL/Lesson 6/Slide 27 of 50
Manage Data in Tables

Query the table to verify that data has been
inserted
 Action:
     In the Query Analyzer window, type:
        SELECT * FROM RecruitmentAgencies
     Press F5 to execute the query




©NIIT                                       SQL/Lesson 6/Slide 28 of 50
Manage Data in Tables

6.D.4 Storing Data From an Existing Table Into a new
Table
 Data for the external candidates with a rating of eight or
  above from the ExternalCandidate table is to be copied into
  a new table called PreferredCandidate. (The
  PreferredCandidate table does not exist).
  After the PreferredCandidate table has been created with the
  required values, it needs to be updated by adding rows of
  external candidates with a rating of seven.




©NIIT                                      SQL/Lesson 6/Slide 29 of 50
Manage Data in Tables

Task List
 Identify rows to be inserted
 Create the new table with the selected values
 Add more rows to the table that has been created
 Query the table to check if the rows have been added




©NIIT                                      SQL/Lesson 6/Slide 30 of 50
Manage Data in Tables

Identify rows to be inserted
 Result:
     The rows to be inserted are of those candidates with a
      rating of eight or above from the ExternalCandidate table




©NIIT                                       SQL/Lesson 6/Slide 31 of 50
Manage Data in Tables

Create the new table with the selected values
 The SELECT INTO Statement is used to copy contents of one
  table into another table
    Syntax
     SELECT columns_list
     INTO new_table_name
     FROM table_names
     WHERE conditions
 Action:
    In the Query Analyzer window, type:
     SELECT * INTO PreferredCandidate
     FROM ExternalCandidate
     WHERE cRating = 8
    Press F5 to execute the query
 ©NIIT                                   SQL/Lesson 6/Slide 32 of 50
Manage Data in Tables

Add more rows to the table that has been created
 The INSERT INTO Statement is used to add data from one
  table to another
    Syntax
     INSERT [INTO] table_name1
     SELECT column_name(s)
     FROM table_name2
     [WHERE condition]
 Action:
    In the Query Analyzer window, type:
     INSERT INTO PreferredCandidate
     SELECT * FROM ExternalCandidate
     WHERE cRating = 7
    Press F5 to execute the query
©NIIT                                   SQL/Lesson 6/Slide 33 of 50
Manage Data in Tables

Query the table to check if the rows have been added
 Action:
     In the Query Analyzer window, type:
        SELECT * FROM    PreferredCandidate
     Press F5 to execute the query




©NIIT                                       SQL/Lesson 6/Slide 34 of 50
Manage Data in Tables

Just a Minute…
 Which statements allow you to copy contents of one table
  into another table?




©NIIT                                     SQL/Lesson 6/Slide 35 of 50
Manage Data in Tables

6.D.5 Updating a Table
 The test score of Jane Schaffer who is an external candidate
  (cCandidateCode 000049) is to be increased by 2 marks,
  due to an error detected in the test correction process.




©NIIT                                      SQL/Lesson 6/Slide 36 of 50
Manage Data in Tables

Task List
 Identify attributes that have to be updated
 Identify values to be updated
 Update rows
 Query tables




©NIIT                                           SQL/Lesson 6/Slide 37 of 50
Manage Data in Tables

Identify attributes that have to be updated
 Result:
     In the ExternalCandidate table, the siTestScore attribute
      has to be updated




©NIIT                                        SQL/Lesson 6/Slide 38 of 50
Manage Data in Tables

Identify values to be updated
 Result:
     The test score of Jane Schaffer who is an external
      candidate is to be increased by 2 marks. The
      cCandidateCode of Jane is 000049




©NIIT                                       SQL/Lesson 6/Slide 39 of 50
Manage Data in Tables

Update rows
 The UPDATE Statement is used to modify data in a database
    Syntax
     UPDATE table_name
     SET column_name = value[,column_name = value]
     [FROM table_name]
     [WHERE condition]
 Action:
    In the Query Analyzer window, type:
     UPDATE ExternalCandidate
     SET siTestScore=siTestScore+2
     WHERE cCandidateCode='000049'
    Press F5 to execute the query

©NIIT                                  SQL/Lesson 6/Slide 40 of 50
Manage Data in Tables

Query Tables
 Action:
     In the Query Analyzer window, type:
        SELECT * from ExternalCandidate
        WHERE cCandidateCode = '000049'
     Press F5 to execute the query




©NIIT                                       SQL/Lesson 6/Slide 41 of 50
Manage Data in Tables

6.D.6 Deleting Data
 The ExternalCandidate table contains data on all external
  candidates who were rejected after the entrance test. Some
  of the data in this table present now is more than two years
  old. It is occupying hard disk space that can be used for
  some other purpose. This data is not required anymore. You
  are required to ensure that this old data is removed from the
  ExternalCandidate table.




©NIIT                                       SQL/Lesson 6/Slide 42 of 50
Manage Data in Tables

Task List
 Identify rows that need to be deleted
 Delete the row(s)
 Query the table




 ©NIIT                                    SQL/Lesson 6/Slide 43 of 50
Manage Data in Tables

Identify rows that need to be deleted
 Result:
     The rows containing data about the candidates who took
      the entrance test more than two years ago




©NIIT                                     SQL/Lesson 6/Slide 44 of 50
Manage Data in Tables

Delete the row(s)
 The DELETE Statement is used to delete a row from a table
    Syntax
     DELETE [FROM] table_name
     [ FROM table(s)]
     [WHERE condition]
 Action:
    In the Query Analyzer window, type:
     DELETE FROM ExternalCandidate
     WHERE dTestDate  dateadd(yy,-2,getdate())
    Press F5 to execute the query



©NIIT                                    SQL/Lesson 6/Slide 45 of 50
Manage Data in Tables

Query the table
 Action:
     In the Query Analyzer window, type:
        SELECT * FROM ExternalCandidate
        WHERE dTestDate  dateadd(yy,-2,getdate())
     Press F5 to execute




©NIIT                                       SQL/Lesson 6/Slide 46 of 50
Manage Data in Tables

Just a Minute…
 Which statement allows the modification of data in a
  database?




©NIIT                                      SQL/Lesson 6/Slide 47 of 50
Manage Data in Tables

Truncating a Table
 The TRUNCATE TABLE statement
     Is used to remove rows from a table
     Is identical (functionally) to the DELETE statement
     Is faster than DELETE statement
     Does not fire a trigger
        ® Syntax

         TRUNCATE TABLE table_name




©NIIT                                        SQL/Lesson 6/Slide 48 of 50
Manage Data in Tables

Summary
In this lesson, you learned that:
 Rules and defaults are objects that are bound to columns or
  user-defined datatypes for specifying the restricted values
  and default values respectively
 A rule is created using the CREATE RULE statement, and
  bound to the column and user-defined datatypes using the
  sp_bindrule procedure
 A rule is unbound using the sp_unbindrule procedure
 A default is created using the CREATE DEFAULT statement,
  and bound to the column and user-defined datatypes using
  the sp_bindefault procedure

©NIIT                                      SQL/Lesson 6/Slide 49 of 50
Manage Data in Tables

Summary (Contd.)
 A default is unbound using the sp_unbindefault procedure
 Data is modified in the database to keep the data up-to-date
 The INSERT statement is used to insert rows into tables
 You can copy contents of one table into another table by
  using the SELECT INTO command
 SQL Server provides a row update statement called
  UPDATE to modify values within tables
 You can delete a row from a table by using the DELETE
  statement
 You use the TRUNCATE TABLE statement to remove all the
  rows from a table
©NIIT                                      SQL/Lesson 6/Slide 50 of 50

More Related Content

ODP
Oracle SQL Advanced
PPS
Sql xp 04
PPS
Sql xp 07
PPS
Sql xp 03
PPS
Sql xp 01
PPS
Sql xp 02
PPS
Sql xp 05
PDF
Sql ch 4
Oracle SQL Advanced
Sql xp 04
Sql xp 07
Sql xp 03
Sql xp 01
Sql xp 02
Sql xp 05
Sql ch 4

What's hot (20)

DOCX
Teradata imp
PDF
Application sql issues_and_tuning
PDF
Tufte Sample Bi Portfolio
PDF
Sq lite module8
PDF
Sql wksht-2
DOCX
Assg2 b 19121033-converted
PDF
Partitioning tables and indexing them
PPTX
Partitioning on Oracle 12c - What changed on the most important Oracle feature
PPT
Sql views
PPTX
Sql basics
PDF
Partitioning Tables and Indexing Them --- Article
PPTX
SQL(database)
ODP
BIS06 Physical Database Models
PDF
Oracle SQL Part 2
PDF
Oracle SQL Part 3
PDF
Sql ch 5
PPT
Sql basic best-course-in-mumbai
PPTX
SQL for ETL Testing
PPTX
MYSQL join
Teradata imp
Application sql issues_and_tuning
Tufte Sample Bi Portfolio
Sq lite module8
Sql wksht-2
Assg2 b 19121033-converted
Partitioning tables and indexing them
Partitioning on Oracle 12c - What changed on the most important Oracle feature
Sql views
Sql basics
Partitioning Tables and Indexing Them --- Article
SQL(database)
BIS06 Physical Database Models
Oracle SQL Part 2
Oracle SQL Part 3
Sql ch 5
Sql basic best-course-in-mumbai
SQL for ETL Testing
MYSQL join
Ad

Similar to Sql xp 06 (20)

PPTX
Database COMPLETE
DOC
Oracle SQL AND PL/SQL
PPT
PPS
06 qmds2005 session08
PDF
Part2 (1 Examen)
PPTX
2. DBMS Experiment - Lab 2 Made in SQL Used
PPTX
zekeLabs sql-slides
PPT
Ms Access ppt
PDF
CS3481_Database Management Laboratory .pdf
PPTX
data base programming chapter2 29 slides
PPT
PPT
ODP
BIS06 Physical Database Models
PPS
05 qmds2005 session07
PDF
Part_2_Operations_On_Table_DBMS.pdf made by saiket sir
PDF
Part1 (2 Examene)
PPTX
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
PPT
Revision sql te it new syllabus
PDF
DBMS 4 | MySQL - DDL & DML Commands
PPT
Mysql rab2-student
Database COMPLETE
Oracle SQL AND PL/SQL
06 qmds2005 session08
Part2 (1 Examen)
2. DBMS Experiment - Lab 2 Made in SQL Used
zekeLabs sql-slides
Ms Access ppt
CS3481_Database Management Laboratory .pdf
data base programming chapter2 29 slides
BIS06 Physical Database Models
05 qmds2005 session07
Part_2_Operations_On_Table_DBMS.pdf made by saiket sir
Part1 (2 Examene)
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
Revision sql te it new syllabus
DBMS 4 | MySQL - DDL & DML Commands
Mysql rab2-student
Ad

More from Niit Care (20)

PPS
Ajs 1 b
PPS
Ajs 4 b
PPS
Ajs 4 a
PPS
Ajs 4 c
PPS
Ajs 3 b
PPS
Ajs 3 a
PPS
Ajs 3 c
PPS
Ajs 2 b
PPS
Ajs 2 a
PPS
Ajs 2 c
PPS
Ajs 1 a
PPS
Ajs 1 c
PPS
Dacj 4 2-c
PPS
Dacj 4 2-b
PPS
Dacj 4 2-a
PPS
Dacj 4 1-c
PPS
Dacj 4 1-b
PPS
Dacj 4 1-a
PPS
Dacj 1-2 b
PPS
Dacj 1-3 c
Ajs 1 b
Ajs 4 b
Ajs 4 a
Ajs 4 c
Ajs 3 b
Ajs 3 a
Ajs 3 c
Ajs 2 b
Ajs 2 a
Ajs 2 c
Ajs 1 a
Ajs 1 c
Dacj 4 2-c
Dacj 4 2-b
Dacj 4 2-a
Dacj 4 1-c
Dacj 4 1-b
Dacj 4 1-a
Dacj 1-2 b
Dacj 1-3 c

Recently uploaded (20)

PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Encapsulation theory and applications.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPT
Teaching material agriculture food technology
PPTX
Cloud computing and distributed systems.
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Reach Out and Touch Someone: Haptics and Empathic Computing
Per capita expenditure prediction using model stacking based on satellite ima...
MIND Revenue Release Quarter 2 2025 Press Release
Spectral efficient network and resource selection model in 5G networks
Dropbox Q2 2025 Financial Results & Investor Presentation
20250228 LYD VKU AI Blended-Learning.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Review of recent advances in non-invasive hemoglobin estimation
Encapsulation theory and applications.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Teaching material agriculture food technology
Cloud computing and distributed systems.
The Rise and Fall of 3GPP – Time for a Sabbatical?
Digital-Transformation-Roadmap-for-Companies.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm

Sql xp 06

  • 1. Manage Data in Tables Objectives In this lesson, you will learn to: Create rules Create defaults Maintain data in a table by using INSERT statement UPDATE statement DELETE statement Truncate a table ©NIIT SQL/Lesson 6/Slide 1 of 50
  • 2. Manage Data in Tables 6.D.1 Creating a Rule The zip code in the Newspaper table should be of the character type and should have the following pattern: [0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9] An example of such a pattern is: 42482-4353 Without changing the table structure, how can you ensure that you can meet this requirement? ©NIIT SQL/Lesson 6/Slide 2 of 50
  • 3. Manage Data in Tables Task List Identify how to implement the constraint without changing the table structure Draft the statement to create a rule Create the rule Bind the rule to the column Verify the constraint by inserting data in the table ©NIIT SQL/Lesson 6/Slide 3 of 50
  • 4. Manage Data in Tables Identify how to implement the constraint without changing the table structure A rule provides a mechanism for enforcing domain integrity for columns or user-defined datatypes. The rule is applied to the column or the user-defined datatype before an INSERT or UPDATE statement is issued. Result: The constraint can be implemented by using rules. ©NIIT SQL/Lesson 6/Slide 4 of 50
  • 5. Manage Data in Tables Draft the statement to create a rule The CREATE RULE Statement: Is used to create a rule Syntax CREATE RULE rule_name AS conditional_expression Action: The rule would be applied on the cNewspaperCode attribute The condition to be applied is: @ZipCode LIKE '[0-9][0-9][0-9][0-9][0-9]- [0-9][0-9][0-9][0-9]' The name of the rule would be rulZipCode ©NIIT SQL/Lesson 6/Slide 5 of 50
  • 6. Manage Data in Tables Draft the statement to create a rule (Contd.) The rule can be created as follows: CREATE RULE rulZipCode AS @ZipCode LIKE '[0-9][0-9][0-9][0-9][0-9]- [0-9][0-9][0-9][0-9]' ©NIIT SQL/Lesson 6/Slide 6 of 50
  • 7. Manage Data in Tables Create the rule Action: In the Query Analyzer window, type the query Press F5 to execute the query ©NIIT SQL/Lesson 6/Slide 7 of 50
  • 8. Manage Data in Tables Bind the rule to the column Binding Rules A rule can be bound using the sp_bindrule system store procedure Syntax sp_bindrule rule_name, object_name [,FUTUREONLY] Unbinding Rules A rule can be unbound from a column or user-defined datatype using the sp_unbindrule system stored procedure Syntax sp_unbindrule object_name [, FUTUREONLY] ©NIIT SQL/Lesson 6/Slide 8 of 50
  • 9. Manage Data in Tables Bind the rule to the column (Contd.) Action: In the Query Analyzer, type: sp_bindrule rulZipCode,'Newspaper.cZip' Press F5 to execute the code ©NIIT SQL/Lesson 6/Slide 9 of 50
  • 10. Manage Data in Tables Verify the constraint by inserting data in the table Action Test case cZip to be Result inserted 1 3452345 The row would not be inserted, as the zip code is not in the valid format 2 34563-5678 The row would be inserted, as the zip code is in the valid format ©NIIT SQL/Lesson 6/Slide 10 of 50
  • 11. Manage Data in Tables Just a Minute… Which system stored procedure is used to bind and unbind a rule? ©NIIT SQL/Lesson 6/Slide 11 of 50
  • 12. Manage Data in Tables 6.D.2 Creating a Default The data entry operator complains that for most rows, he has to repeatedly enter the code 001 for the cCountryCode attribute of the Newspaper table. You need to simplify the data entry task without modifying the table structure. ©NIIT SQL/Lesson 6/Slide 12 of 50
  • 13. Manage Data in Tables Task List Identify how the data entry task can be simplified Draft the statement to create a default Create the default Bind the default to the column Verify the default by adding a row with the DEFAULT value ©NIIT SQL/Lesson 6/Slide 13 of 50
  • 14. Manage Data in Tables Identify how the data entry task can be simplified Default It is a constant value assigned to a column, into which the user need not insert values Result: The data entry task can be simplified by using defaults ©NIIT SQL/Lesson 6/Slide 14 of 50
  • 15. Manage Data in Tables Draft the statement to create a default The CREATE DEFAULT Statement Syntax CREATE DEFAULT default_name AS constant_expression Action: The default would be applied on the Newspaper table The column on which the default would be applied is cCountryCode The default value is '001’ ©NIIT SQL/Lesson 6/Slide 15 of 50
  • 16. Manage Data in Tables Draft the statement to create a default (Contd.) The code for creating the default can be written as CREATE DEFAULT defCountry AS '001' ©NIIT SQL/Lesson 6/Slide 16 of 50
  • 17. Manage Data in Tables Create the default Action: In the Query Analyzer window, type the query Press F5 to execute the code ©NIIT SQL/Lesson 6/Slide 17 of 50
  • 18. Manage Data in Tables Bind the default to a column Binding Defaults - After a DEFAULT is created, it needs to be bound to a column or a user-defined datatype Syntax sp_bindefault default_name, object_name [, FUTUREONLY] Unbinding Defaults - Defaults can be unbound from a column or user-defined datatype using the sp_unbindefault system stored procedure Syntax sp_unbindefault object_name [, FUTUREONLY] ©NIIT SQL/Lesson 6/Slide 18 of 50
  • 19. Manage Data in Tables Bind the default to a column (Contd.) Action: In the Query Analyzer, type: sp_bindefault defCountry,'Newspaper.cCountryCode' Press F5 to execute the code ©NIIT SQL/Lesson 6/Slide 19 of 50
  • 20. Manage Data in Tables Verify the default by adding a row with the DEFAULT value Action: In the Query Analyzer, type: INSERT INTO Newspaper VALUES('0008','Kansas Today','Kansas','Genral','Robin Paul','1925 Shawnee Dr ','Kansas City','Kansas','66106-3025',DEFAULT,'(913) 362-9529','(913)362-9515') Press F5 to execute ©NIIT SQL/Lesson 6/Slide 20 of 50
  • 21. Manage Data in Tables Maintaining Databases Data Manipulation Language - Data manipulation involves inserting, modifying, and deleting data. The Data Manipulation Language (DML) of Transact–SQL is used to manipulate data The three operations that you will typically perform to maintain a database are: Insert Rows Update Rows Delete Rows ©NIIT SQL/Lesson 6/Slide 21 of 50
  • 22. Manage Data in Tables 6.D.3 Storing Details in a Table Recruitment of candidates is done through recruitment agencies. One of the new recruitment agencies is called ‘Head Hunters’. The details of the Head Hunters are: Attributes Data Agency Code 0010 Name Head Hunters Address 223 Hill Street City Cleveland State Ohio Zip 44167-5943 Phone (440)345-8872 Fax (440)345-8943 Charge 7 Total Paid 1000 The above details are required to be stored in the RecruitmentAgencies table ©NIIT SQL/Lesson 6/Slide 22 of 50
  • 23. Manage Data in Tables Task List Decide in which table the information is to be added Identify the values to be inserted Insert rows into the table Query the table to verify that data has been inserted ©NIIT SQL/Lesson 6/Slide 23 of 50
  • 24. Manage Data in Tables Decide in which table the information is to be added Result: The information is to be added in the RecruitmentAgencies table ©NIIT SQL/Lesson 6/Slide 24 of 50
  • 25. Manage Data in Tables Identify the values to be inserted Result: In the RecruitmentAgencies table, the values to be inserted are: cAgencyCode = '0010' cName = ‘Head Hunters ', vAddress = ‘223 Hill Street ', cCity = 'Cleveland', cState = ‘Ohio’ cZip = '44167-5943', cPhone = '(440)345-8872', cFax = '(440)345-8943', siPercentageCharge = 7, mTotalPaid = 1000 ©NIIT SQL/Lesson 6/Slide 25 of 50
  • 26. Manage Data in Tables Insert rows into the table The INSERT Statement You must add data to the database to maintain the latest information about the organization and the transactions performed by it. This is done using the INSERT statement Syntax INSERT [INTO]{table_name}[(column_list)] VALUES {DEFAULT values_list|select_statement} ©NIIT SQL/Lesson 6/Slide 26 of 50
  • 27. Manage Data in Tables Insert rows into the table (Contd.) Action: In the Query Analyzer Window, type: INSERT INTO RecruitmentAgencies VALUES('0010','Head Hunters','223 Hill Street','Cleveland', 'Ohio','44167- 5943','(440)345-8872','(440)345- 8943',7,1000) Press F5 to execute the query ©NIIT SQL/Lesson 6/Slide 27 of 50
  • 28. Manage Data in Tables Query the table to verify that data has been inserted Action: In the Query Analyzer window, type: SELECT * FROM RecruitmentAgencies Press F5 to execute the query ©NIIT SQL/Lesson 6/Slide 28 of 50
  • 29. Manage Data in Tables 6.D.4 Storing Data From an Existing Table Into a new Table Data for the external candidates with a rating of eight or above from the ExternalCandidate table is to be copied into a new table called PreferredCandidate. (The PreferredCandidate table does not exist). After the PreferredCandidate table has been created with the required values, it needs to be updated by adding rows of external candidates with a rating of seven. ©NIIT SQL/Lesson 6/Slide 29 of 50
  • 30. Manage Data in Tables Task List Identify rows to be inserted Create the new table with the selected values Add more rows to the table that has been created Query the table to check if the rows have been added ©NIIT SQL/Lesson 6/Slide 30 of 50
  • 31. Manage Data in Tables Identify rows to be inserted Result: The rows to be inserted are of those candidates with a rating of eight or above from the ExternalCandidate table ©NIIT SQL/Lesson 6/Slide 31 of 50
  • 32. Manage Data in Tables Create the new table with the selected values The SELECT INTO Statement is used to copy contents of one table into another table Syntax SELECT columns_list INTO new_table_name FROM table_names WHERE conditions Action: In the Query Analyzer window, type: SELECT * INTO PreferredCandidate FROM ExternalCandidate WHERE cRating = 8 Press F5 to execute the query ©NIIT SQL/Lesson 6/Slide 32 of 50
  • 33. Manage Data in Tables Add more rows to the table that has been created The INSERT INTO Statement is used to add data from one table to another Syntax INSERT [INTO] table_name1 SELECT column_name(s) FROM table_name2 [WHERE condition] Action: In the Query Analyzer window, type: INSERT INTO PreferredCandidate SELECT * FROM ExternalCandidate WHERE cRating = 7 Press F5 to execute the query ©NIIT SQL/Lesson 6/Slide 33 of 50
  • 34. Manage Data in Tables Query the table to check if the rows have been added Action: In the Query Analyzer window, type: SELECT * FROM PreferredCandidate Press F5 to execute the query ©NIIT SQL/Lesson 6/Slide 34 of 50
  • 35. Manage Data in Tables Just a Minute… Which statements allow you to copy contents of one table into another table? ©NIIT SQL/Lesson 6/Slide 35 of 50
  • 36. Manage Data in Tables 6.D.5 Updating a Table The test score of Jane Schaffer who is an external candidate (cCandidateCode 000049) is to be increased by 2 marks, due to an error detected in the test correction process. ©NIIT SQL/Lesson 6/Slide 36 of 50
  • 37. Manage Data in Tables Task List Identify attributes that have to be updated Identify values to be updated Update rows Query tables ©NIIT SQL/Lesson 6/Slide 37 of 50
  • 38. Manage Data in Tables Identify attributes that have to be updated Result: In the ExternalCandidate table, the siTestScore attribute has to be updated ©NIIT SQL/Lesson 6/Slide 38 of 50
  • 39. Manage Data in Tables Identify values to be updated Result: The test score of Jane Schaffer who is an external candidate is to be increased by 2 marks. The cCandidateCode of Jane is 000049 ©NIIT SQL/Lesson 6/Slide 39 of 50
  • 40. Manage Data in Tables Update rows The UPDATE Statement is used to modify data in a database Syntax UPDATE table_name SET column_name = value[,column_name = value] [FROM table_name] [WHERE condition] Action: In the Query Analyzer window, type: UPDATE ExternalCandidate SET siTestScore=siTestScore+2 WHERE cCandidateCode='000049' Press F5 to execute the query ©NIIT SQL/Lesson 6/Slide 40 of 50
  • 41. Manage Data in Tables Query Tables Action: In the Query Analyzer window, type: SELECT * from ExternalCandidate WHERE cCandidateCode = '000049' Press F5 to execute the query ©NIIT SQL/Lesson 6/Slide 41 of 50
  • 42. Manage Data in Tables 6.D.6 Deleting Data The ExternalCandidate table contains data on all external candidates who were rejected after the entrance test. Some of the data in this table present now is more than two years old. It is occupying hard disk space that can be used for some other purpose. This data is not required anymore. You are required to ensure that this old data is removed from the ExternalCandidate table. ©NIIT SQL/Lesson 6/Slide 42 of 50
  • 43. Manage Data in Tables Task List Identify rows that need to be deleted Delete the row(s) Query the table ©NIIT SQL/Lesson 6/Slide 43 of 50
  • 44. Manage Data in Tables Identify rows that need to be deleted Result: The rows containing data about the candidates who took the entrance test more than two years ago ©NIIT SQL/Lesson 6/Slide 44 of 50
  • 45. Manage Data in Tables Delete the row(s) The DELETE Statement is used to delete a row from a table Syntax DELETE [FROM] table_name [ FROM table(s)] [WHERE condition] Action: In the Query Analyzer window, type: DELETE FROM ExternalCandidate WHERE dTestDate dateadd(yy,-2,getdate()) Press F5 to execute the query ©NIIT SQL/Lesson 6/Slide 45 of 50
  • 46. Manage Data in Tables Query the table Action: In the Query Analyzer window, type: SELECT * FROM ExternalCandidate WHERE dTestDate dateadd(yy,-2,getdate()) Press F5 to execute ©NIIT SQL/Lesson 6/Slide 46 of 50
  • 47. Manage Data in Tables Just a Minute… Which statement allows the modification of data in a database? ©NIIT SQL/Lesson 6/Slide 47 of 50
  • 48. Manage Data in Tables Truncating a Table The TRUNCATE TABLE statement Is used to remove rows from a table Is identical (functionally) to the DELETE statement Is faster than DELETE statement Does not fire a trigger ® Syntax TRUNCATE TABLE table_name ©NIIT SQL/Lesson 6/Slide 48 of 50
  • 49. Manage Data in Tables Summary In this lesson, you learned that: Rules and defaults are objects that are bound to columns or user-defined datatypes for specifying the restricted values and default values respectively A rule is created using the CREATE RULE statement, and bound to the column and user-defined datatypes using the sp_bindrule procedure A rule is unbound using the sp_unbindrule procedure A default is created using the CREATE DEFAULT statement, and bound to the column and user-defined datatypes using the sp_bindefault procedure ©NIIT SQL/Lesson 6/Slide 49 of 50
  • 50. Manage Data in Tables Summary (Contd.) A default is unbound using the sp_unbindefault procedure Data is modified in the database to keep the data up-to-date The INSERT statement is used to insert rows into tables You can copy contents of one table into another table by using the SELECT INTO command SQL Server provides a row update statement called UPDATE to modify values within tables You can delete a row from a table by using the DELETE statement You use the TRUNCATE TABLE statement to remove all the rows from a table ©NIIT SQL/Lesson 6/Slide 50 of 50