You are on page 1of 127

UNIT I.

  Introduction to DBMS
• Introduction :
• Basic concepts
• Advantages of DBMS over file processing systems
• Data abstraction
• Database languages
• Data models
• Data independence
• Components of a DBMS, Overall structure of DBMS
• Multi-user DBMS architecture, System catalogs
• Data Modelling: Basic concepts, Entity, attributes, relationships, constraints, keys.
• Case Study :- MySQL Database


• Text Books

• 1. Silberschatz A., Korth H., Sudarshan S. “Database System Concepts”,


6th edition, Tata McGraw Hill Publishers

• 2. G. K. Gupta “Database Management Systems” , Tata McGraw Hill


Reference Books:
• 1. Rab P., Coronel C. “Database Systems Design, Implementation
and Management”, 5th edition, Thomson Course Technology, 2002

• 2. Elmasri R., Navathe S. “ Fundamentals of Database Systems”,


4th edition, Pearson Education, 2003

• 3. Date C. “ An Introduction to Database Systems”, 7th edition,


Pearson Education, 2002

• 4. Ramkrishna R., Gehrke J. “ Database Management Systems”, 3rd


edition, McGraw Hill
Unit I : Introduction
Data vs. information:
What is the difference?
•What is data? • What is information?
• Information is data that have
• Data is raw, unorganized facts been organized and
that need to be processed communicated in a coherent and
• Information science defines meaningful manner.
data as unprocessed • Data is converted into
information. information, and information is
• Ex: Each student’s test score is converted into knowledge.
one piece of data. • Knowledge; information
evaluated and organized so that it
can be used purposefully.
• Ex: The class average score is the
information that can be
concluded from the given data
What is a database

A database is any organized collection of data.

A database is a collection of related information.


For example, a phone book is a database of names, addresses
and phone numbers.

A data file is a single disk file that stores related information on


a hard disk or floppy diskette.
For example, a phone book database would be stored in a
single data file. 
Some examples of databases you may encounter in your daily
life are:

• a telephone book
• airline reservation system
• motor vehicle registration records
• files on your computer hard drive
Why do we need a database?

• Keep records of :
• Clients
• Staff
• Volunteers
• To keep a record of activities;
• Keep sales records;
• Develop reports;
• Perform research
• Longitudinal tracking
What is the ultimate purpose of a database
management system?

Is to transform

Data Information Knowledge Action


What Is a DBMS?
A very large, integrated collection of data and a set of programs to
access those data.
Supports efficient access to very large amounts of data.
Supports concurrent access to very large amounts of data.
Example: bank and its ATM machines
Supports secure, atomic access to very large amounts of data.

The collection of data , usually referred to as the database.

A Database Management System (DBMS) is a software package


designed to store and manage databases.

Management of data involves both defining structures for storage


of information and provide mechanism for the manipulation of
information .
Why Use a DBMS?
The goal of a DBMS is to provide an environment that is both
convenient and efficient to use in

Retrieving information from the database.


Storing information into the database.
 Data independence and efficient access.
 Reduced application development time.
 Data integrity and security.
 Uniform data administration.
 Concurrent access, recovery from crashes.
Databases are used…

To manipulate information so that it can be


sorted and/or searched.

To make record keeping and tracking fast and


efficient.
Database System Applications
• Databases are widely used some representative applications:
• Banking:
For customer information, accounts, and loans, and banking
transactions.
• Airlines:
For reservations and schedule information.
• Universities:
For student information, course registrations, and grades.
• Credit card transactions:
For purchases on credit cards and generation of monthly
statements.
• Telecommunication:
For keeping records of calls made, generating monthly bills, maintaining balances on
prepaid calling cards, and storing information about the communication networks.
• Finance:
For storing information about holdings, sales, and purchases of financial instruments
such as stocks and bonds.
• Sales:
For customer, product, and purchase information.
• Manufacturing:
For management of supply chain and for tracking production of items in factories,
inventories of items in warehouses/stores, and orders for items.
• Human resources:
For information about employees, salaries, payroll taxes and benefits, and for
generation of paychecks.
Who uses databases?

•Almost everyone:
•Business
•Doctors
•Teachers
•Students
Purpose of Database System
1.let's look at a typical file-processing system" supported by a
conventional operating system.

• The application is a savings bank:


• Savings account and customer records are kept in permanent
system files.
• Application programs are written to manipulate files to perform
the following tasks:-
• Debit or credit an account.
• Add a new account.
• Find an account balance.
• Generate monthly statements.  
2.Development of the system proceeds as follows:

•  New application programs must be written as the need arises.

•  New permanent files are created as required.

• but over a long period of time files may be in different


formats, and
•  Application programs may be in different languages.
• Drawbacks of typical file processing system over Database
Management System-
• Data redundancy and inconsistency
• Same information may be duplicated in several places.
• All copies may not be updated properly.
• Difficulty in accessing data
• May have to write a new application program to satisfy an unusual request.
• E.g. find all customers with the same postal code.
• Could generate this data manually, but a long job...
• Data isolation
• Data in different files.
• Data in different formats.
• Difficult to write new application programs.
• Multiple users
• Want concurrency for faster response time.
• Need protection for concurrent updates.
• E.g. two customers withdrawing funds from the same account at the same time - account has
$500 in it, and they withdraw $100 and $50. The result could be $350, $400 or $450 if no
protection.
• Security problems
• Every user of the system should be able to access only the data they are permitted to see.
• E.g. payroll people only handle employee records, and cannot see customer accounts; tellers
only access account data and cannot see payroll data.
• Difficult to enforce this with application programs.
• Integrity problems
• Data may be required to satisfy constraints.
• E.g. no account balance below $25.00.
• Again, difficult to enforce or to change constraints with the file-processing approach.

• These problems and others led to the development of database


management systems.
Data Abstraction
• A database system is a collection of interrelated data and set of
programs that allow users to access and modify these data.

The major purpose of a database system is to provide users


with an abstract view of the system.

The system hides certain details of how data is stored and


maintained .

Complexity should be hidden from database users.


There are several levels of abstraction:

1. Physical Level:

•  How the data are stored.

•  E.g. index, B-tree, hashing.

•  Lowest level of abstraction.

•  Complex low-level structures described in detail.


2. Conceptual Level:

•  Next highest level of abstraction.

• Describes what data are stored.

•  Describes the relationships among data.

•  Database administrator level.


3.View Level:

•  Highest level.

•  Describes part of the database for a particular group of users.

•  Can be many different views of a database.

•  E.g. tellers in a bank get a view of customer accounts, but not


of payroll data.
Three level of Data abstraction

View 1 View 2 View n

Conceptual Level

Physical Level
The Elements of a Database

• The database schema


• Schema objects
• Indexes
• Tables
• Fields and columns
• Records and rows
The database schema

•A schema is quite simply a group of related objects in a


database.
•Within a schema, objects that are related have
relationships to one another.

Figure - Collection of objects that comprise a database schema.


Table
A table is the primary unit of physical storage for data in a database.

 When a user accesses the database , a table is usually referenced for


the desired data.

 Multiple tables might comprise a database , therefore a relationship


might exist between tables.

Figure illustrates tables in a schema. Each table in the figure is related


to at least one other table. Some tables are related to multiple tables.

                                                                                                                                       

Figure - Database tables and their relationships.


Columns
•A column, or field, is a specific category of information that exists
in a table.
•A column is to a table what an attribute is to an entity.
•In other words, when a business model is converted into a database
model, entities become tables and attributes become columns.
•A column represents one related part of a table and is the smallest
logical structure of storage in a database.
•Each column in a table is assigned a data type.
•The assigned data type determines what type of values that can
populate a column.
•When visualizing a table, a column is a vertical structure in the
table that contains values for every row of data associated with a
particular column.
A Field
• (category) is the place where one item of
information is recorded; the smallest part of the
database.
Fields
In Figure , columns within the Customers table are shown.

Each column is a specific category of information.

 All of the data in a table associated with a field is called a


column.

Figure- Columns in a database table.


Rows
•A row of data is the collection of all the columns in a table
associated with a single occurrence.
•Simply speaking, a row of data is a single record in a table.
•For example, if there are 25,000 book titles with which a
bookstore deals, there will be 25,000 records, or rows of data, in
the book titles table once the table is populated.
•The number of rows within the table will obviously change as
books' titles are added and removed.

Figure - Row of data in a database table.


A RECORD
• One row is a one record.

Record
Instances and Schemas
• Instances :-Instances is collection of the Information store in the database
at a particular moment is called Instances.

• It is also called database state.

• The term instance is typically used to describe a complete database


environment, including the RDBMS software, table structure, stored
procedures and other functionality.

• It is most commonly used when administrators describe multiple


instances of the same database.

• Examples: An organization with an employees database might have three


different instances: production (used to contain live data), pre-production
(used to test new functionality prior to release into production) and
development (used by database developers to create new functionality).
• Schemas:-
• The description of data base is called database schema.

• Overall design of data base.

• Schema contains 'No of records + Type of data + No of


attributes.

• Description of data at some level.

• Each level has its own schema

• It is specified during database design and is not expected to


change frequently.

• A displayed schema is called schema diagram.


Schema diagram for UNIVERSITY database

schema construct

Known data:
name of record types, data items
Example: University Database
Conceptual schema:

Students(sid: string, name: string, login: string, age: integer, gpa:real)

Courses(cid: string, cname:string, credits:integer)

Enrolled(sid:string, cid:string, grade:string)

Physical schema:

Relations stored as unordered files.

Index on first column of Students.

External Schema (View):

Course_info(cid:string, enrollment:integer)

CS542Students(sid: string, grade:string)


Database Languages
• A database system provides a Data-Definition Language
(DDL) to specify the database schema.

• A Data-Manipulation Language (DML) to express


database queries and updates.

• DDL and DML are not two separate languages ,instead


they simply and widely called as SQL language.
Data Definition Language (DDL)
Used to specify a database scheme as a set of definitions expressed in a DDL.

The DDL , just like any programming languages , gets an input some
instructions and generates some output.

The output of DDL is placed in the data dictionary.

The data directory contains metadata (data about data).

The data dictionary is considered to be a special type of table, which can only
be accessed and updated by the database system itself.

A database system consults the data dictionary before reading or modifying


actual data.
•The data values stored in database must satisfy certain
consistency constraints.

•E.g.-suppose the balance on an account should not fall


below $1000.

•The DDL provides facilities to specify such


constraints.

•The database systems check these constraints every


time the database updated.
• Domain Constraints –
• A domain of possible values must be associated with every
attributes (e.g. integer type, character type, date type).
• Domain constraints are the most elementary form of integrity
constraints.
• Attributes are tested easily by the system whenever a new data
item is inserted into the database.

• Referential Integrity –
• There are cases where we wish to ensure that a value that
appears in relation for a given set of attributes also appears for
a certain set of another relation.
• Database modifications can cause violations of referential
integrity.
• When a referential integrity constraints is violated , the normal
procedure is to reject the action that caused the violation.
• Assertions –
• An assertion is any condition that the database must always
satisfy.
• Domain constraints and referential integrity constraints are
special forms of assertion.
• There are many constraints that we cannot express by using
only these special forms.
• E.g. “Every loan has at least one customer who maintains an
account with minimum balance of $10,000” must be expressed
as an assertion.
• Authorization –
• We may want to differentiate among the users as far as the type
of access they permitted on various data values in database.
• These differentiation are expressed in terms of authorization.
• E.g. Read authorization, insert authorization , delete
authorization , update authorization
Data Manipulation Language (DML)
• A data manipulation language (DML) is a language that enables
users to access or manipulate data.
• The goal is to provide efficient human interaction with the
system.
Data Manipulation is:

• Retrieval of information from the database

• Insertion of new information into the database

 
• Deletion of information in the database

 
• Modification of information in the database
There are two types of DML: -

• Procedural DMLs – require a user to specify what data are


needed and how to get those that data.
• Procedural languages are used in the traditional programming
that is based on algorithms or a logical step by step process for
solving a problem.

• non procedural DMLs –require a user to specify what data are


needed without specifying how to get those data.
• Non procedural languages allows users and professional
programmers to specify the results they want without specifying
how to solve the problem
•Query:-
• in general , a query is a question.
• In computers , what a user of a search engine or database enter
is sometime called the Query.
• A query is a statement requesting the retrieval of information.
• Database query can be either a select query or an action query.
•Query Language:-
• Language used to interact with databases are called query
languages, of which SQL is well known standard.
• The portion of a DML that involves information retrieval is
called a query language.
• It is a common practice to use the terms query language and
data manipulation language synonymously.
Data Models
•Data model is a collection of concepts that can be used to describe the
structure of a database.
•Data models are a collection of conceptual tools for describing data, data
relationships, data semantics(relation between stored data and real world) and
data constraints
•Business Model is a plan implemented by a company to generate revenue and
make a profit from operations
•The model includes the components and functions of the business , as well as
the revenues it generates and the expenses it incurs.
• There are three different Models

Object-based Logical Models.


 
Record-based Logical Models.
 
Physical Data Models.
Object-based Logical Models
Object-based logical models:
The object based models use the concepts of entities or objects and
relationships among them rather than the implementation based
concepts such as records used in the record based models
• Describe data at the conceptual and view levels.
• Provide fairly flexible structuring capabilities.
• Allow one to specify data constraints explicitly.
such models,
• Entity-relationship model.
• Object-oriented model
• Binary model.
• Semantic data model
• Functional data model
The E-R Model
• An entity-relationship model (ERM) is an abstract and
conceptual representation of data.

• The entity-relationship model (or ER model) is a way of


graphically representing the logical relationships of entities (or
objects) in order to create a database.

• Entity-relationship modeling is a database modeling method,


used to produce a type of conceptual schema or semantic data
model of a system.
• Diagrams created by this process are called entity-relationship
diagrams, ER diagrams, or ERDs.

• The entity-relationship model is based on a perception of the


world as consisting of a collection of basic objects (entities and
relationships among these objects.)

• The ER model was developed to facilitate database design by


allowing specification of an enterprise schema that represents
the overall logical structure of database.
Entity:-

• An entity is a distinguishable object that exists.


• Entity is a person , place , thing or concept about which data
can be collected
• Example: House ,Car , Employee

• Each entity has associated with it a set of attributes describing


it.
• E.g. number and balance form an account entity

• Entities have attributes


• Example: people have names and addresses
Entity
Entity Sets
• An entity set is a set of entities of the same type that share the
same properties.
• Entity set is collection or set all entities of a particular entity
type at any point of time.
• Example: set of all persons, companies, trees, holidays
• Entity Sets customer and loan
customer-id customer- customer- customer- loan- amount
name street city number
 John
 Smith
 Sana
 Lee

Student entity set has four entities john, smith , sana , Lee
Attributes
• An entity is represented by a set of attributes, that is
descriptive properties possessed by all members of an
entity set.

Example:
customer = (customer-id, customer-name,
customer-street, customer-city)

loan = (loan-number, amount)


• Domain – the set of permitted values for each attribute
Attributes of
Product

Attributes of
Supplier
Attributes
Attribute types:-
Simple and composite attributes.
Single-valued and multi-valued attributes
 E.g. multivalued attribute: phone-numbers
Derived attributes
 Can be computed from other attributes
 E.g. age, given date of birth

• Composite Attributes
Relationship:-
 A relationship is an association among several entities.
 e.g. A cust_acct relationship associates a customer with each
account he or she has.
 The set of all relationships of the same type is called the
relationship set.

Example:
Hayes depositor A-102
customer entity relationship set account entity

A relationship set is a mathematical relation among n  2


entities, each taken from entity sets
{(e1, e2, … en) | e1  E1, e2  E2, …, en  En}
where (e1, e2, …, en) is a relationship

Example: (Hayes, A-102)  depositor


Relationship Set borrower
Relationship Sets (Cont.)
• An attribute can also be property of a relationship set.

• For instance, the depositor relationship set between entity sets


customer and account may have the attribute access-date
Degree of a Relationship Set

• Refers to number of entity sets that participate in a relationship set.


• Relationship sets that involve two entity sets are binary (or degree
two). Generally, most relationship sets in a database system are
binary.
• Relationship sets may involve more than two entity sets.

E.g. Suppose employees of a bank may have jobs (responsibilities) at multiple


branches, with different jobs at different branches. Then there is a ternary
relationship set between entity sets employee, job and branch

• Relationships between more than two entity sets are rare. Most
relationships are binary.
Ternary relationship set

Branch
city
Branch
Name Assets

Branch
Social
security Street
Account
Balance
No
Cust city
Name

Customer Job Account


Mapping Cardinalities
• Express the number of entities to which another entity can be
associated via a relationship set.
• Most useful in describing binary relationship sets.
• For a binary relationship set the mapping cardinality must be
one of the following types:
One to one
One to many
Many to one
Many to many
Mapping Cardinalities

One to one One to many

Note: Some elements in A and B may not be mapped to any elements in the
other set
Mapping Cardinalities

Many to one Many to many


Note: Some elements in A and B may not be mapped to any elements in the other
set
• The one to one relationship 1:1
• Examples:
• 1. In South Africa a person can have one and only one Identity
Document.  Also, a specific Identity Document can belong to one
and only one person.

• 2. A voter can cast only one vote in an election. 


• A ballot paper can belong to only one voter.
• So there will be a 1:1 relationship between a Voter and a Ballot
Paper.
The one to many or many to one relationship 1:m or m:1
• Examples:
1.  Master-detail.  You have a master (or header) record with many detail records.  For
example an order.  There will be a master record with the order date, person placing the
order, etc.  And then detail records of everything ordered.  The master record will have
many detail, and the detail will have only 1 master.

2. Supervisor-subordinates.  A supervisor will have one or many subordinates.  A


subordinate will have only 1 manager.

3. Division- department.  A division will have one or many departments.  A department will
belong to only 1 division.

4. A person can own more than one car.  A car can only have one owner.  So Owner to Car
will be a one to many or 1:M relationship.
5. A person can buy one or many movie tickets.  A ticket will belong to only one person.
• The many to many relationship m:m
• Examples:
• 1. Student - professor.  A student will have one or more
professors.  The same professor will have lots of students.

• 2. Partent - child.  A parent can have zero, one, or many


children. A child will have more than one (biological) parent.

• 3. At a hospital a patient will be assigned to a coupled of


nurses.  A specific nurse will be assigned to 1 or many patients.

• 4. A student will have lots of subjects and the same subject can
be taken by lots of students
Database Modeling and Implementation
Process

Ideas ER Design Relational Schema

Relational DBMS
Implementation
Keys
The key is defined as the column or attribute of the database
table.
The following are the various types of keys available in the
DBMS system.
Super Key –
An attribute or a combination of attribute that is used to
identify the records uniquely is known as Super Key.
A table can have many Super Keys.
E.g. of Super Key
1 ID
2 ID, Name
3 ID, Address
4 ID, Department_ID
5 ID, Salary
6 Name, Address
7 Name, Address, Department_ID
………… So on as any combination which can identify the records
uniquely will be a Super Key.
• Candidate Key –
• It can be defined as minimal Super Key or irreducible Super Key.
• In other words an attribute or a combination of attribute that
identifies the record uniquely but none of its proper subsets can
identify the records uniquely.

• E.g. of Candidate Key

• Employee (‘ID’ , ‘Name’ ,’Address’)

• For above table we have only two Candidate Keys


• ‘ID’ Key can identify the record uniquely.
• similarly combination of Name and Address can identify the record
uniquely.
• Neither Name nor Address can be used to identify the records
uniquely .
• Primary Key –
• A Candidate Key that is used by the database designer for
unique identification of each row in a table is known as Primary
Key.
• A Primary Key can consist of one or more attributes of a table.

• E.g. of Primary Key -


• Customer
• CustomerNo FirstName LastName
• 1 Sally Thompson
• 2 Sally Henderson
• 3 Harry Henderson
• 4 Sandra Wellington
• For example, in the table above, CustomerNo is the primary
key.
• Foreign Key –
• A foreign key is an attribute or combination of attribute in one base table
that points to the candidate key (generally it is the primary key) of
another table.
• The purpose of the foreign key is to ensure referential integrity of the data
i.e. only values that are supposed to appear in the database are permitted.
• for example, OrderNo is the primary key of the table ORDERS below
and CustomerNo is a foreign key that points to the primary key in the
CUSTOMERS table.
• ORDERS
OrderNo EmployeeNo CustomerNo Supplier Price Item
• 1 1 42 Harrison $235 Desk
• 2 4 1 Ford $234 Chair
• 3 1 68 Harrison $415 Table
• 4 2 112 Ford $350 Lamp
• 5 3 42 Ford $234 Chair
• 6 2 112 Ford $350 Lamp
• 7 2 42 Harrison $235 Desk
• Composite Key –
• If we use multiple attributes to create a Primary Key then that
Primary Key is called Composite Key (also called a Compound
Key or Concatenated Key).
• E.g. of Composite Key, if we have used “Name, Address” as a
Primary Key then it will be our Composite Key.
• Alternate Key –
• Alternate Key can be any of the Candidate Keys except for the
Primary Key.
• E.g. of Alternate Key is “Name, Address” as it is the only other
Candidate Key which is not a Primary Key.
• Secondary Key –
• The attributes that are not even the Super Key but can be still used
for identification of records (not unique) are known as Secondary
Key.
• E.g. of Secondary Key can be Name, Address, Salary,
Department_ID etc. as they can identify the records but they might
not be unique
Data Independence
• The ability to modify a scheme definition in one level without
affecting a scheme definition in a higher level is called data
independence.

• There are two kinds:

• Physical data independence


• The ability to modify the physical scheme without causing
application programs to be rewritten.
• This approach has to do with altering the organization or
storage procedures related to the data, rather than modifying the
data itself.
• Logical data independence

• The ability to modify the conceptual scheme without causing


application programs to be rewritten – Usually done when
logical structure of database is altered.

• Logical data independence makes it possible to change the


structure of the data independently of modifying the
applications or programs that make use of the data.

• There is no need to rewrite current applications as part of the


process of adding to or removing data from then system.
Database Manager
The database manager is a program module which provides
the interface between the low-level data stored in the database
and the application programs and queries submitted to the
system.
The goal of the database system is to simplify and facilitate
access to data.
The database manager module is responsible for:-

 Interaction with the file manager:-


 Storing raw data on disk using the file system usually provided
by a conventional operating system.

 The database manager must translate DML statements into


low-level file system commands (for storing, retrieving and
updating data in the database).
Integrity enforcement:-
Checking that updates in the database do not violate
consistency constraints (e.g. no bank account balance below
$25).

Security enforcement:-
Ensuring that users only have access to information they are
permitted to see.

Backup and recovery:-


 Detecting failures due to power failure, disk crash, software
errors, etc., and restoring the database to its state before the
failure.

Concurrency control:-
 Preserving data consistency when there are concurrent users.
 
Database Administrator
• The database administrator is a person having central control
over data and programs accessing that data.

• Duties of the database administrator include:-

• Scheme definition:-
• The creation of the original database scheme.
• This involves writing a set of definitions in a DDL , compiled
by the DDL compiler into a set of tables stored in the data
dictionary.
• Storage structure and access method definition:-
• writing a set of definitions translated by the data storage and definition language compiler.
• Scheme and physical organization modification: -
• writing a set of definitions used by the DDL compiler to generate modifications to appropriate
internal system tables (e.g. data dictionary).
• This is done rarely, but sometimes the database scheme or physical organization must be modified.

• Granting of authorization for data access:-


• Granting different types of authorization for data access to various users .

• Integrity constraint specification:-


• Generating integrity constraints.
• These are consulted by the database manager module whenever
updates occur.
Database Users
The database users fall into several categories: -
 Application programmers :-

 Are computer professionals interacting with the system through DML calls embedded in a program
written in a host language (e.g. C, Pascal).

 Sophisticated users:-

 Interact with the system without writing programs.


 They form requests by writing queries in a database query language.
These are submitted to a query processor that breaks a DML
statement down into instructions for the database manager
module.
Specialized users:-

Are sophisticated users writing special database application


programs.
These may be CAD systems, knowledge-based and expert
systems, complex data systems (audio/video), etc.

 Naive users:-

 Are unsophisticated users who interact with the system by


using permanent application programs (e.g. automated teller
machine).
Overall System Structure
• Database systems are partitioned into modules for different
functions.
• Some functions (e.g. file systems) may be provided by the
operating system.

•  Components include:-

File manager :-
manages allocation of disk space and data structures used to
represent information on disk.

• Database manager :-
• The interface between low-level data and application programs
and queries.
• Query processor :-
• Translates statements in a query language into low-level
instructions the database manager understands.

• DML precompiler :-
• Converts DML statements embedded in an application program
to normal procedure calls in a host language.
• The precompiler interacts with the query processor.

• DDL compiler :-
• Converts DDL statements to a set of tables containing metadata
stored in a data dictionary.
• In addition, several data structures are required for physical
system implementation :-

• Data files :-
• Store the database itself.

•  Data dictionary :-
• Stores information about the structure of the database. It is used
heavily.
• Great emphasis should be placed on developing a good design
and efficient implementation of the dictionary.

Indices :-
Provide fast access to data items holding particular values.
Overall System Structure
Constraints
• Constraints are used to limit the type of data that can go into a
table.
• Constraints can be specified when a table is created (with the
CREATE TABLE statement) or after the table is created (with
the ALTER TABLE statement).

• We will focus on the following constraints:


NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
SQL NOT NULL Constraint
• The NOT NULL constraint enforces a column to NOT accept NULL
values
• The NOT NULL constraint enforces a field to always contain a value.
• This means that you cannot insert a new record, or update a record
without adding a value to this field.
• The following SQL enforces the "P_Id" column and the "LastName"
column to not accept NULL values:
• CREATE TABLE Persons
• (
• P_Id int NOT NULL,
• LastName varchar(255) NOT NULL,
• FirstName varchar(255),
• Address varchar(255),
• City varchar(255)
• )
SQL UNIQUE Constraint
• The UNIQUE constraint uniquely identifies each record in a database table.
• The UNIQUE and PRIMARY KEY constraints both provide a guarantee for
uniqueness for a column or set of columns.
• A PRIMARY KEY constraint automatically has a UNIQUE constraint
defined on it.
• Note that you can have many UNIQUE constraints per table, but only
one PRIMARY KEY constraint per table.
• The following SQL creates a UNIQUE constraint on the "P_Id" column
when the "Persons" table is created:
• CREATE TABLE Persons
• (
• P_Id int NOT NULL UNIQUE,
• LastName varchar(255) NOT NULL,
• FirstName varchar(255),
• Address varchar(255),
• City varchar(255)
• )
• SQL UNIQUE Constraint on ALTER TABLE

• To create a UNIQUE constraint on the "P_Id" column when the


table is already created, use the following SQL:

• ALTER TABLE Persons


ADD UNIQUE (P_Id)
SQL PRIMARY KEY Constraint
• The PRIMARY KEY constraint uniquely identifies each record in a database table.
• Primary keys must contain unique values.
• A primary key column cannot contain NULL values.
• Each table should have a primary key, and each table can have only ONE primary
key.

• SQL PRIMARY KEY Constraint on CREATE TABLE

• The following SQL creates a PRIMARY KEY on the "P_Id" column when the
"Persons" table is created:
• CREATE TABLE Persons
• (
• P_Id int NOT NULL PRIMARY KEY,
• LastName varchar(255) NOT NULL,
• FirstName varchar(255),
• Address varchar(255),
• City varchar(255)
• )
• SQL PRIMARY KEY Constraint on ALTER TABLE

• To create a PRIMARY KEY constraint on the "P_Id" column


when the table is already created, use the following SQL

• ALTER TABLE Persons


ADD PRIMARY KEY (P_Id);

• To DROP a PRIMARY KEY Constraint

• To drop a PRIMARY KEY constraint, use the following SQL:

• ALTER TABLE Persons


DROP PRIMARY KEY
SQL FOREIGN KEY Constraint
• FOREIGN KEY in one table points to a PRIMARY KEY in
another table.
Primary key
• Look at the following two tables:
Primary key
• The "Persons" table:
P_Id LastName FirstName Address City
1 Nilsen Johan Bakken 2 Stavanger
2 Hansen Ola Timoteivn 10 Sandnes
3 Svendson Tove Borgvn 23 Sandnes

O_Id OrderNo P_Id

1 77895 3

• The "Orders" table: 2 44678 3


Foreign key
3 22456 2

4 24562 1
• Note that the "P_Id" column in the "Orders" table points to the
"P_Id" column in the "Persons" table.

• The "P_Id" column in the "Persons" table is the PRIMARY KEY


in the "Persons" table.

• The "P_Id" column in the "Orders" table is a FOREIGN KEY in


the "Orders" table.

• The FOREIGN KEY constraint is used to prevent actions that


would destroy links between tables.

• The FOREIGN KEY constraint also prevents that invalid data


form being inserted into the foreign key column, because it has to
be one of the values contained in the table it points to.
• SQL FOREIGN KEY Constraint on CREATE TABLE

• The following SQL creates a FOREIGN KEY on the "P_Id"


column when the "Orders" table is created

• CREATE TABLE Orders


• (
• O_Id int NOT NULL PRIMARY KEY,
• OrderNo int NOT NULL,
• P_Id int REFERENCES Persons
• )

• SQL FOREIGN KEY Constraint on ALTER TABLE

• To create a FOREIGN KEY constraint on the "P_Id" column when


the "Orders" table is already created, use the following SQL:
• ALTER TABLE Orders
• ADD FOREIGN KEY (P_Id)
• REFERENCES Persons(P_Id)
SQL CHECK Constraint
• The CHECK constraint is used to limit the value range that can
be placed in a column.

• If you define a CHECK constraint on a single column it allows


only certain values for this column.

• If you define a CHECK constraint on a table it can limit the


values in certain columns based on values in other columns in
the row.
• SQL CHECK Constraint on CREATE TABLE

• The following SQL creates a CHECK constraint on the "P_Id"


column when the "Persons" table is created.

• The CHECK constraint specifies that the column "P_Id" must


only include integers greater than 0.

• CREATE TABLE Persons


•(
• P_Id int NOT NULL CHECK (P_Id>0),
• LastName varchar(255) NOT NULL,
• FirstName varchar(255),
• Address varchar(255),
• City varchar(255)
•)
• To allow naming of a CHECK constraint, and for defining a
CHECK constraint on multiple columns, use the following SQL
syntax:

• CREATE TABLE Persons


•(
• P_Id int NOT NULL,
• LastName varchar(255) NOT NULL,
• FirstName varchar(255),
• Address varchar(255),
• City varchar(255),
• CONSTRAINT chk_Person CHECK (P_Id>0 AND city=‘Pune)
•)
• SQL CHECK Constraint on ALTER TABLE

• To create a CHECK constraint on the "P_Id" column when the


table is already created, use the following SQL:

• ALTER TABLE Persons


ADD CHECK (P_Id>0)
SQL DEFAULT Constraint
• The DEFAULT constraint is used to insert a default value into a column.
• The default value will be added to all new records, if no other value is
specified

• SQL DEFAULT Constraint on CREATE TABLE


• The following SQL creates a DEFAULT constraint on the "City"
column when the "Persons" table is created:
• CREATE TABLE Persons
• (
• P_Id int NOT NULL,
• LastName varchar(255) NOT NULL,
• FirstName varchar(255),
• Address varchar(255),
• City varchar(255) DEFAULT ‘Pune‘
• )
• The DEFAULT constraint can also be used to insert system
values, by using functions like GETDATE():

• CREATE TABLE Orders


• (
• O_Id int NOT NULL,
• OrderNo int NOT NULL,
• P_Id int,
• OrderDate date DEFAULT GETDATE()
• )
• SQL DEFAULT Constraint on ALTER TABLE

• To create a DEFAULT constraint on the "City" column when the


table is already created, use the following SQL:
• ALTER TABLE Persons
• ALTER COLUMN City SET DEFAULT ‘Pune'
• To DROP a DEFAULT Constraint

• To drop a DEFAULT constraint, use the following SQL:

• ALTER TABLE Persons


ALTER COLUMN City DROP DEFAULT
Case Study

•MySQL Database
https://www.w3schools.in/
What is MySQL?
• MySQL is a database system used for developing web-based
software applications.
• MySQL used for both small and large applications.
• MySQL is a relational database management system (RDBMS).
• MySQL is fast, reliable, and flexible and easy to use.
• MySQL supports standard SQL (Structured Query Language).
• MySQL is free to download and use.
• MySQL was developed by Michael Widenius and David Axmark in
1994.
• MySQL is presently developed, distributed, and supported by
Oracle Corporation.
• MySQL Written in C, C++.
Main Features of MySQL
• MySQL server design is multi-layered with independent modules.
• MySQL is fully multithreaded by using kernel threads. It can
handle multiple CPUs if they are available.
• MySQL provides transactional and non-transactional storage
engines.
• MySQL has a high-speed thread-based memory allocation system.
• MySQL supports in-memory heap table.
• MySQL Handles large databases.
• MySQL Server works in client/server or embedded systems.
• MySQL Works on many different platforms.

https://www.w3schools.in/
Who uses MySQL

• Some of the most famous websites like Facebook,


Wikipedia, Google (not for search), YouTube, Flickr.
• Content Management Systems (CMS) like WordPress,
Drupal, Joomla, phpBB etc.
• A large number of web developers worldwide are using
MySQL to develop web applications.

https://www.w3schools.in/
• MySQL is a very popular, open source DBMS
• MySQL databases are relational
• Officially pronounced “my Ess Que Ell” (not my sequel).
• Handles very large databases; very fast performance;
reliable.
• MySQL is compatible with standard SQL
• Why are we using MySQL?
• Free (much cheaper than Oracle!)
• Each student can install MySQL locally.
• Multi-user access to a number of databases offered
• Easy to use Shell for creating tables, querying tables, etc.
• Easy to use with Java JDBC
• MySQL is frequently used by PHP and Perl
History of MySQL
• Founded and developed by David Axmark, Allan
Larsson, and Michael “Monty” Widenius
• Named after Monty's daughter, My
• Written in C and C++
• Works on many different platforms
Thank You!!!

You might also like