0% found this document useful (0 votes)
19 views133 pages

6.database Systems

Uploaded by

Tanatswa
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)
19 views133 pages

6.database Systems

Uploaded by

Tanatswa
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/ 133

DATABASES

Form 5
OBJECTIVES
 Describe the file based
approach database systems
 Outline features of a DBMS
describe features of relational
database which address
limitations of a file based
approach
 Write SQL commands
develop interfaces and
queries using DBMS tools
 Access data in a database
through a high level language
 Design database applications
using Entity relationship
diagrams (ERDs)
 Convert ERDs to relational
databases schema in standard
normal form
 Normalise database tables up
to second normal form
- A database is a single organised collection of structured
and related data, stored with minimum duplication of data
items so as to provide consistent and controlled data within
an organisation.
- Databases can be accessed using different application
software.
- Data stored in databases can be accessed by all system
users, but with different access rights.
- Databases are designed to meet the information needs of
an organisation.
- Database operations may include addition of new
records, deletion of unwanted records, amendments
to existing records, creation of relationships between
files and removal or addition of fields of files.
- Databases ensure controlled redundancy since
redundancy cannot be wholly eliminated.
File Based Approach Database
Systems
- File based Approach is a traditional approach
of collecting and storing data In which data is
stored in files with each unit of organization
having its own files and each file having a
specific set of programs that manipulate the
data in that file.
The early days of computerized data processing, an organizational
data was duplicated in different files for the use of individual
departments eg Personnel department would hold details on name,
address and qualifications of each employee, while payroll
department would hold detals on name, surname, address and
salary of each employee.
Each department has its own set of application programs to
process the data in files.
This led to problems such as data redundancy which cane as a
result of duplication of data,
Duplication of data
Duplication of data
- The same data is duplicated in many files e.g. in the
personnel department along with a lot of other data kept
in the sales department.
- Another problem which came as a result of this
traditional file is inconsistency of data eg address was
updates on one file and not all other files e.g. in the
personnel file and not the payroll file and hence the next
pay slip will be send to the old address which is wrong.
- Another problem was that data was not shareable.
Database Approach Database Systems
- In attempt to solve the above problems mentioned, the data
from different departments was centralized in a common pool
so that all applications can have access to the same sort of data.
- Although this solves problems of duplication and inconsistency
it introduces few problems such as:
- Unproductive maintenance
- Programs were still depended on structure of the data so that
one department needed to add a new field to a particular file and
all programmes accessing that file need to be changed.
- The problem of security, all data in the database even
confidential or commercially sensitive was accessible by all
applications.
Types of databases (Database Models)
These include relational, hierarchical, network databases and
Object oriented databases.
1. Relational databases:
- These are database that organises data in a table format,
consisting of related data in another file, allowing users to link
the files.
- A table is collection of records stored using rows and column
structure.
- Each table is called a relation. A relation is a table with
columns and rows.
- It only applies to logical structure of the database, not the
- Each column represents an attribute (characteristic or field). Attribute is a
named column of a relation. It corresponds to a characteristic of an entity.
They are also called fields.
- Each row represents a record, as shown below.
- Degree is the number of attributes in a relation.
- Cardinality is the number of tuples in a relation
- Each cell of relation contains exactly one atomic (single) value.
- Each attribute has a distinct name.
- Values of an attribute are all from the same domain. Domain is the set of
allowable values for one or more attributes.
- Each tuple is distinct; there are no duplicate tuples.
- Order of attributes has no significance.
- Order of tuples has no significance, theoretically
- Relational databases organize data in a flexible manner.
- They are also simple to construct
- They are easy to use; Easier database design,
implementation, management.
- Ensures structural independence
- Ensures adhoc query capability with SQL
Disadvantages
o Substantial hardware and system software overhead
o May promote “islands of information” problems
o However, it may be difficult to come up with
relationships.
Database Keys:
 A simple key contains a single attribute.
 A composite key is a key that contains more than one
attribute.
 A candidate key is an attribute (or set of attributes) that
uniquely identifies a row. A candidate key must possess the
following properties:
o Unique identification - For every row the value of the
key must uniquely identify that row.
o Non redundancy - No attribute in the key can be
discarded without destroying the property of unique
identification.
 Super key: An attribute or a set of attributes
that uniquely identifies a tuple within a relation. A
super key is any set of attributes that uniquely
identifies a
row. A super key differs from a candidate key in
that it does not require the non-redundancy
property.
 Primary key: It is a candidate key that is used
to identify a unique (one) record from a relation. A
candidate key which is selected as the
principal unique identifier. Every relation
must contain a primary key. The primary
key is usually the key selected to identify a
row when the database is physically
implemented. For example, a part number
is selected instead of a part description
 Foreign key: A primary key in one file that is used/found in
another file. Foreign key is set of fields or attributes in one
relation that is used to “refer” to a tuple in another relation. Thus
it is a filed in one table but also used as a primary key in another
table.
 Secondary Key: A field used to identify more than one record
at a time, e.g. a surname.

Attribute: A characteristic of a record, e.g. its surname, date of


birth.
Entity: any object or event about which data can be collected,
e.g. a patient, student, football match, etc.
2. Network (Distributed) Databases
It is whereby several computers on the network each hold part of the data
which can be shared among the networked computers (users). If data is not
available on a user’s computer, the user communicates with others on the
network to obtain it. Each computer creates its own backup of data resident on
it.
These databases have links that are used to express
relationships between different data items.
 They are based on the principle of linked lists
 Data is maintained by a single input.
 There is little duplication of data.
 There is no duplication of inputs.
 Linkages are more flexible.
 Many to many relationships to records are limited
Handles more relationship types
 Promotes database integrity
 Ensures data independence
However, the system has the following problems:
 Databases may run only on particular computer
systems
 System is more complex
 Lack of structural independence
3. Hierarchical database:
Is a database structure in which data is held in a tree structure, indicating
different levels of files within the system.
Records are subordinates to other records in a tree structure of database.
Records at the lower level holds more details than their father records
It promotes grandfather, father, and son relationship of records as illustrated
below.
 Each father file has one or more son files.
 Each son file has only one father file.
 There are no cross linkages of file records.
 Database security and integrity is ensured
 Complex implementation as it is difficult to access all
the files at one time.
 A lot of duplication exists in this type of database
structure
 Difficult to manage
 Implementation limitations (no M:N relationship)
An object is a collection of data, an identity, and a set
of operations sometimes called methods. An object
oriented database stores the data and methods as
objects that can be automatically retrieved and shared.
An object-oriented database combines database
capabilities with an object oriented analysis and design
which encompasses features like polymorphism,
inheritance and encapsulation. Objects are taken as
data.
Benefits
 OODBMS are faster than relational DBMS because data isn’t stored in
relational rows and columns but as objects. Objects have a many to many
relationship and are accessed by the use of pointers, which will be faster.
 OODBMS is that it can be reprogrammed without affecting the entire
system.
 Can handle complex data models and therefore is more superior than
RDBMS
Disadvantages
 Pointer-based techniques will tend to be slower and more difficult to
formulate than relational.
 Object databases lack a formal mathematical foundation, unlike the
relational model, and this in turn leads to weaknesses in their query
DBMS
- Is a complex layer of software used to develop and to maintain
the database and provides interface between the database and
application programs.
Features of Database Management Systems
a) Data Dictionary Management
- Data Dictionary: contains names and descriptions of every
data element in the database i.e. how data elements are related to
each other.
- Stores data in a consistent memory, reducing data redundancy.
- Data Languages: a Special language (Data Definition
Language) used to describe the characteristics of a data element
b) Data Storage Management
- DBMS Handles data storage in the database.
- Uses Teleprocessing monitors which is a software
that manages communication between the database
and remote terminals.
c) Data Transformation and Presentation
- DBMS provides options to transform data in
multiple formats & then present it to the appropriate
users.
d) Security Management
- DBMS provides security rules that can restrict
access to tables, schema & other database objects.
- Security Software: provides tools used to shield
the database from unauthorised access.
e) Backup And Recovery Management
- DBMS should be able to take backups and
provide methods to recover the lost data.
- Recovery and archiving system: these allow
data to be copied onto backups in case of
disaster
. f) Data Integrity Management
- DBMS makes use of primary keys to
make sure that data integrity is not affected
in any case.
- The information in database management
system occurs only once so chances of
duplicity are very less, thus maintaining
data integrity, data concurrency & data
g) Database Access Languages And Application
Programming Interfaces
- Use of Structured Query language to access
database. The query language provided by DBMS is
so easy to understand.
- Report writers: these are programs used to design
output reports without writing an algorithm in any
programming language.
Features Of Relational Database Which
Address Limitations of A File Based Approach
a) Program-Data Independence
- Data is independent of the programs that
accesses it, in the file-based system, the structure
of the data files is defined in the application
programs so if a user wants to change the
structure of a file, all the programs that access that
file might need to be changed as well.
- Relational databases is self-describing, ie.
Contains the database itself and also
metadata which defines and describes the
data and relationships between tables in the
database (DD).
- Therefore, one change is all that is needed
to change the structure of a file.
b) Support for multiple views of data
- A database supports multiple views of data, ie.
Subsets of the database, which is defined and
dedicated for particular users of the system.
- Multiple users in the system might have different
views of the system and each view might contain
only the data of interest to a user or group of users.
c) Sharing of data and multiuser system
- allow many users to access the same database at the
same time through use of concurrency control
strategies (features of a database that allow several
users access to the same data item at the same time)
- These strategies ensure that the data accessed are
always correct and that data integrity is maintained.
d) Control of data redundancy/ Eliminating data
redundancy
- Data need only be stored once and applications that
need data can access the data from the central database.
e) Data sharing
- allows for data sharing among employees
and others who have access to the system.
- gives users the ability to generate more
information from a given amount of data than
would be possible without the integration of
all the data, for an organization, within a
database system.
f) Enforcement of integrity constraints
- define and enforce certain constraints to
ensure that users enter valid information
and maintain data integrity.
- A database constraint is a restriction or
rule that dictates what can be entered or
edited in a table
- Database constraints like Data uniqueness
ensures that no duplicates are entered thus
ensuring consistence and integrity.
g) Restriction of unauthorized access
- Database management system provide a
security system to create and control different
types of user accounts and restrict unauthorized
access.
- Users of a database system are given different
access privileges e.g read-only access (i.e., the
ability to read a file but not make changes), or
read and write privileges, which is the ability to
both read and modify a file.
- Databases implement security through data
classification (i.e., data objects are given
classification levels and users are assigned
clearance levels) and data encryption
h) Data independence
- The system data descriptions or data describing data
(metadata) are separated from the application
programs.
- The database approach allows multiple application
programs to use the data concurrently and the data
can be accessed in several different ways (e.g.,
through applications processing, online query, and
report writing programs).
- The access can be quickly changed by modifying
i) Transaction processing
- Database management system
include concurrency control
subsystems which ensures that data
remains consistent and valid during
transaction processing even if several
users update the same information.
j) Backup and recovery facilities
- Database system provides for backing
up and recovering of data.
- If a computer system fails in the
middle of a complex update process, the
recovery subsystem is responsible for
making sure that the database is restored
to its original state.
k) Ease of maintenance.
- Because each data element is stored
only once, any additions, deletions, or
changes to the database are accomplished
easily.
l) Reduced storage costs.
- By eliminating redundant data, storage
space is reduced, resulting in associated
Relational Database Vs Flat File
Database Normalisation
- is the process of organising fields and
tables of a relational database to minimize
redundancy and dependency.
- is a process of organizing the data in
database to avoid data redundancy, insertion
anomaly, update anomaly & deletion
anomaly.
Data in a table is normalised to a specific form to
prevent possible occurrence of update anomalies,
basing on functional dependencies among the
attributes in the relation. It is done so as:
- To reduce duplication of data by storing each
record/data within the database only once
- To ensure that data stored in databases is
consistent.
- Produce controlled redundancies to link
tables
- To put data into a more flexible form that
is able to accurately accommodate change
- To avoid certain anomalies like updating,
insertion and deleting anomalies
- To allow users to make queries relating to
data stored in different tables
Normalization
1NF - First normal form
- A table is in 1NF if and only if an attribute
(column) of a table do not hold multiple values
i.e it should have only atomic values.
- All entries in a field must be of same kind and
each field must have a unique name, but the
order of the field (column) is irrelevant.
Suppose a company wants to store the names and contact details of its
employees. It creates a table that looks like this:
Two employees (Jon & Lester) are
having two mobile numbers so the
company stored them in the same field.
Therefore this table is not in 1NF as
“each attribute of a table must have
atomic (single) values”, the emp_mobile
values for employees Jon & Lester
To make the table complies with 1NF we should have the data like this:
2NF - Second normal form
 The table in 1NF will lead to too much
duplication of data, therefore a table will
be in second normal form (2NF) if and
only if it is in 1NF and every non-key
attribute is fully dependent on the primary
key i.e. there are no partial
dependencies.
 A table is in 2NF if is in 1NF (First
normal form) and no non-prime attribute is
dependent on the proper subset of any
candidate key of table.

**NB: An attribute that is not part of any


candidate/primary key is known as non-
prime/ non-key attribute.
Example: Suppose a school wants to store the data of
teachers and the subjects they teach. They create a table
that looks like this: Since a teacher can teach more than
one subjects, the table can have multiple rows for a same
teacher.

Candidate Keys: {teacher_id, subject}


Non prime attribute: teacher_age
The table is in 1 NF because each attribute
has atomic values. However, it is not in
2NF because non prime attribute
teacher_age is dependent on teacher_id
alone.
To put the table in 2NF we can break it in
two tables like this:
3NF - Third normal form
 A table is in Third Normal Form (3NF) if it
is in 2NF and has no transitive dependencies. A
transitive dependency is when an attribute is
indirectly functionally dependent on the key
(the dependency is through another nonkey
attribute), that is, all non-key elements are fully
dependent on the primary key.
 In other words a table is in 3NF
if it is in 2NF and for each
functional dependency X-> Y , X
is a super key of table and Y is a
prime attribute ( is a part of one of
the candidate keys) of table
Example: Suppose a company wants to store the complete address of each
employee, they create a table named employee_details that looks like this:
Super keys: {emp_id}, {emp_id,
emp_name}, {emp_id, emp_name,
emp_zip}…so on
Candidate Keys: {emp_id}
Non-prime attributes: all attributes except
emp_id are non-prime as they are not part
of any candidate keys. Here, emp_state,
emp_city & emp_district dependent on
And, emp_zip is dependent on emp_id that
makes non-prime attributes (emp_state,
emp_city & emp_district) transitively
dependent on super key (emp_id).
Therefore to put the table in 3NF we have to
break the table into two tables to remove the
transitive dependency:
Example 2
Database Applications Using Entity
Relationship Diagrams (ERDs)
An entity relationship model, also called an
entity-relationship (ER) diagram, is a
graphical representation of entities (which
will become your tables) and their
relationships to each other.
Entity: physical objects like person, patient
or events on which information or data is
being collected. It can also be an abstract
object like a patient record.
- An entity is something of interest to an
organisation about which data is to be held.
- - represents a table in a database
Attribute: individual data item within an entity;
e.g. date of birth, surname.
- This is a property or characteristic of an entity.
- An attribute or a column (simple) represents a
piece of data in the table, like an address, salary,
and date.
Relationship: links between two different
entities or relations (tables).
- a link or association between entities.
Relationship
This is a link or association between entities. Relationship
type is a meaningful association between entity types.
The examples of relationship types are:
– Teaches is the relationship type between LECTURER
and STUDENT.
– Buying is the relationship between VENDOR and
CUSTOMER.
– Treatment is the relationship between DOCTOR and
PATIENT
Types of Relationships
There are 3 types of relationships between 2
attributes which include:
a. One to one
Eg. A president can lead one country and a
contry has one president. A department in a
school has one HOD and this person leads only
one department.
b. One to many relationship
Eg. Relationship between mother and
children, mother can have many
children whilst children can have only
one mother.
One member and books in a library, a
club member can borrow many books.
Many to many relationship
Eg. Students and teachers, students with
many teachers and teachers with many
students.
-Relationship between students and course,
you can have many students doing the
course and have many courses done by
many students.
Converting ERDs to Relational Databases Schema in
Standard Normal Form
ER diagram represents the conceptual level of
database design meanwhile the relational schema is
the logical level for the database design. We will be
following the simple rules:
1. Entities and Simple Attributes:
- An entity within ER diagram is turned into a table.
You may preferably keep the same name for the entity
or give it a sensible name but avoid DBMS reserved
- Each attribute turns into a column
(attribute) in the table. The key attribute
of the entity is the primary key of the
table which is usually underlined. It can
be composite if required but can never
be null.
Taking the following simple ER diagram:
The initial relational schema is expressed in
the following format writing the table
names with the attributes list inside a
parentheses as shown below for
Persons ( personId , name, lastname, email )
- personId is the primary key for the table
Persons
2. Multi-Valued Attributes
A multi-valued attribute is usually represented
with a double-line oval.
- A multi-valued attribute is turned into a new entity or table
of its own.
- make a 1:N relationship between the new entity and the
existing one ie
- Create a table for the attribute.
- Add the primary (id) column of the parent entity as a foreign
key within the new table as shown below:
Persons( personid , name, lastname, email )
Phones ( phoneid , personid, phone )
**NB: personid within the table Phones is a foreign key
referring to the personid of Persons
Relationships
For instance, let us consider the case where the Person has
or optionally has one wife. You can place the primary key
of the wife within the table of the Persons which we call in
this case Foreign key as shown below.
Persons( personid , name, lastname, email , wifeid )
Wife ( wifeid , name )
Or vice versa to put the personid as a foreign key within
the Wife table as shown below:
Persons( personid , name, lastname, email ) Wife ( wifeid ,
name , personid)
Relationships (One to Many)
For instance, the Person can have a House
from zero to many , but a House can have
only one Person. To represent such
relationship the personid as the Parent node
must be placed within the Child table as a
foreign key but not the other way around.
It should convert to :
Persons( personid , name, lastname, email )
House ( houseid , num , address, personid)
N:N Relationships (Many to
Many)
For instance, The Person can live or work
in many countries. Also, a country can have
many people. To express this relationship
within a relational schema we use a
separate table.
It converte into :
Persons( personid , name, lastname, email )
Countries ( countryid , name, code)
HasRelat ( hasrelatid , personid ,
countryid)
** It is recommended to use table to
represent relationship with attributes to
keep the design tidy and clean regardless of
Case Study
Produce the relational schema for the following ER diagram:
The relational schema for the ER Diagram is given
below as:
Company( CompanyID , name , address )
Staff( StaffID , dob , address , WifeID)
Child( ChildID , name , StaffID )
Wife ( WifeID , name )
Phone(PhoneID , phoneNumber , StaffID)
Task ( TaskID , description)
Work(WorkID , CompanyID , StaffID , since )
Perform(PerformID , StaffID , TaskID )
SQL COMMANDS
Communicating With the Database
Some databases have their own computer
languages. For all the data in databases, data
descriptions must be provided. Data Description
(Definition) Languages (DDL) are provided as
well as the Data Manipulation Language (DML)
*NB:
 DDL- Refers to data about data (data
used to describe data (metadata)).
o It specifies the data in the database.
o It defines the structure of the tables.
o It is used to define the data tables.
o It specifies the data types of data held.
o It specifies constraints on the data.
o contains validation rules for data
 DML: Language used by users to (access)
retrieve data from databases. It allows user to
perform the following
o Allows storage of data in tables
o Insert new records
o Update the database
o Delete records
o Modify/edit records
o Search and retrieve data
A combination of the DDL and the
DML is called a Data Sub-Language
(DSL) or a Query Language. The
most common DSL is the Structured

Query Language (SQL)


SQL is the standard computer language used to
communicate with relational database
management systems. A SQL is a standard (de
facto) query function for searching data from
databases. It is a medium for communication
with databases.
SQL commands consist of English-like
statements which are used to query, insert,
update, and delete data
A query is a user request to retrieve
data or information using a certain
condition.
It is a command written in query
language which allows users to access
and manipulate data stored in
databases.
These SQL commands are mainly categorized
into four categories:
1. DDL(Data Definition Language) : consists
of the SQL commands that can be used to
define the database schema. It deals with
descriptions of the database schema and is used
to create and modify the structure of database
objects in database.
Examples of DDL commands:
 CREATE – used to create the database or its objects
(like table, index, function, views, store procedure and
triggers).
 DROP – used to delete objects from the database.
 ALTER- used to alter the structure of the database.
 TRUNCATE– used to remove all records from a table,
including all spaces allocated for the records are removed.
 COMMENT – used to add comments to the data
dictionary.
 RENAME – used to rename an object existing in the
2. DML(Data Manipulation Language) : deals
with the manipulation of data in database.
Examples of DML:
 SELECT – used to retrieve data from the a
database.
 INSERT – used to insert data into a table.
 UPDATE – used to update existing data within a
table.
 DELETE – used to delete records from a
database table.
3. DCL(Data Control Language) : DCL includes
commands such as GRANT and REVOKE which
mainly deals with the rights, permissions and other
controls of the database system.
Examples of DCL commands:
 GRANT-gives user’s access privileges to
database.
 REVOKE-withdraw user’s access privileges
given by using the GRANT command.
4. TCL(transaction Control Language) : TCL
commands deals with the transaction within the
database.
Examples of TCL commands:
 COMMIT– commits a Transaction.
 ROLLBACK– rollbacks a transaction in case of any
error occurs.
 SAVEPOINT– sets a save point within a transaction.
 SET TRANSACTION–specify characteristics for
the transaction.
Example of SQL commands
MSU DATABASE
• StudentDetails
The SELECT
• It is the most commonly used language.
• It is a statement used to Query or Retrieve data from a
hidden table.
• It can return a result set of records from one or more
tables.
• Specifies a result set but does not specify how to
calculate it.
• Also have many optional clauses eg Select—where--.
The Select cntd
• To create a simple SQL Select statement you
must specify the column(s) name and the
table name.
• The whole query is called SQL Select
statement.
SYNTAX
SELECT column list from table_name
The Select example
Query Result
• SELECT * FROM • All elements from
StudentDetails; rows the table are
shown
Reg.Number FirstName LastName Age Course Games
R15200 Peter Moyo 18 History Soccer
R15001 Mary Moyo 18 Maths cricket
R15100 Tony Jame 21 Maths chess
R15110 Sam Dube 19 Medicine soccer
R15220 Chipo Rima 20 Science cricket
Selecting one column
Query Results
• All elements of column 3
SELECT LastName will be shown like
FROM LastName
StudentDetails; Moyo
Moyo
James
Dube
Rima
WHERE CLAUSE

QUERY RESULT
• SELECT * FROM • All those only
StudentDetails
playing soccer will
WHERE
Games=‘Soccer’ be displayed
DISTINCT Clause
• The DISTINCT keyword is used in conjunction with the
SELECT statement to eliminate all the duplicate
records and fetching only unique records.
• Syntax: SELECT DISTINCT column1, column2….
FROM table_name
WHERE [condition];
QUERY
DISTINCT clause
RESULT

• SELECT • Only 3 different games


DISTINCT are displayed under
games
Games FROM
Games
StudentDetails
Soccer
Cricket
Chess
The Insert into statement
• It is used to insert a new record in a table
• The INSERT INTO statement is written in two ways
• The first way specifies both the column name and the value to be
inserted.
• INSERT INTO table_name (column1, column2, column3,…)
VALUES (value1, value2, value3,…)
• The second way is used when adding all columns of a table
• The INSERT INTO syntax will be as follows:
• INSERT INTO table_name
Contd

• When inserting a new student into our table


StudentDetails, the following SQL INSERT INTO
syntax is used
• INSERT INTO StudentDetails
VALUES (‘R15230’, ‘James’, ‘Gudo’, ‘23’,
‘Mining’, ‘Soccer’)
INSERT INTO
QUERY RESULTS
• INSERT INTO StudentDetails • The 6th student is
Values(‘R15230’, ‘James’, ‘Gudo’, added to the
’23’, ‘Mining’, ‘Soccer’)
StudentDetails table
DELETE

• The DELETE statement is used to delete the existing


records from a table.
• You can use the WHERE clause with a DELETE query
to delete the selected rows, otherwise all the records
would be deleted
• Eg DELETE FROM StudentDetails (WHERE age is
>20);
DELETE STATEMENT

QUERY RESULT
• DELETE FROM StudentDetails• All students above the age of 20
(WHERE age is > 20); are eliminated from the table
The Update

• The Update statement is used to modify the existing


records in a table.
• You can use the WHERE clause with the UPDATE query
to change the existing data in the selected rows, otherwise
all the rows would be affected meaning to say either all
the rows can be updated or a subset maybe chosen using a
condition
UPDATE cont
• General Syntax
UPDATE table_name
SET column 1 = value 1, column 2 = value 2
WHERE condition;
(example refer to table” STUDENT”)
UPDATE Student
SET first name = Peter last name = Moyo
WHERE course = maths
UPDATE STATEMENT

QUERY RESULT
• UPDATE StudentDetails SET • The LastName of Rima is
LastName =‘Dube’ WHERE changed to Dube
LastName = ‘Rima’;

Dube
CREATE

• CREATE statement is used to create a new table in


an existing database
• Eg. CREATE LecturerDetails (LectrNumber varchar,
FirstName varchar(50), LastName string(50),
ModuleCode varchar(20));
MSU DATABASE
• StudentDetails

• LecturerDetails

LectrNumber FirstName LastName ModuleCode


The Drop statement

• The DROP statement is used to remove a table


definition and all the data, indexes, triggers,
constraints and permission specifications for the
table
Syntax
DROP table_name;
DROP STATEMENT
QUERY RESULT

• DROP LecturerDetails • The LecturerDetails table


is deleted from the msu
database

StudentDetails MSU DATABASE


The DROP database
• Conditionally drops the database only if it already
exists.
• A database can be dropped regardless of its
state(offline, read only or suspect).
• A dropped database can be recreated only by
storing a backup.
• Dropping a database deletes all the information
from an instance
Syntax of a DROP database

• DROP DATABASE database name;


eg DROP DATABASE that contains table
student details;
NB// make sure you have permission to
drop a database from the administration
INNER JOIN STATEMENT
• In SQL joins are used to combine records from two or more tables in a
database. A join is a means of combing two tables by using values
common to each other.
• The INNNER JOIN is the most important and frequently used joins. The
INNER JOIN creates a new result table by combing columns values of
two tables ( table1 and table 2) based upon the join predicate.
• The query comprises each row of table1 with each of table2 to find all
pairs of rows which satisfy the join predicate. When the join predicate is
satisfied, column values of each matched pair of rows of A and B are
combined into a new result.
BASIC SYNTAX OF THE INNER JOIN

• SELECT table1.column1, table2.column2….


FROM table1
INNER JOIN table2
ON table1.common_field =
table2.common_field;
INNER JOIN EXAMPLE
MSU DATABASE
StudentDetails Library
RegNu FirstN Last Ag Cour Games StuRegN Book DateOve Fine
mber am Nam se umbe rdue
R15200 Peter Moy 18 Histo Socce R15200 Enclo 03.08.17 $8
R15001 Mary Moy 18 Math Cricke R15230 Geom 10.08.17 $12
R15100 Tony Jame 21 Math Chess R15110 BBdias 12.08.17 $5
R15110 Sam Dube 19 Medi Socce R15440 Fagus 15.08.17 $10
R15220 Chip Rima 20 Scien Cricke
INNER JOIN
QUERY
RESULT
• SELECT StudentDetails. The column FirstName from
FirstName, Library.Fine StudentDetails and Fine from Library
From StudentDetails will be inner joined using RegNumber
INNER JOIN ON as the predicate
StudentDetails.RegNum RegNumber First Fine
ber Name
=Library.StuRegNumber R15200 Peter $8
R15110 Sam $5
ADVANTAGES OF USING SQL

• It introduced the concept of accessing


many records with one single command.
• It eliminates the need to specify how to
reach a record eg with or without an index.
Develop Interfaces and
Queries Using DBMS Tools

You might also like