0% found this document useful (0 votes)
7 views

DB2 Session01

The document provides an introduction to relational databases and SQL. It discusses database concepts like the relational model, normalization, integrity rules and the entity-relationship model. It also covers SQL and its uses for data manipulation, definition and control. Relational concepts like tables, rows, columns, primary keys and foreign keys are explained.

Uploaded by

ritankardey21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

DB2 Session01

The document provides an introduction to relational databases and SQL. It discusses database concepts like the relational model, normalization, integrity rules and the entity-relationship model. It also covers SQL and its uses for data manipulation, definition and control. Relational concepts like tables, rows, columns, primary keys and foreign keys are explained.

Uploaded by

ritankardey21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

DB2 1

DB2 – Session 1
DB2 2

Topics to be covered in this session


• Introduction to databases - covers their advantages and
the types of databases
• Relational database concepts - covers Properties,
Terminology, Normalization, Integrity rules, CODD’s
Relational Rules and the E-R model
DB2 3

Introduction to Databases
What is Data ?
‘A representation of facts or instruction in a form
suitable for communication’ - IBM Dictionary

What is a Database ?
‘Is a repository for stored data’ - C.J.Date
DB2 4

Introduction to Database (contd...)


What is a database system ?
An integrated and shared repository for stored data or
collection of stored operational data used by
application systems of some particular enterprise.
Or
‘Nothing more than a computer-based record keeping
system’.
DB2 5

Advantages of DBMS over File Mngt Sys


• Data redundancy
• Multiple views
• Shared data
• Data independence (logical/physical)
• Data dictionary
• Search versatility
• Cost effective
• Security & Control
• Recovery restart & Backup
• Concurrency
DB2 6

TYPES OF DATABASES (or Models)

• Hierarchical Model
• Network Model
• Relational Model
• Object-Oriented Model
DB2 7

Types of Databases (contd...)

HIERARCHICAL
• Top down structure resembling an upside-down
tree
• Parent child relationship
• First logical database model
• Available on most of the Mainframe computers
• Example - IMS
DB2 8

Types of Database (contd...)

NETWORK
• Does not distinguish between parent and child. Any
record type can be associated with any number of
arbitrary record types
• Enhanced to overcome limitations of other models
but in reality, there is minimal difference due to
frequent enhancements
• Example - IDMS
DB2 9

Types of Database (contd...)

RELATIONAL
• Data stored in the form of tables consists of
multiple rows and columns.
• Examples - DB2, Oracle, Sybase, Ingres etc.

OBJECT -ORIENTED MODEL


• Data attributes and methods that operate on those
attributes are encapsulated in structures called
objects
DB2 10

RELATIONAL DB CONCEPTS
DB2 11

Relational Properties
• Why Relational ? - Relation is a mathematical
term for a table - Hence Relational database ‘is
perceived’ by the users as a set of tables.
• All data values are atomic.
• Entries in columns are from the same domain
• Sequence of rows (T-B) is insignificant
• Each row is unique
• Sequence of columns (L-R) is insignificant
DB2 12
Relational Concepts (Terminology)
• Relation : A table or File
• Tuple : Row contains an entry for each attribute
• Attributes : Columns or the characteristics that
define the entity
• Domain:. A range of values (or Pool)
• Entity : Some object about which we wish to store
information
• Null : Represents an unknown/empty value
• Atomic Value: Smallest unit of data; the individual
data value
DB2 13

Relational Concepts (contd...)


• Candidate key : Some attribute (or a set of
attributes) that may uniquely identify each
row(tuple) in the relation(table)
• Primary key : The candidate key that is chosen for
primary attributes to uniquely identify each row.
• Alternate key :The remaining candidate keys that
were not chosen as primary key
• Foreign key :An attribute of one relation that might
be a primary key of another relation.
DB2 14

Types of Integrity

• Entity Integrity : Is a state Where no column that is


part of a primary key can have a null values.
• Referential Integrity : Is a state Where every foreign
key in the first table must either match a primary key
value in the second table or must be wholly null
• Domain Integrity : Integrity of information allowed in
column
DB2 15

Entity Relationship Model

• E-R model is a logical representation of data for a


business area
• Represented as entities, relationship between entities
and attributes of both relationships and entities
• E-R models are outputs of analysis phase i.e they
are conceptual data models expressed in the form of an
E-R Diagram
DB2 16

Example of a Relational Structure

CUSTOMER Places ORDERS


ORDER Has ITEMS
DB2 17
The above relations can be interpreted as
follows:
• Each order relates to only one customer (one-to-one)
• Many orders can contain many items (many-to-many)
• A customer can place any number of orders (one-to-
many)
DB2 18

Entity Relationship Model (contd...)

• In the above example Customer, Order & Item are


called ENTITIES.
• An Entity may transform into table(s).
• The unique identity for information stored in an
ENTITY is called a PRIMARY KEY. E.g...
CUSTOMER-ID uniquely identifies each customer
DB2 19

Entity Relationship Model (contd...)

A table essentially consists of


• Attributes, which define the characteristics of the
table
• Primary key, which uniquely identifies each row of
data stored in a table
• Secondary & Foreign Keys/indexes
DB2 20

Entity Relationship Model (contd...)


Table Definition :

Table ‘CUSTOMER’ -
Attributes - CUST_ID, CUST_NAME,
CUST_ADDRESS, CUST_ZIPCODE,
CUST_CCARD_NO...

Primary Key - CUSTOMER_ID


Secondary Key - CUST_CCARD_NO
DB2 21

Entity Relationship Model (contd...)


Table Definition :

Table ‘ORDER’ -
Attributes – ORDER_NO, CUST_ID, ORDER_DATE,
ORDER_AMT, ORDER_STATUS...

Primary Key - ORDER_NO


Foreign Key - CUST_ID
DB2 22

Entity Relationship Model (contd...)

• The Relationships transform into Foreign Keys.


For e.g.. ORDER is related to CUSTOMER through
‘CUST_ID’ which is the foreign key in ORDER and
Primary key in CUSTOMER.
• As per the relational integrity the Primary Key,
CUST_ID for the table CUSTOMER can never be null,
while it can, theoretically, be so in the table ORDER.
In practical scenarios, this is dependent on the
database design. That is, for instance, database
can be designed so that CUST_ID will never be
null on ORDER as well.
DB2 23

Entity Relationship Model (contd...)

• Tables exist in Tablespaces. A tablespace can contain


one or more tables
• Apart from the Primary Key, a table can have many
secondary keys/indexes, which exist in Indexspaces.
• These tablespaces and indexspaces together exist in a
Database
DB2 24

Entity Relationship Model (contd...)

• To do transformations as described above we need a


tool that will provide a way of creating the tables,
manipulate the data present in these, create
relationships, indexes, tablespace, indexspace and so
on. DB2 provides SQL which performs these functions.
The next part briefly deals with SQL and its functions.
A detailed explanation will be taken up later.
DB2 25

Topics to be covered in this session

• SQL - all data object manipulation, creation and use,


involve SQL’s.
• DB2 objects - Database, Tablespaces & Indexspaces -
creation & use, and other terminology's associated with
databases.
• DDL - Data Definition Language
DB2 26

An introduction to SQL
SQL or Structured Query Language is
• A Powerful language that performs the functions of
data manipulation(DML), data definition(DDL) and
data control or data authorization(DAL/DCL).
• A Non procedural language - the capability to act
on a set of data and the lack of need to know how to
retrieve it. An SQL can perform the functions of
more than a procedure.
• The De Facto Standard query language for RDBMS
• Very flexible
DB2 27

Introduction to SQL (contd...)


SQL - Features :-
• Unlike COBOL or 4GL’s, SQL is coded without
data-navigational instructions. The optimal access
paths are determined by the DBMS. This is
advantageous because the database knows better
how it has stored data than the user.
• What you want and not how to get it
• Set level processing & multiple row processing
DB2 28

SQL - Types (based on the functionality)

• Data Definition Language (DDL)


- Create, Alter and Drop
• Data Manipulation Language (DML)
- Select, Insert, Update and Delete
• Data Control Language (DCL)
- Grant and Revoke
DB2 29
The following are the Operations that can be
performed by a SQL on the database tables :
• Select
• Project
• Union
• Intersection
• Difference
• Join
• Divide
DB2 30

Topics dealt with, in DB2 objects

• Stogroup, Databases, Tablespaces (types, creation and


modification)
• Indexspaces (creation and modification)
• Some more terms associated with tablespaces
DB2 31

DB2 Objects

• The DB2 Object Hierarchy


DB2 32

Stogroup

• It is a collection of direct access volumes, all of the


same device type
DB2 33

Database

• A collection of logically related objects - like


Tablespaces, Indexspaces, Tables etc.
• Not a physical kind of object - may occupy more
than one disk space
DB2 34

Tablespaces

• Logical address space on secondary storage to hold one


or more tables
• Three Type of Tablespaces - Simple, Partitioned &
Segmented
DB2 35

Simple Tablespace

• Can contain more than one stored table


• Depending on application, storing more than one Table
might enable faster retrieval for joins using these tables
• Usually only one is preferred. This is because a single
page can contain rows from all tables defined in the
database.
DB2 36

Segmented Tablespaces

• Can contain more than one stored table, but in a


segmented space
• A ‘Segment’ consists of a logically contiguous set of
‘n’ pages.
• No segment is allowed to contain records for more than
one table
DB2 37

Partitioned Tablespaces
• Primarily used for Very large tables
• Only one table in a partitioned TS; 1 to 64
partitions/TS
• Numpart parameter specifies the no. of partitions
• It is partitioned in accordance with value ranges for
single or a combination of columns. Hence these
column(s) cannot be updated
DB2 38

Data types

Data Type

String Datetime Numbers

Character Graphic Date Timestamp Time

Floating
Integer Numeric
Point
Fixed Variable
Length Length
Small Large Single Double
DB2 39

Data types (continuation)

• Char(n)
• Maximum of 254 bytes
• PIC X(n)

• Avoid defining numeric data as char fields


• Char takes up more storage
• Require single quotes while querying
DB2 40

Data types (continuation)

• Varchar(n)
• Maximum of 4046 bytes.
• A structure containing
• PIC S9(4) COMP for length and
• PIC X(n) for the data
• Use only for descriptive fields.
• Can be indexed from DB2 version 7 onwards.
• Provide sufficient free space.
• Should ideally be the last field in the table.
DB2 41

Data types (continuation)

• Integer
• 4 bytes (5 if nullable)
• PIC S9(10) COMP
• Ranges from -2147483648 to +2147483647.
• Small int
• 2 bytes (3 if nullable)
• PIC S9(5) COMP
• Ranges from -32768 to 32767
• Numeric(p,s) – means s digits after decimal & total p digits
• Max of 16 bytes
• PIC S9(p-s)V9(s)COMP-3
DB2 42

Data types (continuation)

• Time
• 3 bytes (4 if nullable)
• PIC X(8)

• Date
• 4 bytes (5 if nullable)
• PIC X(10)

• Timestamp
• 10 bytes (11 if nullable)
• PIC X(26)
DB2 43

NULL value

• Not same as Zero or Blank.


• DB2 adds an extra byte to all nullable columns. This extra byte
has the information whether the field contains NULL or not.
• The NULL values do not participate in operations such as
AVERAGE, SUM, etc.,
• Need to have special care while inserting, updating, or
retrieving nullable fields in the host language program.
DB2 44

Not NULL with default

• DB2 puts the default value of the data type in that field while
inserting a record. If no default value is specified, then DB2
uses the following:
• Character fields - spaces.
• Numeric fields - zeros.
• Date fields - current date.
• Time fields - current time.

• To use specific default values, use the following syntax while


creating a table:
ColName Type NOT NULL WITH DEFAULT <value>
DB2 45

Data Definition Language


CREATE
This statement is used to create objects

Syntax : For Creating a Table


CREATE TABLE <tabname> (Col Definitions)
PRIMARY KEY(Columns) / FOREIGN KEY
UNIQUE (Colname) (referential constraint)
[LIKE Table name / View name]
[IN Database Tablespace Name ]
DB2 46

Data Definition Language (contd...)


• Foreign Key references dbname.table
• Table1 references table2(target) - Table2’s Primary key
is the foreign key defined in Table1
• ON DELETE condition can be specified while
declaring the foreign key. The Conditions that can be
used are CASCADE, RESTRICT and SET NULL
(referential constraint for the foreign key definition).
These conditions specify what should happen in the
table with the foreign key when the corresponding
primary key rows are deleted in the table with the
primary key.
DB2 47

Data Definition Language (contd...)


• Syntax:
FOREIGN KEY(CUST_ID) REFERENCES

CUSTOMER(CUST_ID)
ON DELETE CASCADE
• Default is RESTRICT
• SET NULL is allowed only if column accepts NULLs
in the foreign key table
• Inserting (or updating ) rows in the main table is
allowed only if there are no corresponding rows in the
foreign key table
DB2 48

Examples…
CREATE TABLE TRGA25.DEGREES

(DEGREE_NAME CHAR(4) NOT NULL,

START_YEAR NUMERIC(4,0),

PRIMARY KEY(DEGREE_NAME)) IN
DLFDB.DLFTS;
CREATE UNIQUE INDEX TRGA25.DEGREES_PIDX
ON TRGA25.DEGREES(DEGREE_NAME);

• DLFDB.DLFTS represents database name and table


DB2 49

…Examples…
• It is imperative to create unique index on the primary
key at the time of table creation itself
• DEGREES is the table name and the columns in it are
DEGREE_NAME and START_YEAR
• Primary key must be defined with NOT NULL, as
columns are NULLable by default
• In create index, the table name and column name
should be referred to as table name(column name)
DB2 50

…Examples…
CREATE TABLE TRGA25.STUDENTS

(REG_NO INTEGER NOT NULL,

NAME CHAR(20),
DEGREE_NAME CHAR(4),

PRIMARY KEY(REG_NO),

FOREIGN KEY(DEGREE_NAME) REFERENCES

TRGA25.DEGREES(DEGREE_NAME)
DB2 51

…Examples…
• It is also possible to restrict a column to have only a
particular set of values. For this, use CHECK. That is:
CREATE TABLE TRGA25.STUDENTS

(REG_NO INTEGER NOT NULL,

NAME CHAR(20),
DEGREE_NAME CHAR(4)
CHECK(DEGREE_NAME IN (‘ECE’, ‘EEE’)),
PRIMARY KEY(REG_NO),

FOREIGN KEY(DEGREE_NAME) REFERENCES


DB2 52

…Examples…
• For a column that has an automatically incremented
sequence number, use the following:
CREATE TABLE TRGA25.STUDENTS

(REG_NO INTEGER NOT NULL


GENERATED ALWAYS AS IDENTITY
(START WITH 100, INCREMENT BY 1),

NAME CHAR(20),
DEGREE_NAME CHAR(4)
PRIMARY KEY(REG_NO),
DB2 53

…Examples
• Creation of table and index is similar to previous
example
• Extra is definition of foreign key – the related table
should have been created before, with the appropriate
primary key and index
• Better to define foreign key along with the table
creation, else database will go into CHECKPENDING
• Good practice to give constraint name for foreign key
so that dropping it will be easier. That is:
FOREIGN KEY D_NAME(DEGREE_NAME)
REFERENCES …
DB2 54

Data Definition Language (contd...)


ALTER
This statement is used for altering all DB2 objects

Syntax : For altering a Table


ALTER TABLE <Tablename>
ADD Column Data-type [not null with default]

• Alter allows primary & foreign key specifications to be


added or dropped, addition of columns, change in
length / type for columns (provided the new length is
greater than the old one) and renaming columns
DB2 55

Data Definition Language (contd...)


Examples for ALTER TABLE…

ALTER TABLE TRGA25.STUDENTS ADD MARKS


NUMERIC(3,2)
ALTER TABLE TRGA25.DEGREES ADD PRIMARY
KEY (REG_NO)
ALTER TABLE TRGA25.DEGREES ALTER COLUMN
DEGREE_NAME SET DATA TYPE VARCHAR(5)
Assuming that DEGREE_NAME was CHAR or
VARCHAR earlier with length less than 5
DB2 56

Data Definition Language (contd...)


…Examples for ALTER TABLE

ALTER TABLE TRGA25.STUDENTS ADD FOREIGN


KEY (DEGREE_NAME) REFERENCES

TRGA25.DEGREES(DEGREE_NAME)

ALTER TABLE TRGA25.DEGREES DROP PRIMARY


KEY
ALTER TABLE TRGA25.STUDENTS DROP FOREIGN
KEY D_NAME
ALTER TABLE TRGA25.STUDENTS RENAME
DB2 57

Data Definition Language (contd...)


DROP
This statement is used for dropping all DB2 objects

Syntax : For dropping a table


DROP TABLE <Tablename>
DB2 58

Some general rules for RI & Table Parameters


• Avoid nulls in columns participating in
Arithmetic logic or comparisons
• Primary key cols cannot be nulls
• Limit referential structures to no more than
three levels in a direction
• Use DB2’s inherent features rather than program coded
RI’s.

You might also like