SlideShare a Scribd company logo
1 of 33
Querying and Managing Data Using SQL Server 2005
Objectives


               In this session, you will learn to:
                  Manage databases
                  Manage tables




    Ver. 1.0                        Session 7        Slide 1 of 33
Querying and Managing Data Using SQL Server 2005
Identifying the System Databases in SQL Server 2005


               SQL Server 2005 contains the following system databases:
               – master: The master database that records all the
                 server-specific configuration information.
               – tempdb: The temporary database that holds all temporary
                 tables and stored procedures.
               – model: The model database that acts as a template or
                 prototype for the new databases.
               – msdb: The database that handles the task of scheduling,
                 exception handling, etc.
               – Resource: Read-only database that contains all the system
                 objects included in the SQL Server 2005.




    Ver. 1.0                      Session 7                          Slide 2 of 33
Querying and Managing Data Using SQL Server 2005
Just a minute


               What is the utility of the model database?




               Answer:
                   The model database acts as a template or a prototype
                   for the new databases.



    Ver. 1.0                       Session 7                              Slide 3 of 33
Querying and Managing Data Using SQL Server 2005
Creating a User-Defined Database


               User-defined database:
                  Is stored as a set of files. These files include:
                   • Primary data file
                   • Secondary data file
                   • Transaction log file
                  Syntax:
                   CREATE DATABASE database_name
                   [ ON [ PRIMARY ] [ < filespec >]]
                   [ LOG ON { < filespec > [ ,...n ] } ]
                   < filespec > ::=
                   ( [ NAME = logical_file_name , ]
                   FILENAME = 'os_file_name'
                   [ , SIZE = size ]
                   [ , MAXSIZE = { max_size | UNLIMITED } ]
                   [ , FILEGROWTH = growth_increment ] ) [,...n]
               Let’s see how…
    Ver. 1.0                         Session 7                        Slide 4 of 33
Querying and Managing Data Using SQL Server 2005
Just a minute


               Which statement is used to create a database?




               Answer:
                  The CREATE DATABASE statement




    Ver. 1.0                     Session 7                     Slide 5 of 33
Querying and Managing Data Using SQL Server 2005
Creating a Table


                Table:
                   Is created to store data
                   Is created by using the CREATE TABLE statement
                   Syntax:
                     CREATE TABLE
                     [ database_name . [ schema_name ] .]
                   table_name
                     ( { <column_definition> |
                     <computed_column_definition> }
                     [ <table_constraint> ] [ ,...n ] )
                     [ ON { partition_scheme_name (
                     partition_column_name ) | filegroup
                     | "default" } ]
                     [ { TEXTIMAGE_ON { filegroup | "default" } ]
                     [ ; ]
     Ver. 1.0                   Session 7                   Slide 6 of 33
Querying and Managing Data Using SQL Server 2005
Creating a Table (Contd.)


                Example:
                   Create an EmployeeLeave table in the HumanResources
                   schema with the following details:
                   Columns          Data Type        Checks

                   EmployeeID       int              NOT NULL

                   LeaveStartDate   date             NOT NULL

                   LeaveEndDate     date             NOT NULL

                   LeaveReason      varchar(100)     NOT NULL

                   LeaveType        char(2)          NOT NULL


                Let’s see how…




     Ver. 1.0                       Session 7                       Slide 7 of 33
Querying and Managing Data Using SQL Server 2005
Implementing Data Integrity


               Avoids data redundancy
               Ensures that the data in a database is accurate, consistent,
               and reliable
               Is broadly classified into the following categories:
                  Entity integrity: Ensures that each row can be uniquely
                  identified by an attribute called the primary key
                  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 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



    Ver. 1.0                        Session 7                             Slide 8 of 33
Querying and Managing Data Using SQL Server 2005
Implementing Data Integrity (Contd.)


               You can maintain data integrity by:
                  Applying constraints
                  Applying rules
                  Using user-defined types




    Ver. 1.0                       Session 7         Slide 9 of 33
Querying and Managing Data Using SQL Server 2005
Implementing Data Integrity (Contd.)


               Constraints can be applied:
                  By using CREATE TABLE statement
                  By using ALTER TABLE statement
                  Syntax:
                   CREATE TABLE table_name
                   (
                   column_name CONSTRAINT constraint_name
                   constraint_type [,CONSTRAINT constraint_name
                   constraint_type]
                   )




    Ver. 1.0                      Session 7               Slide 10 of 33
Querying and Managing Data Using SQL Server 2005
Implementing Data Integrity (Contd.)


               Constraints are of the following types:
                  Primary key constraint
                  Unique constraint
                  Foreign key constraint
                  Check constraint
                  Default constraint




    Ver. 1.0                       Session 7             Slide 11 of 33
Querying and Managing Data Using SQL Server 2005
Implementing Data Integrity (Contd.)


               Primary key constraint:
                  Is defined on a column or a set of columns whose values
                  uniquely identify all the rows in a table
                  Does not allow NULL values in the column
                  Ensures entity integrity
                  Syntax:
                    CREATE TABLE table_name
                    (
                    col_name [CONSTRAINT constraint_name PRIMARY
                    KEY [CLUSTERED|NONCLUSTERED]
                    col_name [, col_name [, col_name [, …]]]
                    )




    Ver. 1.0                      Session 7                        Slide 12 of 33
Querying and Managing Data Using SQL Server 2005
Implementing Data Integrity (Contd.)


               Unique constraint:
                  Is defined to enforce uniqueness in non-primary key columns
                  Allows one NULL value in the column
                  Syntax:
                    CREATE TABLE table_name
                    (
                    col_name [CONSTRAINT constraint_name UNIQUE
                    [CLUSTERED | NONCLUSTERED]
                    (col_name [, col_name [, col_name [, …]]])
                    col_name [, col_name [, col_name [, …]]]
                    )




    Ver. 1.0                        Session 7                          Slide 13 of 33
Querying and Managing Data Using SQL Server 2005
Implementing Data Integrity (Contd.)


               Foreign key constraint:
                  Is defined to remove the inconsistency in two tables when the
                  data in one table depends on the data in another table
                  Associates one or more columns (the foreign key) of a table
                  with an identical set of columns (a primary key column) in
                  another table




    Ver. 1.0                       Session 7                            Slide 14 of 33
Querying and Managing Data Using SQL Server 2005
Implementing Data Integrity (Contd.)


                  Syntax:
                   CREATE TABLE table_name
                   (
                   col_name [CONSTRAINT constraint_name FOREIGN
                   KEY (col_name [,
                   col_name [, …]])
                   REFERENCES table_name (column_name [,
                   column_name [, …]])]
                   (col_name [, col_name [, col_name [, …]]])
                   col_name [, col_name [, col_name [, …]]]
                   )
               Let’s see how…



    Ver. 1.0                    Session 7                Slide 15 of 33
Querying and Managing Data Using SQL Server 2005
Implementing Data Integrity (Contd.)


               Check constraint:
                  Is defined to enforce domain integrity by restricting the values
                  to be inserted in a column
                  Can be defined on multiple columns
                  Is specified by using the following keywords:
                      IN
                      LIKE
                      BETWEEN




    Ver. 1.0                        Session 7                              Slide 16 of 33
Querying and Managing Data Using SQL Server 2005
Implementing Data Integrity (Contd.)


                  Syntax:
                   CREATE TABLE table_name
                   (
                   col_name [CONSTRAINT constraint_name] CHECK
                   (expression)
                   (col_name [, col_name [, …]])
                   .
                   )
               Let’s see how…




    Ver. 1.0                    Session 7                Slide 17 of 33
Querying and Managing Data Using SQL Server 2005
Implementing Data Integrity (Contd.)


               Default constraint:
                – Is defined to assign a constant value to a column
                – Syntax:
                    CREATE TABLE table_name
                    (
                    col_name [CONSTRAINT constraint_name]
                    DEFAULT (constant_expression | NULL)
                    (col_name [, col_name [, …]])
                    .
                    )
               Let’s see how…




    Ver. 1.0                         Session 7                        Slide 18 of 33
Querying and Managing Data Using SQL Server 2005
Just a minute


               Which keyword is used to specify a check constraint?




               Answer:
                  A check constraint can be specified by using the LIKE,
                  IN, and BETWEEN keywords.



    Ver. 1.0                       Session 7                           Slide 19 of 33
Querying and Managing Data Using SQL Server 2005
Implementing Data Integrity (Contd.)


               Rules:
                  Help in enforcing domain integrity for columns or user-defined
                  data types
                  Can be specified to the column or the user-defined data type
                  before an INSERT or UPDATE statement is issued
                  Are used to implement business-related restrictions or
                  limitations
                  Can be created by using the CREATE RULE statement
                  Syntax:
                    CREATE RULE rule_name AS
                    conditional_expression
                  Can be bound by using the sp_bindrule stored procedure
               Let’s see how…



    Ver. 1.0                        Session 7                            Slide 20 of 33
Querying and Managing Data Using SQL Server 2005
Implementing Data Integrity (Contd.)


               User-defined data types:
                  Are custom data types defined by the users with a custom
                  name
                  Can be created by using the CREATE TYPE statement
                  Syntax:
                   CREATE TYPE [ schema_name. ] type_name { FROM
                   base_type [ ( precision
                   [ , scale ] ) ] [ NULL | NOT NULL ] } [ ; ]
               Let’s see how…




    Ver. 1.0                      Session 7                       Slide 21 of 33
Querying and Managing Data Using SQL Server 2005
Just a minute


               You want to create a rule, rule1, which allows the user to
               enter any of the four values: Tea, Coffee, Soup, or Miranda
               in a column. Which command should you execute?




               Answer:
                   CREATE RULE rule1 AS @TypeRule IN ('Tea',
                   'Coffee', 'Soup', 'Miranda')



    Ver. 1.0                      Session 7                        Slide 22 of 33
Querying and Managing Data Using SQL Server 2005
Creating a Partitioned Table


               Flash presentation: Partitioning Tables
               Partitioned table:
                  Is created when the table contains voluminous data
                  Is created to separate data into multiple physical locations
                  based on a range of values for a specific column
                  Helps in improving query performance
                  Can be created by:
                      Creating a partition function
                      Creating a partition scheme
                      Creating a table by using the partition scheme




    Ver. 1.0                         Session 7                            Slide 23 of 33
Querying and Managing Data Using SQL Server 2005
Modifying a Table


               Modify a table:
                  When there is a requirement to add or remove columns and
                  constraints
                  Using the ALTER TABLE statement
                  Syntax:
                   ALTER TABLE [ database_name . [ schema_name ]
                   . | schema_name . ]
                   table_name
                   { ALTER COLUMN column_name
                   { [ NULL | NOT NULL ]
                   } | [ WITH { CHECK | NOCHECK } ] ADD COLUMN
                   <column_definition>
                   { ADD CONSTRAINT constraint_name
                   constraint_type
               Let’s see how…

    Ver. 1.0                      Session 7                       Slide 24 of 33
Querying and Managing Data Using SQL Server 2005
Just a minute


               You are managing a large table. You want to improve the
               performance of the table and want the table to be more
               manageable. Which strategy can you use?




               Answer:
                  Partition the table




    Ver. 1.0                        Session 7                    Slide 25 of 33
Querying and Managing Data Using SQL Server 2005
Dropping a Table


               Drop a table:
                  When a table is not required
                  Using the DROP TABLE statement
                  Syntax:
                   DROP TABLE [ database_name . [ schema_name ]
                   . ] table_name
               Let’s see how…




    Ver. 1.0                    Session 7                 Slide 26 of 33
Querying and Managing Data Using SQL Server 2005
Demo: Managing Tables


               Problem Statement:
                  The management of AdventureWorks, Inc. has decided to
                  provide travel and medical reimbursements to the employees.
                  They want to store the details of these reimbursements in the
                  database. For this, you need to create a database table,
                  EmployeeReimbursements. The details of the tables are
                  shown in the following table.
                   Columns        Data Type and Size   Constraints

                   RimID          int                  Primary key

                   EmployeeID     int                  Foreign Key references the EmployeeID of
                                                       the Employee Table, NOT NULL
                   Amount         money                Amount>0

                   RimType        varchar(20)          RimType should be Medical, Cash, or
                                                       Local
                   Pending_with   varchar(30)          NOT NULL


                  How will you create the table?

    Ver. 1.0                              Session 7                                       Slide 27 of 33
Querying and Managing Data Using SQL Server 2005
Demo: Managing Tables (Contd.)


                Solution:
                   To solve the preceding problem, you need to perform the
                   following tasks:
                     1. Write the query to create a table.
                     2. Execute the statement to verify the result.




     Ver. 1.0                          Session 7                        Slide 28 of 33
Querying and Managing Data Using SQL Server 2005
Summary


              In this session, you learned that:
                 A database is a repository of information that contains data in
                 an organized way.
                 The master database records all the server-specific
                 configuration information, including authorized users,
                 databases, system configuration settings, and remote servers.
                 The tempdb database is a temporary database that holds all
                 temporary tables and stored procedures.
                 The model database acts as a template or a prototype for the
                 new databases.
                 The msdb database supports the SQL Server Agent. The SQL
                 Server Agent includes features that schedule periodic activities
                 of the SQL Server.
                 The Resource database is a read-only database that contains
                 all the system objects that are included with SQL Server 2005.


   Ver. 1.0                        Session 7                            Slide 29 of 33
Querying and Managing Data Using SQL Server 2005
Summary (Contd.)


                 The user-defined databases are created by the users to store
                 data for client-server applications.
                 A database consists of the following types of files:
                   • Primary data file
                   • Secondary data file
                   • Transaction log file
               – A database must consist of a primary data file and one
                 transaction log file.
               – The CREATE DATABASE statement is used to create a
                 database, which also includes determining the name of the
                 database, the size of the database, and the files used to store
                 data in the database.
               – Tables are used to store data.




    Ver. 1.0                         Session 7                           Slide 30 of 33
Querying and Managing Data Using SQL Server 2005
Summary (Contd.)


               Tables are used to store data.
               The CREATE TABLE statement is used to create a table.
               Data integrity is enforced to keep the data in a database
               accurate, consistent, and reliable. It is broadly classified into
               the following categories:
                • Entity integrity: Ensures that each row can be uniquely identified
                  by an attribute called the primary key.
                • 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 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.




    Ver. 1.0                      Session 7                                Slide 31 of 33
Querying and Managing Data Using SQL Server 2005
Summary (Contd.)


               Constraints define rules that must be followed to maintain
               consistency and correctness of data.
               A primary key constraint is defined on a column or a set of
               columns whose values uniquely identify rows in a table.
               The unique constraint is used to enforce uniqueness on non-
               primary key columns.
               A foreign key constraint associates one or more columns of a
               table (the foreign key) with an identical set of columns on
               which a primary key constraint has been defined (a primary
               key column in another table).
               A check constraint enforces domain integrity by restricting the
               values to be inserted in a column. The IN, LIKE, and
               BETWEEN keywords are used to define the check constraint.




    Ver. 1.0                     Session 7                             Slide 32 of 33
Querying and Managing Data Using SQL Server 2005
Summary (Contd.)


               A default constraint can be used to assign a constant value to
               a column, and the user need not insert values for such a
               column.
               A rule provides a mechanism for enforcing domain integrity for
               columns or user-defined data types.
               User-defined data types are custom data types defined by the
               users with a custom name.
               A partitioned table is created to manage the data and improve
               the query performance.
               The ALTER TABLE statement is used to modify a table.
               The DROP TABLE statement is used to delete a table.




    Ver. 1.0                    Session 7                            Slide 33 of 33

More Related Content

What's hot

09 qmds2005 session13
09 qmds2005 session1309 qmds2005 session13
09 qmds2005 session13
Niit Care
 
GR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM OptimizationGR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM Optimization
GR8Conf
 
06 qmds2005 session08
06 qmds2005 session0806 qmds2005 session08
06 qmds2005 session08
Niit Care
 
GR8Conf 2011: Grails 1.4 Update by Peter Ledbrook
GR8Conf 2011: Grails 1.4 Update by Peter LedbrookGR8Conf 2011: Grails 1.4 Update by Peter Ledbrook
GR8Conf 2011: Grails 1.4 Update by Peter Ledbrook
GR8Conf
 

What's hot (19)

09 qmds2005 session13
09 qmds2005 session1309 qmds2005 session13
09 qmds2005 session13
 
Java &amp; banco de dados
Java &amp; banco de dadosJava &amp; banco de dados
Java &amp; banco de dados
 
GR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM OptimizationGR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM Optimization
 
06 qmds2005 session08
06 qmds2005 session0806 qmds2005 session08
06 qmds2005 session08
 
Sql analytic queries tips
Sql analytic queries tipsSql analytic queries tips
Sql analytic queries tips
 
Oracle Database Security For Developers
Oracle Database Security For DevelopersOracle Database Security For Developers
Oracle Database Security For Developers
 
Database administration commands
Database administration commands Database administration commands
Database administration commands
 
Sql
SqlSql
Sql
 
GR8Conf 2011: Grails 1.4 Update by Peter Ledbrook
GR8Conf 2011: Grails 1.4 Update by Peter LedbrookGR8Conf 2011: Grails 1.4 Update by Peter Ledbrook
GR8Conf 2011: Grails 1.4 Update by Peter Ledbrook
 
The Ring programming language version 1.2 book - Part 17 of 84
The Ring programming language version 1.2 book - Part 17 of 84The Ring programming language version 1.2 book - Part 17 of 84
The Ring programming language version 1.2 book - Part 17 of 84
 
MySql:Introduction
MySql:IntroductionMySql:Introduction
MySql:Introduction
 
Oracle ORA Errors
Oracle ORA ErrorsOracle ORA Errors
Oracle ORA Errors
 
Postgre sql run book
Postgre sql run bookPostgre sql run book
Postgre sql run book
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
MySql:Basics
MySql:BasicsMySql:Basics
MySql:Basics
 
MySQL lecture
MySQL lectureMySQL lecture
MySQL lecture
 
Database Basics and MySQL
Database Basics and MySQLDatabase Basics and MySQL
Database Basics and MySQL
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
 

Viewers also liked

Rotary Club Of Pashupati-Ktm Rota Activities 2014-2015
Rotary Club Of Pashupati-Ktm Rota Activities 2014-2015Rotary Club Of Pashupati-Ktm Rota Activities 2014-2015
Rotary Club Of Pashupati-Ktm Rota Activities 2014-2015
paudelmanoj
 
Conozco y limpio mis dientes (3) madiay
Conozco y limpio mis dientes (3)  madiayConozco y limpio mis dientes (3)  madiay
Conozco y limpio mis dientes (3) madiay
MADIAY
 
Amenazas contra compañeros de la ucizoni
Amenazas contra compañeros de la ucizoniAmenazas contra compañeros de la ucizoni
Amenazas contra compañeros de la ucizoni
UCIZONI AC
 
Tecnologia ip.pptx adriana blasco
Tecnologia ip.pptx adriana blascoTecnologia ip.pptx adriana blasco
Tecnologia ip.pptx adriana blasco
adripblasco
 
Vittorio Tedeschi lança campanha: Bridge, esporte Olímpico
Vittorio Tedeschi lança campanha: Bridge, esporte OlímpicoVittorio Tedeschi lança campanha: Bridge, esporte Olímpico
Vittorio Tedeschi lança campanha: Bridge, esporte Olímpico
VittorioTedeschi
 
Project Management Article Transport Magazine dual language rev6
Project Management Article Transport Magazine dual language rev6Project Management Article Transport Magazine dual language rev6
Project Management Article Transport Magazine dual language rev6
Rene Cruz
 

Viewers also liked (19)

Rotary Club Of Pashupati-Ktm Rota Activities 2014-2015
Rotary Club Of Pashupati-Ktm Rota Activities 2014-2015Rotary Club Of Pashupati-Ktm Rota Activities 2014-2015
Rotary Club Of Pashupati-Ktm Rota Activities 2014-2015
 
Conozco y limpio mis dientes (3) madiay
Conozco y limpio mis dientes (3)  madiayConozco y limpio mis dientes (3)  madiay
Conozco y limpio mis dientes (3) madiay
 
Amenazas contra compañeros de la ucizoni
Amenazas contra compañeros de la ucizoniAmenazas contra compañeros de la ucizoni
Amenazas contra compañeros de la ucizoni
 
品座
品座品座
品座
 
Tecnologia ip.pptx adriana blasco
Tecnologia ip.pptx adriana blascoTecnologia ip.pptx adriana blasco
Tecnologia ip.pptx adriana blasco
 
Conozco y limpio mis dientes (2) madiay
Conozco y limpio mis dientes (2)  madiayConozco y limpio mis dientes (2)  madiay
Conozco y limpio mis dientes (2) madiay
 
Vittorio Tedeschi lança campanha: Bridge, esporte Olímpico
Vittorio Tedeschi lança campanha: Bridge, esporte OlímpicoVittorio Tedeschi lança campanha: Bridge, esporte Olímpico
Vittorio Tedeschi lança campanha: Bridge, esporte Olímpico
 
Ds 6
Ds 6Ds 6
Ds 6
 
Presentatie framingham-bij-ouderen-finaal
Presentatie framingham-bij-ouderen-finaalPresentatie framingham-bij-ouderen-finaal
Presentatie framingham-bij-ouderen-finaal
 
Fabricación unión
Fabricación uniónFabricación unión
Fabricación unión
 
Inversión para el progreso
Inversión para el progresoInversión para el progreso
Inversión para el progreso
 
Ekonomi sem 2
Ekonomi sem  2Ekonomi sem  2
Ekonomi sem 2
 
Doc2
Doc2Doc2
Doc2
 
Team Power Point
Team Power PointTeam Power Point
Team Power Point
 
Ideas de negocio globales para internacionalización de startups.
Ideas de negocio globales para internacionalización de startups. Ideas de negocio globales para internacionalización de startups.
Ideas de negocio globales para internacionalización de startups.
 
Categoria
CategoriaCategoria
Categoria
 
Internacionalización en red. Redes sociales e internacionalización 360
Internacionalización en red. Redes sociales e internacionalización 360Internacionalización en red. Redes sociales e internacionalización 360
Internacionalización en red. Redes sociales e internacionalización 360
 
Project Management Article Transport Magazine dual language rev6
Project Management Article Transport Magazine dual language rev6Project Management Article Transport Magazine dual language rev6
Project Management Article Transport Magazine dual language rev6
 
Angka indeks statistika
Angka indeks statistikaAngka indeks statistika
Angka indeks statistika
 

Similar to 05 qmds2005 session07

11 qmds2005 session16
11 qmds2005 session1611 qmds2005 session16
11 qmds2005 session16
Niit Care
 
Introducing ms sql_server
Introducing ms sql_serverIntroducing ms sql_server
Introducing ms sql_server
leetinhf
 
07 qmds2005 session10
07 qmds2005 session1007 qmds2005 session10
07 qmds2005 session10
Niit Care
 
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdfmysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
pradnyamulay
 
05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx
MohamedNowfeek1
 
Lecture on DBMS & MySQL.pdf v. C. .
Lecture on DBMS & MySQL.pdf v.  C.     .Lecture on DBMS & MySQL.pdf v.  C.     .
Lecture on DBMS & MySQL.pdf v. C. .
MayankSinghRawat6
 
android sqlite
android sqliteandroid sqlite
android sqlite
Deepa Rani
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
EliasPetros
 
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptxhjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
EliasPetros
 
Introducing ms sql_server_updated
Introducing ms sql_server_updatedIntroducing ms sql_server_updated
Introducing ms sql_server_updated
leetinhf
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
webhostingguy
 

Similar to 05 qmds2005 session07 (20)

11 qmds2005 session16
11 qmds2005 session1611 qmds2005 session16
11 qmds2005 session16
 
Introducing ms sql_server
Introducing ms sql_serverIntroducing ms sql_server
Introducing ms sql_server
 
07 qmds2005 session10
07 qmds2005 session1007 qmds2005 session10
07 qmds2005 session10
 
Module02
Module02Module02
Module02
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architecture
 
Dms 22319 micro project
Dms 22319 micro projectDms 22319 micro project
Dms 22319 micro project
 
Getting Started with MySQL I
Getting Started with MySQL IGetting Started with MySQL I
Getting Started with MySQL I
 
MySQL and its basic commands
MySQL and its basic commandsMySQL and its basic commands
MySQL and its basic commands
 
Sq lite module5
Sq lite module5Sq lite module5
Sq lite module5
 
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdfmysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
 
05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx
 
Sql server basics
Sql server basicsSql server basics
Sql server basics
 
SQL2.pptx
SQL2.pptxSQL2.pptx
SQL2.pptx
 
Lecture on DBMS & MySQL.pdf v. C. .
Lecture on DBMS & MySQL.pdf v.  C.     .Lecture on DBMS & MySQL.pdf v.  C.     .
Lecture on DBMS & MySQL.pdf v. C. .
 
android sqlite
android sqliteandroid sqlite
android sqlite
 
SQL_SERVER_BASIC_1_Training.pptx
SQL_SERVER_BASIC_1_Training.pptxSQL_SERVER_BASIC_1_Training.pptx
SQL_SERVER_BASIC_1_Training.pptx
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
 
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptxhjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
 
Introducing ms sql_server_updated
Introducing ms sql_server_updatedIntroducing ms sql_server_updated
Introducing ms sql_server_updated
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
 

More from 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
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

05 qmds2005 session07

  • 1. Querying and Managing Data Using SQL Server 2005 Objectives In this session, you will learn to: Manage databases Manage tables Ver. 1.0 Session 7 Slide 1 of 33
  • 2. Querying and Managing Data Using SQL Server 2005 Identifying the System Databases in SQL Server 2005 SQL Server 2005 contains the following system databases: – master: The master database that records all the server-specific configuration information. – tempdb: The temporary database that holds all temporary tables and stored procedures. – model: The model database that acts as a template or prototype for the new databases. – msdb: The database that handles the task of scheduling, exception handling, etc. – Resource: Read-only database that contains all the system objects included in the SQL Server 2005. Ver. 1.0 Session 7 Slide 2 of 33
  • 3. Querying and Managing Data Using SQL Server 2005 Just a minute What is the utility of the model database? Answer: The model database acts as a template or a prototype for the new databases. Ver. 1.0 Session 7 Slide 3 of 33
  • 4. Querying and Managing Data Using SQL Server 2005 Creating a User-Defined Database User-defined database: Is stored as a set of files. These files include: • Primary data file • Secondary data file • Transaction log file Syntax: CREATE DATABASE database_name [ ON [ PRIMARY ] [ < filespec >]] [ LOG ON { < filespec > [ ,...n ] } ] < filespec > ::= ( [ NAME = logical_file_name , ] FILENAME = 'os_file_name' [ , SIZE = size ] [ , MAXSIZE = { max_size | UNLIMITED } ] [ , FILEGROWTH = growth_increment ] ) [,...n] Let’s see how… Ver. 1.0 Session 7 Slide 4 of 33
  • 5. Querying and Managing Data Using SQL Server 2005 Just a minute Which statement is used to create a database? Answer: The CREATE DATABASE statement Ver. 1.0 Session 7 Slide 5 of 33
  • 6. Querying and Managing Data Using SQL Server 2005 Creating a Table Table: Is created to store data Is created by using the CREATE TABLE statement Syntax: CREATE TABLE [ database_name . [ schema_name ] .] table_name ( { <column_definition> | <computed_column_definition> } [ <table_constraint> ] [ ,...n ] ) [ ON { partition_scheme_name ( partition_column_name ) | filegroup | "default" } ] [ { TEXTIMAGE_ON { filegroup | "default" } ] [ ; ] Ver. 1.0 Session 7 Slide 6 of 33
  • 7. Querying and Managing Data Using SQL Server 2005 Creating a Table (Contd.) Example: Create an EmployeeLeave table in the HumanResources schema with the following details: Columns Data Type Checks EmployeeID int NOT NULL LeaveStartDate date NOT NULL LeaveEndDate date NOT NULL LeaveReason varchar(100) NOT NULL LeaveType char(2) NOT NULL Let’s see how… Ver. 1.0 Session 7 Slide 7 of 33
  • 8. Querying and Managing Data Using SQL Server 2005 Implementing Data Integrity Avoids data redundancy Ensures that the data in a database is accurate, consistent, and reliable Is broadly classified into the following categories: Entity integrity: Ensures that each row can be uniquely identified by an attribute called the primary key 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 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 Ver. 1.0 Session 7 Slide 8 of 33
  • 9. Querying and Managing Data Using SQL Server 2005 Implementing Data Integrity (Contd.) You can maintain data integrity by: Applying constraints Applying rules Using user-defined types Ver. 1.0 Session 7 Slide 9 of 33
  • 10. Querying and Managing Data Using SQL Server 2005 Implementing Data Integrity (Contd.) Constraints can be applied: By using CREATE TABLE statement By using ALTER TABLE statement Syntax: CREATE TABLE table_name ( column_name CONSTRAINT constraint_name constraint_type [,CONSTRAINT constraint_name constraint_type] ) Ver. 1.0 Session 7 Slide 10 of 33
  • 11. Querying and Managing Data Using SQL Server 2005 Implementing Data Integrity (Contd.) Constraints are of the following types: Primary key constraint Unique constraint Foreign key constraint Check constraint Default constraint Ver. 1.0 Session 7 Slide 11 of 33
  • 12. Querying and Managing Data Using SQL Server 2005 Implementing Data Integrity (Contd.) Primary key constraint: Is defined on a column or a set of columns whose values uniquely identify all the rows in a table Does not allow NULL values in the column Ensures entity integrity Syntax: CREATE TABLE table_name ( col_name [CONSTRAINT constraint_name PRIMARY KEY [CLUSTERED|NONCLUSTERED] col_name [, col_name [, col_name [, …]]] ) Ver. 1.0 Session 7 Slide 12 of 33
  • 13. Querying and Managing Data Using SQL Server 2005 Implementing Data Integrity (Contd.) Unique constraint: Is defined to enforce uniqueness in non-primary key columns Allows one NULL value in the column Syntax: CREATE TABLE table_name ( col_name [CONSTRAINT constraint_name UNIQUE [CLUSTERED | NONCLUSTERED] (col_name [, col_name [, col_name [, …]]]) col_name [, col_name [, col_name [, …]]] ) Ver. 1.0 Session 7 Slide 13 of 33
  • 14. Querying and Managing Data Using SQL Server 2005 Implementing Data Integrity (Contd.) Foreign key constraint: Is defined to remove the inconsistency in two tables when the data in one table depends on the data in another table Associates one or more columns (the foreign key) of a table with an identical set of columns (a primary key column) in another table Ver. 1.0 Session 7 Slide 14 of 33
  • 15. Querying and Managing Data Using SQL Server 2005 Implementing Data Integrity (Contd.) Syntax: CREATE TABLE table_name ( col_name [CONSTRAINT constraint_name FOREIGN KEY (col_name [, col_name [, …]]) REFERENCES table_name (column_name [, column_name [, …]])] (col_name [, col_name [, col_name [, …]]]) col_name [, col_name [, col_name [, …]]] ) Let’s see how… Ver. 1.0 Session 7 Slide 15 of 33
  • 16. Querying and Managing Data Using SQL Server 2005 Implementing Data Integrity (Contd.) Check constraint: Is defined to enforce domain integrity by restricting the values to be inserted in a column Can be defined on multiple columns Is specified by using the following keywords: IN LIKE BETWEEN Ver. 1.0 Session 7 Slide 16 of 33
  • 17. Querying and Managing Data Using SQL Server 2005 Implementing Data Integrity (Contd.) Syntax: CREATE TABLE table_name ( col_name [CONSTRAINT constraint_name] CHECK (expression) (col_name [, col_name [, …]]) . ) Let’s see how… Ver. 1.0 Session 7 Slide 17 of 33
  • 18. Querying and Managing Data Using SQL Server 2005 Implementing Data Integrity (Contd.) Default constraint: – Is defined to assign a constant value to a column – Syntax: CREATE TABLE table_name ( col_name [CONSTRAINT constraint_name] DEFAULT (constant_expression | NULL) (col_name [, col_name [, …]]) . ) Let’s see how… Ver. 1.0 Session 7 Slide 18 of 33
  • 19. Querying and Managing Data Using SQL Server 2005 Just a minute Which keyword is used to specify a check constraint? Answer: A check constraint can be specified by using the LIKE, IN, and BETWEEN keywords. Ver. 1.0 Session 7 Slide 19 of 33
  • 20. Querying and Managing Data Using SQL Server 2005 Implementing Data Integrity (Contd.) Rules: Help in enforcing domain integrity for columns or user-defined data types Can be specified to the column or the user-defined data type before an INSERT or UPDATE statement is issued Are used to implement business-related restrictions or limitations Can be created by using the CREATE RULE statement Syntax: CREATE RULE rule_name AS conditional_expression Can be bound by using the sp_bindrule stored procedure Let’s see how… Ver. 1.0 Session 7 Slide 20 of 33
  • 21. Querying and Managing Data Using SQL Server 2005 Implementing Data Integrity (Contd.) User-defined data types: Are custom data types defined by the users with a custom name Can be created by using the CREATE TYPE statement Syntax: CREATE TYPE [ schema_name. ] type_name { FROM base_type [ ( precision [ , scale ] ) ] [ NULL | NOT NULL ] } [ ; ] Let’s see how… Ver. 1.0 Session 7 Slide 21 of 33
  • 22. Querying and Managing Data Using SQL Server 2005 Just a minute You want to create a rule, rule1, which allows the user to enter any of the four values: Tea, Coffee, Soup, or Miranda in a column. Which command should you execute? Answer: CREATE RULE rule1 AS @TypeRule IN ('Tea', 'Coffee', 'Soup', 'Miranda') Ver. 1.0 Session 7 Slide 22 of 33
  • 23. Querying and Managing Data Using SQL Server 2005 Creating a Partitioned Table Flash presentation: Partitioning Tables Partitioned table: Is created when the table contains voluminous data Is created to separate data into multiple physical locations based on a range of values for a specific column Helps in improving query performance Can be created by: Creating a partition function Creating a partition scheme Creating a table by using the partition scheme Ver. 1.0 Session 7 Slide 23 of 33
  • 24. Querying and Managing Data Using SQL Server 2005 Modifying a Table Modify a table: When there is a requirement to add or remove columns and constraints Using the ALTER TABLE statement Syntax: ALTER TABLE [ database_name . [ schema_name ] . | schema_name . ] table_name { ALTER COLUMN column_name { [ NULL | NOT NULL ] } | [ WITH { CHECK | NOCHECK } ] ADD COLUMN <column_definition> { ADD CONSTRAINT constraint_name constraint_type Let’s see how… Ver. 1.0 Session 7 Slide 24 of 33
  • 25. Querying and Managing Data Using SQL Server 2005 Just a minute You are managing a large table. You want to improve the performance of the table and want the table to be more manageable. Which strategy can you use? Answer: Partition the table Ver. 1.0 Session 7 Slide 25 of 33
  • 26. Querying and Managing Data Using SQL Server 2005 Dropping a Table Drop a table: When a table is not required Using the DROP TABLE statement Syntax: DROP TABLE [ database_name . [ schema_name ] . ] table_name Let’s see how… Ver. 1.0 Session 7 Slide 26 of 33
  • 27. Querying and Managing Data Using SQL Server 2005 Demo: Managing Tables Problem Statement: The management of AdventureWorks, Inc. has decided to provide travel and medical reimbursements to the employees. They want to store the details of these reimbursements in the database. For this, you need to create a database table, EmployeeReimbursements. The details of the tables are shown in the following table. Columns Data Type and Size Constraints RimID int Primary key EmployeeID int Foreign Key references the EmployeeID of the Employee Table, NOT NULL Amount money Amount>0 RimType varchar(20) RimType should be Medical, Cash, or Local Pending_with varchar(30) NOT NULL How will you create the table? Ver. 1.0 Session 7 Slide 27 of 33
  • 28. Querying and Managing Data Using SQL Server 2005 Demo: Managing Tables (Contd.) Solution: To solve the preceding problem, you need to perform the following tasks: 1. Write the query to create a table. 2. Execute the statement to verify the result. Ver. 1.0 Session 7 Slide 28 of 33
  • 29. Querying and Managing Data Using SQL Server 2005 Summary In this session, you learned that: A database is a repository of information that contains data in an organized way. The master database records all the server-specific configuration information, including authorized users, databases, system configuration settings, and remote servers. The tempdb database is a temporary database that holds all temporary tables and stored procedures. The model database acts as a template or a prototype for the new databases. The msdb database supports the SQL Server Agent. The SQL Server Agent includes features that schedule periodic activities of the SQL Server. The Resource database is a read-only database that contains all the system objects that are included with SQL Server 2005. Ver. 1.0 Session 7 Slide 29 of 33
  • 30. Querying and Managing Data Using SQL Server 2005 Summary (Contd.) The user-defined databases are created by the users to store data for client-server applications. A database consists of the following types of files: • Primary data file • Secondary data file • Transaction log file – A database must consist of a primary data file and one transaction log file. – The CREATE DATABASE statement is used to create a database, which also includes determining the name of the database, the size of the database, and the files used to store data in the database. – Tables are used to store data. Ver. 1.0 Session 7 Slide 30 of 33
  • 31. Querying and Managing Data Using SQL Server 2005 Summary (Contd.) Tables are used to store data. The CREATE TABLE statement is used to create a table. Data integrity is enforced to keep the data in a database accurate, consistent, and reliable. It is broadly classified into the following categories: • Entity integrity: Ensures that each row can be uniquely identified by an attribute called the primary key. • 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 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. Ver. 1.0 Session 7 Slide 31 of 33
  • 32. Querying and Managing Data Using SQL Server 2005 Summary (Contd.) Constraints define rules that must be followed to maintain consistency and correctness of data. A primary key constraint is defined on a column or a set of columns whose values uniquely identify rows in a table. The unique constraint is used to enforce uniqueness on non- primary key columns. A foreign key constraint associates one or more columns of a table (the foreign key) with an identical set of columns on which a primary key constraint has been defined (a primary key column in another table). A check constraint enforces domain integrity by restricting the values to be inserted in a column. The IN, LIKE, and BETWEEN keywords are used to define the check constraint. Ver. 1.0 Session 7 Slide 32 of 33
  • 33. Querying and Managing Data Using SQL Server 2005 Summary (Contd.) A default constraint can be used to assign a constant value to a column, and the user need not insert values for such a column. A rule provides a mechanism for enforcing domain integrity for columns or user-defined data types. User-defined data types are custom data types defined by the users with a custom name. A partitioned table is created to manage the data and improve the query performance. The ALTER TABLE statement is used to modify a table. The DROP TABLE statement is used to delete a table. Ver. 1.0 Session 7 Slide 33 of 33

Editor's Notes

  1. Start the session with explaining the objectives to the students. Note Create a new user named Samual, give dbcreator permission to the user and then create the database. Use the following statement to to create the user and provide the dbcreator role: CREATE LOGIN Samual WITH PASSWORD =&apos;niit#1234&apos; EXEC sys.sp_addsrvrolemember @loginame = N&apos;Samual&apos;, @rolename = N&apos;dbcreator&apos;
  2. Explain the students that System databases are the databases which are present in SQL Server by default. These databases help SQL Server to work properly. Additional Input Unlike previous versions of SQL Server, installing or roll backing a service pack is not a big task now. SQL Server 2005 provides Resources database which holds the definitions of all the server specific stored procedures and views. Therefore, while installing a service pack, you need not to remove all the database from the server any more.
  3. Example In addition to the example given in the SG, you can also provide the following example that includes all the parameters. CREATE DATABASE Employee ON ( NAME = Employee_dat, FILENAME = &apos;C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\Employee_Data.mdf&apos;, SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ) LOG ON ( NAME = Employee_log, FILENAME = &apos;C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\Employee_Log.ldf&apos;, SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB ) GO Remember that in the preceding statement, the path provided will be the path where the SQL Server is installed.
  4. Table Creation Before a table is created, tell your students that the database has to be created. The tables are created in a database. Tell the students that the database has already been created for them. This will not be covered in class. Normally, databases are created and managed by experienced database administrators. While creating a table, it is a good practice to explicitly mention whether an attribute allows null or not null values. Tell the students that it is a good practice to name the tables and attributes meaningfully, and that they should follow the recommended naming conventions. SQL Server does not allow keywords to be used as column names. If a table already exists with a particular name, you will not be able to create another with the same name. You need to drop the table and re-create it again with the same name. Additional Inputs Identity columns can be created to ensure that SQL Server inserts unique values automatically. There can be only one column declared as an identity column. An identity column cannot be updated. It does not allow null values. It can be of the int, smallint, tinyint, and float data types. This property can be used with the CREATE TABLE and ALTER TABLE Transact-SQL statements. Syntax: IDENTITY [ ( seed , increment ) ] Where: seed: specifies the value that is used for the very first row added into the table increment: specifies the incremental value, which needs to be added with the identity value of the previous row that is added
  5. Example CREATE TABLE HumanResources.EmployeeLeave ( EmployeeID int NOT NULL, LeaveStartDate datetime NOT NULL, LeaveEndDate datetime NOT NULL, LeaveReason varchar(100), LeaveType char(2)NOT NULL )
  6. Explain the students that various type of integrities can be used to remove the redundancy from the data stored in a table. Additional Inputs Domain integrity is implemented using the CHECK constraint. Entity integrity is implemented using the PRIMARY KEY constraint. Referential integrity is implemented using the FOREIGN KEY and PRIMARY KEY constraints. User-defined integrity is implemented in the form of business rules using CHECK constraints or triggers.
  7. Additional Inputs Constraints can be added while creating the table. They can also be added later using the ALTER TABLE statement. When a constraint is added in an existing table, by default, it checks the existing data. The system tables which store constraint definitions are syscomments, sysreferences, and sysconstraints. To view all the constraints on a table use sp_helpconstraint followed by the table name.
  8. Additional Inputs Constraints can be added while creating the table. They can also be added later using the ALTER TABLE statement. When a constraint is added in an existing table, by default, it checks the existing data. The system tables which store constraint definitions are syscomments, sysreferences, and sysconstraints. To view all the constraints on a table use sp_helpconstraint followed by the table name.
  9. Additional Inputs Constraints can be added while creating the table. They can also be added later using the ALTER TABLE statement. When a constraint is added in an existing table, by default, it checks the existing data. The system tables which store constraint definitions are syscomments, sysreferences, and sysconstraints. To view all the constraints on a table use sp_helpconstraint followed by the table name.
  10. Foreign Key Stress on the fact that a foreign key constraint can refer to another column of another table or another column of the same table. The easiest way to implement referential integrity is to define a PRIMARY KEY constraint on the parent table and a FOREIGN KEY constraint on the child table. If an index is used to implement the primary key and entity integrity on the parent table, then referential integrity can be implemented using a trigger on the child table. Triggers are dealt with in more detail later in the course. Example: Adding a foreign key in the EmployeeLeave table. CREATE TABLE HumanResources.EmployeeLeave ( EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES HumanResources.Employee(EmployeeID), LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY KEY(EmployeeID, LeaveStartDate), … … …
  11. Foreign Key Stress on the fact that a foreign key constraint can refer to another column of another table or another column of the same table. The easiest way to implement referential integrity is to define a PRIMARY KEY constraint on the parent table and a FOREIGN KEY constraint on the child table. If an index is used to implement the primary key and entity integrity on the parent table, then referential integrity can be implemented using a trigger on the child table. Triggers are dealt with in more detail later in the course. Example: Adding a foreign key in the EmployeeLeave table. CREATE TABLE HumanResources.EmployeeLeave ( EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES HumanResources.Employee(EmployeeID), LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY KEY(EmployeeID, LeaveStartDate), … … …
  12. Check Constraint A CHECK constraint on a column implements domain integrity on the column. A column level CHECK constraint can refer to values of only that column. However, a table level constraint can refer to values of other columns of the same table. Additional Inputs When a CHECK constraint is applied on a column, it verifies the data every time an insertion or an updation happens. A table level check constraint can reference another column on the same table. It cannot be placed on columns having the IDENTITY property. Example: Adding a check constraint in the EmployeeLeave table. CREATE TABLE HumanResources.EmployeeLeave ( EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES HumanResources.Employee(EmployeeID), LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY KEY(EmployeeID, LeaveStartDate), LeaveEndDate datetime NOT NULL, LeaveReason varchar(100), LeaveType char(2) CONSTRAINT chkLeave CHECK(LeaveType IN(&apos;CL&apos;,&apos;SL&apos;,&apos;PL&apos;)) )
  13. Check Constraint A CHECK constraint on a column implements domain integrity on the column. A column level CHECK constraint can refer to values of only that column. However, a table level constraint can refer to values of other columns of the same table. Additional Inputs When a CHECK constraint is applied on a column, it verifies the data every time an insertion or an updation happens. A table level check constraint can reference another column on the same table. It cannot be placed on columns having the IDENTITY property. Example: Adding a check constraint in the EmployeeLeave table. CREATE TABLE HumanResources.EmployeeLeave ( EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES HumanResources.Employee(EmployeeID), LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY KEY(EmployeeID, LeaveStartDate), LeaveEndDate datetime NOT NULL, LeaveReason varchar(100), LeaveType char(2) CONSTRAINT chkLeave CHECK(LeaveType IN(&apos;CL&apos;,&apos;SL&apos;,&apos;PL&apos;)) )
  14. Default Constraint Stress the fact that a default constraint is used for easing data entry. Additional Inputs A default constraint only applies to insert statements. A default cannot be placed on columns with IDENTITY properties. Example: Adding a default constraint in the EmployeeLeave table. CREATE TABLE HumanResources.EmployeeLeave ( EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES HumanResources.Employee(EmployeeID), LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY KEY(EmployeeID, LeaveStartDate), LeaveEndDate datetime NOT NULL, LeaveReason varchar(100), LeaveType char(2) CONSTRAINT chkLeave CHECK(LeaveType IN(&apos;CL&apos;,&apos;SL&apos;,&apos;PL&apos;)) CONSTRAINT chkDefLeave DEFAULT &apos;PL&apos; )
  15. Rules and Defaults CHECK constraints can also be implemented using rules. Similarly, default constraints can also be implemented using defaults. If the same check constraints or default constraints apply to columns in more than one table, then a rule or default can be created and bound to the columns. Example: Creating a rule, rulType for the LeaveType column of EmployeeLeave table CREATE RULE rulType AS @LeaveType IN (&apos;CL&apos;, &apos;SL&apos;, &apos;PL&apos;)
  16. User-defined Data types Explain to the students that a user-defined data type is created for an attribute if the attribute appears in more than one table. Besides, a user-defined data type is used to maintain consistency of the system data type used for an attribute across tables. Tell the students that a user-defined data type needs to be created before creating the table. Before dropping a user-defined data type, ensure that it is not being used in any table. Stress again the need for naming the data types meaningfully. Also, ask them to follow the recommended naming conventions. Additional Inputs User-defined data types created in the model database are automatically included in all databases that are subsequently created. Each user-defined data type when created adds a row to the systypes table. The nullability of the column defined in the table, overrides that of the data type’s. Example: Creating an user-defined data type for descriptive columns CREATE TYPE DSCRP FROM varchar(100) NOT NULL ;
  17. Example: Adding a column in the existing table EmployeeLeave ALTER TABLE HumanResources.EmployeeLeave ADD ClaimDetails DSCRP NOT NULL CONSTRAINT chkDefClaim DEFAULT &apos;No Claim‘
  18. Table Deletion Tell the students that once a table is dropped, it cannot be referred to unless recreated. Additional Inputs Before dropping a table, you must remove any references between the table and any other object. Example: Removing the EmployeeLeave table. DROP TABLE HumanResources.EmployeeLeave
  19. You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.
  20. You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.
  21. You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.
  22. You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.
  23. You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.