Вы находитесь на странице: 1из 62

DBMS HNDA II ATI-Sammanthurai

Contents
Module 1- Database Design .................................................................................................................... 2
1. What is a database? ......................................................................................................................... 2
2. Database Management Systems (DMBS) ....................................................................................... 3
3. Database Organizations .................................................................................................................. 3
3.1 3.1 The Relational Database ................................................................................................... 3
4. Database Design.............................................................................................................................. 5
4.1 Conceptual Database Design .................................................................................................. 5
4.2 Logical Database Design ...................................................................................................... 10
Module 2- Working with Microsoft Access ......................................................................................... 13
1. Getting Started .............................................................................................................................. 13
1.1.1 Creating a Blank Database ............................................................................................ 13
1.1.2 Access Objects .............................................................................................................. 14
1.1.3 Change Views ............................................................................................................... 14
2. Creating Microsoft Access Tables ................................................................................................ 15
2.1 Create a table using Design View ......................................................................................... 15
2.2 Working with Relationship ................................................................................................... 18
2.3 Querying the Database .......................................................................................................... 20
2.3.1 Creating a Query ........................................................................................................... 22
2.3.2 Querying based on Criteria ........................................................................................... 27
2.3.3 Calculation Query ......................................................................................................... 31
2.3.4 Creating a Parameter Query .......................................................................................... 33
2.4 Forms .................................................................................................................................... 35
2.4.1 Creating Forms .............................................................................................................. 35
2.4.2 Modifying a Form ......................................................................................................... 39
2.4.3 Creating a command button in Forms ........................................................................... 40
2.4.4 Using controls in a form................................................................................................ 43
2.5 Reports .................................................................................................................................. 43
2.5.1 Use the Report Button ................................................................................................... 43
2.5.2 Create a report by using the Wizard.............................................................................. 44
Appendix (A) – Structured Query Language ........................................................................................ 46

1
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Module 1- Database Design

1. What is a database?

We define a database as an organized collection of logically related data. A database may be of any
size and complexity.

For example, a salesperson may maintain a small database of customer contacts on her laptop
computer that consists of a few megabytes of data. A large corporation may build a very large
database consisting of several terabytes of data on a large mainframe computer that is used for
decision support applications. Very large data warehouses contain more than a peta byte of data (a
petabyte is a quadrillion bytes).

By the term organized we mean that the data are structured so as to be easily stored, manipulated, and
retrieved by users. By the term related, we mean that the data describe a domain of interest to a group
of users and that the users can use the data to answer questions concerning that domain. For example,
a database for an automobile repair shop contains data identifying customers (customer's name,
address, work phone number, home phone number, and preferred credit card number), automobiles
belonging to those customers (make, model, and year), and repair histories for each of those
automobiles (date of service, name of person who worked on vehicle, type of repair performed, and
rupee amount of work performed).

Advantages of having Databases:

For both individuals and organizations, there are many advantages of having databases:

• Sharing: In organizations, information from one department can be readily shared with
others.
• Security: Users are given passwords or access only to the kind of information they need to
know. Thus, the payroll department may have access to employees' pay rates, but other
departments would not.
• Fewer files: With several departments having access to one file, there are fewer files. Excess
storage, or what is called "data redundancy," is reduced.
• Data integrity: Older filing systems many times did not have "integrity." That is, a change
made in the file in one department might not be made in the file in another department. As
you might expect, this can cause serious problems and conflicts when data is used for
important decisions affecting both departments.
(O’leary, T.J. & O’leary, L.I., 1997)

2
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

2. Database Management Systems (DMBS)

A DBMS program helps organizations use their integrated collections of data records and files known
as databases. It allows different user application programs to easily access the same database. For
example, a DBMS makes it easy for an employee database to be accessed by payroll, employee
benefits, and other human resource programs. A DBMS also simplifies the process of retrieving
information from databases in the form of displays and reports. Instead of having to write computer
programs to extract information, end users can ask simple questions in a query language such as
Structured Query Language (SQL). Thus, many DBMS packages provide fourth-generation languages
(4GLs) and other application development features. Examples of popular mainframe and midrange
DBMS packages are DB2 by IBM and Oracle 9i by Oracle Corporation.

3. Database Organizations

The purpose of a database is to integrate individual items of data-that is, to transform isolated facts
into useful information. We saw that files can be organized in various ways (sequentially, for
example) to best suit their use. Similarly, databases can also be organized in different ways to best fit
their use. Although other arrangements have been tried, the most common formats are hierarchical,
network, relational, and object-oriented. Since the relational database is the one that firmly established
in the database application world, and there are many commercial relational DBMS packages, we will
discuss the relational databases in detail in the following section.

3.1 The Relational Database

The most flexible type of organization is the relational database. In this structure, there are no access
paths down a hierarchy to an item of data. Rather, the data elements are stored in different tables, each
of which consists of rows and columns. A table is called a relation.

An example of a relational database is shown in our illustration (See Figure 1). The book table
contains the reference number, title, author number, and price for all books in a particular library.
Within the table, a row resembles a record for example, information about one book. A column entry
resembles a field. The title of a book is one field; the author number is another field. All tables must
have a field to identify each record in the table uniquely (primary key field). So, the reference number
is a key field of the book table. Another might be the member number of the member table.
Information stored on one table can be linked with information stored on another by using the primary
key of a one table as a field in another table (Foreign key). Therefore a librarian who sees an overdue
book (in the circulation table) can recall it using the borrower information (from the member table)
and the book information (from the book table). He can locate this information from these two tables
easily using the reference number and the borrower number of the corresponding record of the
circulation table.

The most valuable feature of relational databases is their simplicity. Entries can be easily added,
deleted, and modified. The hierarchy and network databases are more rigid. The relational
organization is common for microcomputer DBMSs, such as Access, Paradox, dBASE, and R: Base.

3
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Relational databases are also becoming very popular for mainframe- and minicomputer based
systems.

Figure 1; An example for a relational database

Circulation Table

Circulation ID Reference Borrower Number Date borrowed Date returned


Number

2345 L0987 02088435 12/05/2004 21/05/2004

2346 R9087 09876554 13/06/2004 16/06/2004

2347 L8965 98765455 21/05/2004

.. . . . .

. . . . .

Book Table Member Table

Reference Author Price Title Member Name Address


Number Number Number

L8965 021 107.00 Accountancy 76543245 Senaka U.F. Colombo

L9878 763 56.00 Logic 34562321 Nisha K.L. Galle

E7654 231 250.00 Stress 98765455 Mohmud M. Kandy

4
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

4. Database Design

Database designing is the process of designing the database. It has three main phases

1. Conceptual database design


2. Logical database design
3. Physical database design

4.1 Conceptual Database Design

Conceptual design is the process of constructing a model of information used in an enterprise,


independent of all physical considerations. This model is called Entity Relationship Diagram. This
model provides the overview of the clients complete database.

Conceptual database design requires the following steps:

The more carefully you design, the better the physical database meets users' needs. In the process of
designing a complete system, you must consider user needs from a variety of viewpoints.

1. List the entities.


2. List the attributes about the entities.
3. Determine the relationship among entities.
4. Determine the Primary Key.
5. Final Conceptual design.

Case Study

Suppose you have to design a database for 1st year students of Management Faculty of the
University. The faculty consists of several departments that offer courses for registered
students. One department can offer more than one course. Faculty also records details
about lecturers who belong to departments. A lecturer is assigned to one or more courses.
A Student can follow one or many Courses. The grades obtained by each student for each
course should also be recorded in the database.

5
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Step 1: List the entities

Make a list of all possible entities. An entity can be physical objects such as Students, lecturers,
lecture halls in a university system or conceptual objects such as degree programs, courses.

An entity is a thing that holds information important for the database. Entities can be physical or
conceptual. Entities may be add or remove in the next steps to maintain a good design.

According to above case study following entities are identified.

Department Student
Course Lecturer
Step 2: List the attributes about the entities

There is a great deal of information associated with every entity. In this step, you should list the
attributes about an entity and then eliminate the attributes that are not important to the solution of the
problem.

The Student entity, for example, can have many attributes associated with it: Registration number,
First name, Last name, Date of birth etc. In this case, it is not important to keep information about the
height, weight or blood group of the student. The Faculty needs only the information it will use now
and possibly in the future.

Entity Important attributes about the entity


Department Name, Location, Start Date, Head
Course Title, Credits
Lecturer LecID, First Name, Last Name
Student RegNo, First Name, Last Name, Address, Telephone, Date of
birth, Gender

Other than above attributes, they need to store data about student grades, lecture times and venue.

Step 3: Determine the Relationship among entities

To determine the relationship among the entities, take each entity and look at how that entity may be
related to another. Keep in mind that not every relationship existing between entities is important. The
relationships that are important are those that allow you to model the database in the real-world
situation that the database represents.

A simple approach to do this is using a relationship matrix. This is a table that has rows and columns
for each of the identified entities. With four entities there are four rows and four columns. Each cell is
used to indicate whether or not that combination of entities has an association.

6
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Department Lecturer Course Student


Department Has Offers
Lecturer Belongs to Teaches
Course Offers by Conducts by Takes by
Student Takes

Your completed relationship matrix now contains a list of all the entities and all the relationships
between those entities. This is enough information to create a rough ERD.

Types of Relationships
One-to-one relationships. For any given row in Table A, there is only one row in Table B. For any
given row in Table B, there is only one row in Table A. There are no one-to-one relationships in the
Faculty database. An example of a one-to-one relationship is that of employee data and private
employee data. General information, such as employee name, address, and start date, is kept in one
table, and to ensure privacy, personal information, such as salary, is kept in another table.

One-to-many relationships. For any given row in Table A, there are many rows in Table B. For any
given row in Table B, there is only one row in Table A. The relationship between Department and
Course is one-to-many, because one department may offer more than one course, but a Course is
related to only one Department.

Many-to-many relationships. For any given row in Table A, there are many rows in Table B. For
any given row in Table B, there are many rows in Table A. There is a many-to-many relationship
between the Lecturer table and the Course table. A Lecturer can be assigned to different Courses and
a Course can be conducted by many different Lectures.

7
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

In order to identify the relationships between entities, first identify the number of occurrences of one
entity for a single occurrence of the related entity.

Department
Each lecturer belongs to one department
Each course offer by one department

Courses
Each Department offer one or more courses
Each student takes one or more courses
Each lecturer conduct one or more courses

Lecturer
Each department has one or more lecturers
Each course teach by one or more lecturers

Student
Each course has one or more students

These relationships can present in an ER diagram using following notations.

ER Diagram Notations (Crow’s Feet Notation)

8
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Sept4: Determine the Primary Key

Primary Key column is a column that uniquely identifies each row in a table. A primary key can be an
account number, social security number, part number, license number, or any other numeric value or
combination of characters that are unique. A composite key is one that is derived from more than one
column.

No other row in the table can have the value of the primary key column(s). If a company name is
universally unique, it is used as a unique row identifier. However, if there is any possibility another
company could have the same name, then it is not unique and must not be employed as a primary key
column. Do not use any column as a primary key where the possibility exists for a duplicate. A
primary key column cannot contain null values.

Department Student
Primary Key is DeptID Primary Key is RegNo
FIRSTNAME may not be
unique

Course Lecturer
Primary Key is Primary Key is LecID
CourseID

9
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Step 5: Final Conceptual design.

Department
PK- DeptID

Offers

Course Student
Has Takes
PK- CourseCode PK- RegNo

Teaches

Lecturer
Pk- LecID

4.2 Logical Database Design


Logical Database Design is the process of constructing a model of information used in an enterprise
based on a specific data model (e.g. relational), but independent of a particular DBMS and other
physical considerations.

Output of the conceptual design is input to the logical design.

Logical database design requires the following steps:

1. Remove features not compatible with the relational model (optional step)
2. Determine the Links
3. Final Logical design.

Step 1: Remove features not compatible with the relational model

This step includes:

1. Remove many-to-many binary relationship types


2. Remove many-to-many recursive relationship types
3. Remove complex relationship types
4. Remove multi-valued attributes.

Through this section we are going to learn only remove many-to-many binary relationship types.

10
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

The many-to-many relationship causes problems when attempting to retrieve data and when relating a
value in one table to its corresponding value in the other table. It is important to understand this
relationship to be able to recognize and control this situation when it arises.

According to above case study a many-to-many relationship exists between Lecturer and Course. A
Lecturer can conduct many courses and a course can be conducted by many lecturers.

But which key will we use for a link? If LecID is placed in the Course table, then all of the Course
data would have to be repeated for each Lecturer that contains that Course. If CourseID is placed in
the Lecturer table, then the Lecturer information has to be repeated for each Course contained in the
Lecturer. This leads to redundant data, and the potential for invalid data is increased. Performance
may suffer.

The solution to many-to-many relationships is to create an associate table. This table should contain
the key columns from both tables. This is illustrated in the following diagram.

Step 2: Determine Links

If you have been careful about designating primary key columns, you also have determined
the linking columns. Links provide a way to tie information (rows) in one table to another
table. Tables are linked together through their primary key columns. When a Primary key of
one entity is inserted as a column in the other related entity that column is referred to as
Foreign key.

To determine the placement of the links, you must first know the type of relationship among
the entities or tables. Once you know the type of relationship among tables, it is much easier
to determine where to place the linking column to tie two tables together.

11
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Department (DeptID, DName, Location, StartDate, HeadName)

Course (CourseCode, CourseName, Credits, DeptID)

Step 3: Final Logical Data Model

12
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Modulee 2- Work
king with Microsoft
M A
Access

Microsoftt Access is a Database Management


M System soft u can create a
ftware. With Access, you
computeriized databasee. For examplle, you can uuse Access to organize thee students whho attend an IT
I
training innstitute, the courses theyy take, and thhe instructorss who teach them. After you create an
a
c search it, manipulate itt, and extract information ffrom it.
Access daatabase, you can

1. Geetting Starrted

When youu start Accesss, the Gettingg Started with Microsoft Offfice Access screen
s appearrs. You can use
this screenn to do follow
wing things.

• C
Create a blank database
• C
Create a databaase using a teemplate
• O
Open an existing database

1.1.1 C
Creating a Bla
ank Databasse

A blank database
d is a database withh nothing in it. You can create a dataabase by building your ow
wn
tables, forrms, reports, and
a other dataabase objects. To create a blank databasse;

1. On thhe Getting Sta


arted with Microsoft
Mi Officce Access pagge, under New
w Blank Databbase, click
Blankk Database.
2. In thee Blank Databbase pane, typ
pe a file namee in the File Name
N box. Too change the location
l of
the daatabase from the default, click
c Browse.

Clickk Create.

3. Beginn typing to add data, to the default table (Tablee 1). If you do not wannt to enter
inform
mation in Tab
ble1 at this tim
me, click Close.

1
13
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

1.1.2 Access Objects

When you create a database, Access offers you Tables, Queries, Forms, Reports, Macros, and
Modules.

Objects
Tables In Access, data is stored in tables. A table is a set of columns and rows, with
each column referred to as a field. Each value in a field represents a single
type of data. Each row of a table is referred to as a record.
Queries You use queries to retrieve specific data from your database and to answer
questions about your data. For example, you can use a query to find the
names of the employees in your database who live in a particular state.
Forms Forms give you the ability to choose the format and arrangement of fields.
You can use a form to enter, edit, and display data.

Reports Reports organize or summarize your data so you can print it or view it
onscreen. You often use reports when you want to analyze your data or
present your data to others.
Macros Macros give you the ability to automate tasks. You can use a macro to add
functionality to a form, report, or control.

Modules Like macros, modules give you the ability to automate tasks and add
functionality to a form, report, or control. Macros are created by choosing
from a list of macro actions, whereas modules are written in Visual Basic for
Applications.

1.1.3 Change Views

A view is a way of looking at an object. For example, in Access, data is stored in tables. Two of the
possible ways you can view a table are Datasheet view and Design view. You can see the data

14
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

contained in a table in Datasheet view. You can see the design of a table in Design view. You can use
the View button on the Home tab to change views, or you can click the proper button in the lower-
right corner of the window.

2. Creating Microsoft Access Tables

Tables are the foundation of an Access database. Access stores data in tables.

You can add new tables to an existing database by using the options in the Tables group on the
Create tab.

2.1 Create a table using Design View

In Design view, you first create the new table's structure. You then switch to Datasheet view to enter
data.

1. On the Create tab, in the Tables group, click Table Design.


2. For each field in your table, type a name in the Field Name column, select a data type from the
Data Type list and select a Primary Key for the table. If you want, you can type a description for
each field in the Description column.
3. After you have added all of your fields, save the table:
4. You can begin typing data in the table at any time by switching to Datasheet view and clicking in
the first empty cell.

Understanding Data Types

You can use the Data Type property to specify the type of data stored in a table field. Each field can
store data consisting of only a single data type.

15
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Data Type Use


Text (Default) Text or combinations of text and numbers, as well as numbers that don't
require calculations, such as phone numbers.
Memo Lengthy text or combinations of text and numbers.
Number Numeric data used in mathematical calculations.
Date/Time Date and time values for the years 100 through 9999.
Currency Currency values and numeric data used in mathematical calculations involving
data with one to four decimal places. Accurate to 15 digits on the left side of the
decimal separator and to 4 digits on the right side.
AutoNumber A unique sequential (incremented by 1) number or random number assigned by
Microsoft Access whenever a new record is added to a table. AutoNumber fields
can't be updated.
Yes/No Yes and No values and fields that contain only one of two values (Yes/No,
True/False, or On/Off).
OLE Object Use to attach an OLE object such as a Word document, Excel spreadsheet, or
PowerPoint presentation.
Hyperlink Text or combinations of text and numbers stored as text and used as a hyperlink
address.
Attachment Any supported type of file
Lookup Creates a field that allows you to choose a value from another table or from a list
Wizard of values by using a list box or combo box. Clicking this option starts the Lookup
Wizard, which creates a Lookup field. After you complete the wizard, Microsoft
Access sets the data type based on the values selected in the wizard.

Field Properties

In addition to selecting a data type, you can set the following options for each filed in Design view.

Item Description
Field Size Allow you to set the size of the field (i.e. limit text entries to 10
characters).
Format Format in which to display the values for the field to the users. (i.e. show a
postal code with the space in the middle).

16
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Decimal Set the number of decimal places to show for a numeric field.
Places
Input Mask Restrict the data that the user can enter. Used to ensure correct data entry.
(i.e. for a postal code, you want to make sure that the first character entered
is a letter and not a number.
Caption If you want a different name to appear for the column header in the
datasheet view or the label in form view. (i.e. originally call field
"EmpNo" but you want the labels to say "Employee Number"
Default A value to be entered in to the table if the user does not enter one.
Value
Validation Can be used to validate the information the user enters. (i.e. make sure the
Rule value is always less than 100)
Validation Allow you to set the message that appears if the validation rule fails. If
Text nothing is entered for this value, Access will display a default message.
Required If turned on, the user must enter something in this field in order to save the
record.

Identify the unique field

In a relational database, tables are connected to each another through unique field. Unique field is a
field with values that occur only once in a table. For an example, National Identity card number
uniquely identifies a person. A field or a combination of fields that uniquely identify each record in a
table is called a Primary Key. In some table it takes more than one field to create a primary key and
that is called as Composite Key.

1. In the table design grid, select the field or fields that you want to use as the primary key.
2. On the Design tab, in the Tools group, click Primary Key.

A key indicator appears to the left of the field or fields that you specify as the primary key.

17
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Primary Keey

2.2 Woorking with Relationshiip

To removve data redu


undancy we divide
d data iinto many suubject-based tables so that each fact is
representted only oncce. Then theere should be
b a mechanism to bringg the dividedd informatioon
back togeether to reprresent them in
i a meaninggful way. Microsoft
M Offfice Access 2007
2 providees
a means to
t do this byy creating rellationships bbetween tablles.

A table relationship works


w by maatching data in key fieldds — often a field with th
he same nam
me
in both tables.
t In most
m cases, these matchiing fields arre the prim
mary key froom one tablle,
which provides a uniique identifieer for each record, and a foreign keyy in the otheer table.

Create Relationships
R s

Steps:

1. On th
he Database Tools
T tab, in the Show/Hid
de group, clicck Relationsh
hips.

2. Add tables
t or quarrries from thee Show Tablee dialog box.
3. Drag a field (typiccally the prim
mary key) from
m one table too the commonn field (the fo
oreign key)
in thee other table.. To drag mu
ultiple fields, press the CT
TRL key, clicck each fieldd, and then
drag them.
t

The Edit
E Relation
nships dialog box appears.

1
18
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

4. Verify that the field names shown are the common fields for the relationship. If a field name
is incorrect, click the field name and select a new field from the list.

To enforce referential integrity for this relationship, select the Enforce Referential Integrity
check box.

Click Create.

Setting Referential Integrity

Referential Integrity ensures that records in related tables have related values in the primary table.
Referential integrity prevents users from accidentally deleting or changing records in a primary table
when records in a related table depend on them, making sure that there are no orphaned records in the
related tables, such as employees without departments.

To change present Referential Integrity in a relationship open the relationship window and right click
the join line and click edit relationship. In the Edit Relationship dialog box provide options to change
present Referential Integrity.

19
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Cascade Update

When cascade update related fields enabled, changing the value of the primary key in the primary
table automatically updates that value in the foreign key of the related table’s matching record.

Cascade Delete

When cascade delete related records is enabled, deleting a record in the primary table delete nay
related records in the elated tables. Cascade update and delete make your database more efficient by
ensuring that related records always match their primary records.

2.3 Querying the Database

Queries are the primary mechanism for retrieving information from a database and consist of
questions presented to the database in a predefined format. Queries are often called by the user
through a form. They can be used to search for and grab data from one or more of the tables, perform
certain actions on the database and even carryout a variety of calculations depending on the needs.

Microsoft Access provides the user with several types of queries. They are explained below.

Select Query

The select query is the simplest type of query and because of that, it is also the most
commonly used one in Microsoft Access databases. It can be used to select and display data
from either one table or a series of them depending on what is needed.

Action Query

When the action query is called, the database undergoes a specific action depending on what
was specified in the query itself. This can include such things as creating new tables, deleting
rows from existing ones and updating records or creating entirely new ones.

Action queries are very popular in data management because they allow for many records to
be changed at one time instead of only single records like in a select query.

Four kinds of action queries are:

20
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

1. Append Query – takes the set results of a query and "appends" (or adds) them to an existing
table.
2. Delete Query – deletes all records in an underlying table from the set results of a query.
3. Make Table Query – as the name suggests, it creates a table based on the set results of a
query.
4. Update Query – allows for one or more field in your table to be updated.

Parameter Query

When you want a query to ask for input every time that you run it, you can create a parameter
query. In Microsoft Access, a parameter query works with other types of queries to get
whatever results you are looking for.

It is often chosen because it allows for a dialog box where the end user can enter whatever
parameter value they wish each time the query is run. The parameter query is just a modified
select query.

Aggregate Query

A special type of query is known as an aggregate query. It can work on other queries (such as
selection, action or parameter) just like the parameter query does, but instead of passing a
parameter to another query it totals up the items by selected groups.

It essentially creates a summation of any selected attribute in the table. This can be further
generated into statistical amounts such as averages and standard deviation, just to name a
couple.

Some of the aggregate functions available in Microsoft Access are:

• Sum • Count
• Avg • StDev
• Min • Var
• Max • Expression

MS Access provides a Graphical User Interface to create queries. This avoids the
writing of lengthy codes using Structured Query Language to create queries. Access

21
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

builds the SQL in the background, sends it to the database and returns the result in a
datasheet format.

2.3.1 Creating a Query

To create a query, go to the ‘other’ group of the create ribbon. You can use the query wizard
or the query design options to create a query.

Creating a Simple Query with Query Wizard

Step 1: Select Simple Query option from the dialog box that appears when you click on the
Query wizard option. Click OK to Continue.

22
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Step 2: Select the relevant table or the query from the Tables/Queries combo box. After that,
add the relevant fields from the available fields listbox to the selected fields listbox. You can
add fields from multiple related tables for a single query.

Click Next to Continue.

Step 3: Now you almost completed your query design. Type a meaningful title to identify the
query if you do not like the title given by default. Then click finish to end the wizard. The
query will be opened either in design view or in the datasheet view depending on the options
you set.

23
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Creating a Simple Query using Query Design

Step 1: Select the relevant table(s) from the show table dialog box that appears once you click
on the ‘Design Query’ option

Step 2: Double click the fields one by one from the field list to add them to the query. You
can see the fields are entered to the “Field” section of the bottom pane of the query window.

24
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

If you like, instead of double clicking, you can add fields by selecting them from the ‘field’
section of each column of the bottom section of the query window.

If you want to include all the fields of a table, you can choose “*” symbol from the field list.
(Or else, you can add all the fields one by one).

Step 3 : Click ‘Run’ to execute the query.

25
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

The query will show the results in the datasheet view as follows.

Press save button if you want to save the query. Saved queries are shown in the queries
category of the navigation pane.

SQL View

You can see the SQL statement executed behind this query by selecting the SQL view from
the results group of the design ribbon.

The SQL Statement will be shown as follows.

26
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

2.3.2 Querying based on Criteria

When you want to limit the results of a query based on the values in a field, you should use
query criteria. The criteria should be specified in the criteria row of the relevant field of the
query.

Following picture shows the query designed to obtain the details of the novels from the Books
table.

The results are as follows.

Notes:

• If the data type of the field is text, the criteria that you typed for that field will be
automatically included with in double quotes.
• Do not use quote (‘’ or “”) when specifying criteria for fields based on number,
currency or Date/Time data types.
• =,>,<, <=, >=,< >, between, not between keywords can be used when mentioning the
criteria.
• A query can be created by specifying more than one criterion for the fields it
contains. For example, a query can be prepared to get the details of the all Novels
(Category Field) written by Martin Wickramasinghe.(AuthorName Field)

27
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Dealing with Numbers

Example:

Display Title of the book, Author Name and Number of copies of the books of whom the
number of copies exceeds 5.

In the Criteria cell of the CopyCount column, type in > 5.

Results:

Wildcards

Example:

Display the titles and the names of the authors of the books written by authors who has the
name “Alexander” in somewhere in his full name.

Hint: Use the asterisk (“*”) wildcard.

28
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

In the phrase “*Alexander*”, the * searches for zero or more characters before the word
Alexander and Zero or more characters after the word Alexander.

Result:

Querying based on Multiple Criteria / Conditions

When specifying multiple conditions / criteria for a one attribute, conditional operators such
as AND, OR can be used. You also can specify different criteria for different attributes in a
single query.

OR Conditional Query

The OR condition allows us to select different sets of criteria for the same field.

Example: Display the titles of the books that starts with “G” or ends with “a”.

In the criteria cell of the title column, just type G* or *a. The keyword “Like” and the
quotation marks will be automatically inserted.

29
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Result:

AND Conditional Query

The AND condition allows us to set the criteria for the query based on multiple fields.

Example: Display the titles of all translations published by Willy Ltd.

Result:

30
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Note:

“AND” can also be used to specify criteria for one field.

Example:

Display the book titles which start with letter “G” and end with letter “a”.

Result:

2.3.3 Calculation Query

A calculation query allows us to perform arithmetic and string calculations on the field in the
query.

Example:

Following picture shows the attributes/ fields of a table called “Exam Marks”.

31
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Calculate the total marks obtained by each student by using a query. Display Student Exam
Number and the total marks only.

Steps:

1 Create a query using the design view and add the ExamNo as a field of the query.
2 Right click on the field cell of the adjacent column and select build.

3 In the expression builder, select the “Exam Marks” table from the tables. Now
you can see the fields of the table. Double click to select the field and use “+”
operator add fields together.
4 Type a suitable text (“Total Marks” in this example) just in front of first expression to
identify the calculated result. Use “:” to separate the text and the expression.

5 Click OK and run the query.

32
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Result:

2.3.4 Creating a Parameter Query

Parameter query allows the user to specify input every time he runs it.

Example 1:

Display the title and the author of the books published by a publisher that the user
selects.

Steps

1. Create a select query, and then open the query in Design view.
2. In the Criteria row of a field for which you want a parameter applied, type the
text that you want the parameter dialog box to display, enclosed in square
brackets, for example:

[Enter Publisher Name]

When you run the parameter query, the prompt appears in a dialog box
without the square brackets.

Type a relevant value for the parameter and click OK to continue.

33
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Example : Visidunu

Result:

Example 2:

Create a query to help user to retrieve the books written by an author. User only knows a part
of the author name.

For this purpose, the “like” statement and “*” wildcard should be used with the parameter.

Step 1: Create a query consisting with relent fields.

Step 2: Type Like "*" & [Author Name] & "*" in the criteria cell of the AuthorName
column

Step 3: Run the query and type a part of the author name in the parameter prompt.

34
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Result:

Notes:

You can also use an expression with your parameter prompts, for example:

Between [Start Date] And [End Date]

2.4 Forms

A form is a database object that you can use to enter, edit, or display data from a table
or a query. You can use forms to control access to specific rows or fields of data.
Controls can be added to a form to automate frequently performed actions.

2.4.1 Creating Forms

You can use them to enter, edit, or display data. They are based on tables. When using
a form, you can choose the format, the arrangement, and which fields you want to
display. This lesson teaches you how to create forms.

Using the Form Button

Access can automatically create several types of forms. For example, when you click
the Form button on the Create tab, Access places all fields in the selected table on a

35
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

form. If the table has a one-to-many relationship with one other table or query, Access
creates a stacked form (the records are displayed in a column) for the primary table
and a datasheet for the related table. If there are several tables with a one-to-many
relationship, Access does not create the datasheet.

Steps to create a form:

1. Open the Navigation pane.

2. Click the table or query on which you want to base your form.

3. Activate the Create tab.

4. Click Form in the Forms group. Access creates a form.

3
4

See the following result.

You can use the Navigation bars to move through the records on a form.

36
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

1 2 3 4 5 6 7

1. Go to First Record
2. Go to Previous Record
3. The Current Record
4. Total Number of records
5. Go to Next Record
6. Go to Last Record
7. Create a New (Blank) Record

Tip: After you create a form, you can save it. You can open a saved form at any
time.

Create a Split Form

A split form is a form in which the same data is displayed in two views
simultaneously. One part of the form displays in Form view (stacked fields), while the
other part displays in Datasheet view.

Steps to create a split form:

1. Open the Navigation pane.

2. Click the table or query on which you want to base your form.

3. Activate the Create tab.

4. Click Split Form in the Forms group. Access creates a split form.

37
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

3
4

See the following result.

Create a Multiple Items Form

You can use the Multiple Items button on the Forms tab to create a form that displays
multiple records, one record per row.

Steps to create a multiple items form:

1. Open the Navigation pane.

2. Click the table or query on which you want to base your form.

3. Activate the Create tab.

4. Click Multiple Items in the Forms group. Access creates a multiple items form.

38
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

3
4

See the following result.

2.4.2 Modifying a Form

After you create a form, it opens in Layout view, where you can modify it.

To change the size of a field:

1. Click a side of the field and drag to change the width of the field.

2. Click the top or bottom of a field and drag to change the height of a field.

To move a datasheet:

1. Click the datasheet to select it.

2. Click and drag the four-sided arrow in the upper-right corner to move the datasheet.

To resize a datasheet:

1. Click the datasheet to select it.

39
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

2. Click a side of the datasheet and drag to change the width.

3. Click the top or bottom of the datasheet and drag to change the height.

To apply an AutoFormat:

The AutoFormat option on the Format tab enables you to apply formats quickly, such
as background colors, field colors, field label colors, and fonts.

1. Activate the Format tab.

2. Click AutoFormat. The AutoFormat menu appears.

3. Click the format you want to apply.

To change a form title:

When you create a form, by default, Access uses the form name as the title.

You can change the title:

1. Activate the Format tab.

2. Click the Title button.

3. Type the new title.

2.4.3 Creating a command button in Forms

Steps:

1. Open your form in Design view.

A toolbox appears.

40
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

2. Click the Control Wizards button in the toolbox. In the top right hand corner of the toolbox,
this button resembles a wand and three stars.

3. Click the Command Button. It resembles a small rectangle.

4. Move to the form and click in the spot where you want the button to go.

5. Follow the directions in the wizard to choose the command associated with the button.
Click Finish.

6. Save the form.

Example for creating a Button to close a form:

Open the Properties form in design view

Insert a command button and then it will display the following dialog box,

Select Form Operations from the Categories and select Close Form from Actions category.

41
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Then Select the Text or Picture to insert a text or a picture for the button face.

Finally give a name for the button and then save the form.

Open the form again in form view to operate the button. (See the following result)

42
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

2.4.4 Using controls in a form

This will be discussed in the class room.

2.5 Reports

Reports organize and summarize data for viewing online or for printing. You can
include summary data such as totals, counts, and percentages in a detail report. A
summary report does not list the selected records but instead summarizes the data and
presents totals, counts, percentages, or other summary data only. Access has several
report generation options that you can use to create reports.

2.5.1 Use the Report Button

The Report button creates a simple report that lists the records in the selected table or
query in a columnar format.

Steps to prepare a report using the Report button:

1. Open the Navigation pane.

2. Click the table or query on which you want to base your report.

3. Activate the Create tab.

4. Click the Report button in the Reports group. Access creates your report and displays
your report in Layout view. Also you can modify the report later.

3
4

See the following result.

43
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

2.5.2 Create a report by using the Wizard

Steps to create a report by using the Wizard

1. Click the table or quarry on which you want to base the report

2. Activate the Create tab.

3. Click on the Report wizard button in the Reports group.

It will display following dialog box

4. Select the Table or query which you wish to get fields.

5. Then select the required fields for the report and Select Next

It will display following dialog box

44
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

6. If you need you can add grouping levels for the report (This is optional)

7. Then select Next and configure other necessary options that are shown in the forthcoming
windows, and click finish.

You can see the following Report under the Categories, such as Car, Van and Land

45
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Appendix (A) – Structured Query Language

What is SQL?

• SQL stands for Structured Query Language


• SQL lets you access and manipulate databases
• SQL is an ANSI (American National Standards Institute) standard

What Can SQL do?

• SQL can execute queries against a database


• SQL can retrieve data from a database
• SQL can insert records in a database
• SQL can update records in a database
• SQL can delete records from a database
• SQL can create new databases
• SQL can create new tables in a database
• SQL can create stored procedures in a database
• SQL can create views in a database
• SQL can set permissions on tables, procedures, and views

SQL is a Standard - BUT....

Although SQL is an ANSI (American National Standards Institute) standard, there are many
different versions of the SQL language.
However, to be compliant with the ANSI standard, they all support at least the major
commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.
Note: Most of the SQL database programs also have their own proprietary extensions in
addition to the SQL standard!

SQL Statements

Most of the actions you need to perform on a database are done with SQL statements.
The following SQL statement will select all the records in the "Persons" table:
SELECT * FROM Persons

In this tutorial we will teach you all about the different SQL statements.

Keep in Mind That...

• SQL is not case sensitive

Semicolon after SQL Statements?


Some database systems require a semicolon at the end of each SQL statement.

46
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Semicolon is the standard way to separate each SQL statement in database systems that allow
more than one SQL statement to be executed in the same call to the server.
We are using MS Access and SQL Server 2000 and we do not have to put a semicolon after
each SQL statement, but some database programs force you to use it.
SQL DML and DDL

SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data
Definition Language (DDL).

The query and update commands form the DML part of SQL:

• SELECT - extracts data from a database


• UPDATE - updates data in a database
• DELETE - deletes data from a database
• INSERT INTO - inserts new data into a database

The DDL part of SQL permits database tables to be created or deleted. It also define indexes
(keys), specify links between tables, and impose constraints between tables. The most
important DDL statements in SQL are:

• CREATE DATABASE - creates a new database


• ALTER DATABASE - modifies a database
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table
• CREATE INDEX - creates an index (search key)
• DROP INDEX - deletes an index

The SQL SELECT Statement

The SELECT statement is used to select data from a database.


The result is stored in a result table, called the result‐set.

SQL SELECT Syntax

SELECT column_name(s)
FROM table_name
and
SELECT * FROM table_name

Note: SQL is not case sensitive. SELECT is the same as select.

An SQL SELECT Example


The "Persons" table:

P_Id LastName FirstName Address City


1 Pathirana Ruwan 44/2, Galle Rd Panadura

47
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

2 Samaraweera Ravi 845, Mahawa Panadura


3 Perera Gamini 1/3, Mahara Kadawatha

Now we want to select the content of the columns named "LastName" and "FirstName"
from the table above.

We use the following SELECT statement:


SELECT LastName, FirstName FROM Persons

The result‐set will look like this:

LastName FirstName
Hansen Ruwan
Samaraweera Ravi
Perera Gamini

SELECT * Example
Now we want to select all the columns from the "Persons" table.
We use the following SELECT statement:
SELECT * FROM Persons

Tip: The asterisk (*) is a quick way of selecting all columns!

The result‐set will look like this:

P_Id LastName FirstName Address City

1 Pathirana Ruwan 44/2, Galle Rd Panadura

2 Samaraweera Ravi 845, Mahawa Panadura


3 Perera Gamini 1/3, Mahara Kadawatha

The SQL SELECT DISTINCT Statement

In a table, some of the columns may contain duplicate values. This is not a problem,
however, sometimes you will want to list only the different (distinct) values in a table.

The DISTINCT keyword can be used to return only distinct (different) values.

SQL SELECT DISTINCT Syntax


SELECT DISTINCT column_name(s)
FROM table_name

48
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

SELECT DISTINCT Example


The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ruwan 44/2, Galle Rd Panadura
2 Samaraweera Ravi 845, Mahawa Panadura
3 Perera Gamini 1/3, Mahara Kadawatha

Now we want to select only the distinct values from the column named "City" from the table
above.
We use the following SELECT statement:

SELECT DISTINCT City FROM Persons

The result‐set will look like this:

City

Panadura

Kadawatha

The WHERE Clause

The WHERE clause is used to extract only those records that fulfill a specified criterion.

SQL WHERE Syntax


SELECT column_name(s)
FROM table_name
WHERE column_name operator value

WHERE Clause Example


The "Persons" table:

P_Id LastName FirstName Address City


1 Pathirana Ruwan 44/2, Galle Rd Panadura
2 Samaraweera Ravi 845, Mahawa Panadura
3 Perera Gamini 1/3, Mahara Kadawatha

Now we want to select only the persons living in the city "Panadura" from the table above.

We use the following SELECT statement:


SELECT * FROM Persons
WHERE City='Panadura'

49
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

The result‐set will look like this:

P_Id LastName FirstName Address City


1 Pathirana Ruwan 44/2, Galle Rd Panadura
2 Samaraweera Ravi 845, Mahawa Panadura

Quotes Around Text Fields


SQL uses single quotes around text values (most database systems will also accept double
quotes).
Although, numeric values should not be enclosed in quotes.

For text values:


This is correct:
SELECT * FROM Persons WHERE FirstName='Ravi'

This is wrong:
SELECT * FROM Persons WHERE FirstName=Ravi

For numeric values:

This is correct:
SELECT * FROM Persons WHERE Year=1965

This is wrong:
SELECT * FROM Persons WHERE Year='1965'
Operators Allowed in the WHERE Clause

With the WHERE clause, the following operators can be used:


Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN If you know the exact value you want to return for at least one of the
columns

Note: In some versions of SQL the <> operator may be written as !=

The AND & OR Operators

The AND operator displays a record if both the first condition and the second condition is
true.

50
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

The OR operator displays a record if either the first condition or the second condition is true.

AND Operator Example


The "Persons" table:

P_Id LastName FirstName Address City


1 Pathirana Ruwan 44/2, Galle Rd Panadura
2 Samaraweera Ravi 845, Mahawa Panadura
3 Perera Gamini 1/3, Mahara Kadawatha

Now we want to select only the persons with the first name equal to "Ravi" AND the last
name equal to "Samaraweera":

We use the following SELECT statement:

SELECT * FROM Persons


WHERE FirstName='Ravi'
AND LastName='Samaraweera'

The result-set will look like this:

P_Id LastName FirstName Address City

2 Samaraweera Ravi 845, Mahawa Panadura

OR Operator Example

Now we want to select only the persons with the first name equal to "Ravi" OR the first name
equal to "Ruwan":

We use the following SELECT statement:

SELECT * FROM Persons


WHERE FirstName='Ravi'
OR FirstName='Ruwan'

The result-set will look like this:

LastName FirstName Address City


P_Id
1 Pathirana Ruwan 44/2, Galle Rd Panadura
2 Samaraweera Ravi 845, Mahawa Panadura

51
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Combining AND & OR

You can also combine AND and OR (use parenthesis to form complex expressions).
Now we want to select only the persons with the last name equal to "Samaraweera" AND the
first name equal to "Ravi" OR to "Ruwan":

We use the following SELECT statement:


SELECT * FROM Persons WHERE
LastName='Samaraweera'
AND (FirstName='Ravi' OR FirstName='Ruwan')

The result-set will look like this:

P_Id LastName FirstName Address City

2 Samaraweera Ravi 845, Mahawa Panadura

The ORDER BY Keyword

The ORDER BY keyword is used to sort the result‐set by a specified column.


The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.

SQL ORDER BY Syntax


SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC

ORDER BY Example
The "Persons" table:

P_Id LastName FirstName Address City


1 Pathirana Ruwan 44/2, Galle Rd Panadura
2 Samaraweera Ravi 845, Mahawa Panadura
3 Perera Gamini 1/3, Mahara Kadawatha

Now we want to select all the persons from the table above, however, we want to sort the
persons by their last name.

We use the following SELECT statement:

SELECT * FROM Persons


ORDER BY LastName

52
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

The result‐set will look like this:

P_Id LastName FirstName Address City


1 Pathirana Ruwan 44/2, Galle Rd Panadura
3 Perera Gamini 1/3, Mahara Kadawatha
2 Samaraweera Ravi 845, Mahawa Panadura

ORDER BY DESC Example

Now we want to select all the persons from the table above, however, we want to sort the
persons descending by their last name.

We use the following SELECT statement:

SELECT * FROM Persons


ORDER BY LastName DESC

The result‐set will look like this:


P_Id LastName FirstName Address City
2 Samaraweera Ravi 845, Mahawa Panadura
3 Perera Gamini 1/3, Mahara Kadawatha
1 Pathirana Ruwan 44/2, Galle Rd Panadura

The INSERT INTO Statement

The INSERT INTO statement is used to insert a new row in a table.

SQL INSERT INTO Syntax

It is possible to write the INSERT INTO statement in two forms.

The first form doesn't specify the column names where the data will be inserted, only their
values:

INSERT INTO table_name


VALUES (value1, value2, value3,...)

The second form specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

53
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

SQL INSERT INTO Example


We have the following "Persons" table:

P_Id LastName FirstName Address City


1 Pathirana Ruwan 44/2, Galle Rd Panadura
2 Samaraweera Ravi 845, Mahawa Panadura
3 Perera Gamini 1/3, Mahara Kadawatha

Now we want to insert a new row in the "Persons" table.

We use the following SQL statement:

INSERT INTO Persons


VALUES (4,'Nawarathna', 'Jaliya', '7/2, Kumarathunga Mv’, 'Kadawatha')

The "Persons" table will now look like this:

P_Id LastName FirstName Address City

1 Pathirana Ruwan 44/2, Galle Rd Panadura

2 Samaraweera Ravi 845, Mahawa Panadura

3 Perera Gamini 1/3, Mahara Kadawatha

4 Nawarathna Jaliya 7/2, Kumarathunga Mv Kadawatha

Insert Data Only in Specified Columns

It is also possible to only add data in specific columns.

The following SQL statement will add a new row, but only add data in the "P_Id",
"LastName" and the "FirstName" columns:

INSERT INTO Persons (P_Id, LastName, FirstName)


VALUES (5, 'Thilakawardana', 'Janitha')

The "Persons" table will now look like this:


P_Id LastName FirstName Address City
1 Pathirana Ruwan 44/2, Galle Rd Panadura
2 Samaraweera Ravi 845, Mahawa Panadura
3 Perera Gamini 1/3, Mahara Kadawatha
4 Nawarathna Jaliya 7/2, Kumarathunga Mv Kadawatha
5 Thilakawardana Janitha

54
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

The UPDATE Statement

The UPDATE statement is used to update existing records in a table.

SQL UPDATE Syntax


UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!

SQL UPDATE Example


The "Persons" table:
P_Id LastName FirstName Address City
1 Pathirana Ruwan 44/2, Galle Rd Panadura
2 Samaraweera Ravi 845, Mahawa Panadura
3 Perera Gamini 1/3, Mahara Kadawatha
7/2, Kumarathunga
4 Nawarathna Jaliya Kadawatha
Mv
5 Thilakawardana Janitha

Now we want to update the person "Thilakawardana, Janitha" in the "Persons" table.

We use the following SQL statement:

UPDATE Persons
SET Address=’56, Maligawaththa', City='Panadura'
WHERE LastName='Thilakawardana' AND FirstName='Janitha'

The "Persons" table will now look like this:

P_Id LastName FirstName Address City


1 Pathirana Ruwan 44/2, Galle Rd Panadura
2 Samaraweera Ravi 845, Mahawa Panadura
3 Perera Gamini 1/3, Mahara Kadawatha
4 Nawarathna Jaliya 7/2, Kumarathunga Mv Kadawatha
5 Thilakawardana Janitha 56, Maligawaththa Panadura

55
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

SQL UPDATE Warning

Be careful when updating records. If we had omitted the WHERE clause in the example
above, like this:

UPDATE Persons
SET Address='56, Maligawaththa', City='Panadura'

The "Persons" table would have looked like this:

P_Id LastName FirstName Address City


1 Pathirana Ruwan 56, Maligawaththa Panadura
2 Samaraweera Ravi 56, Maligawaththa Panadura
3 Perera Gamini 56, Maligawaththa Panadura
4 Nawarathna Jaliya 56, Maligawaththa Panadura
5 Thilakawardana Janitha 56, Maligawaththa Panadura

The DELETE Statement

The DELETE statement is used to delete rows in a table.

SQL DELETE Syntax

DELETE FROM table_name


WHERE some_column=some_value

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which
record or records that should be deleted. If you omit the WHERE clause, all records will be
deleted!

SQL DELETE Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Pathirana Ruwan 44/2, Galle Rd Panadura
2 Samaraweera Ravi 845, Mahawa Panadura
3 Perera Gamini 1/3, Mahara Kadawatha
4 Nawarathna Jaliya 7/2, Kumarathunga Mv Kadawatha
5 Thilakawardana Janitha 56, Maligawaththa Panadura

Now we want to delete the person "Thilakawardana, Janitha" in the "Persons" table.

We use the following SQL statement:

56
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

DELETE FROM Persons


WHERE LastName='Thilakawardana' AND FirstName='Janitha'

The "Persons" table will now look like this:

P_Id LastName FirstName Address City


1 Pathirana Ruwan 44/2, Galle Rd Panadura
2 Samaraweera Ravi 845, Mahawa Panadura
3 Perera Gamini 1/3, Mahara Kadawatha
4 Nawarathna Jaliya 7/2, Kumarathunga Mv Kadawatha
Delete All Rows

It is possible to delete all rows in a table without deleting the table. This means that the
table structure, attributes, and indexes will be intact:

DELETE FROM table_name


or
DELETE * FROM table_name

Note: Be very careful when deleting records. You cannot undo this statement!

SQL has many built-in functions for performing calculations on data.

SQL Aggregate Functions

SQL aggregate functions return a single value, calculated from values in a column.

Useful aggregate functions:

• AVG() - Returns the average value


• COUNT() - Returns the number of rows
• FIRST() - Returns the first value
• LAST() - Returns the last value
• MAX() - Returns the largest value
• MIN() - Returns the smallest value
• SUM() - Returns the sum

SQL Scalar functions

SQL scalar functions return a single value, based on the input value.

Useful scalar functions:


• UCASE() - Converts a field to upper case
• LCASE() - Converts a field to lower case
• MID() - Extract characters from a text field
• LEN() - Returns the length of a text field
• ROUND() - Rounds a numeric field to the number of decimals specified
• NOW() - Returns the current system date and time
• FORMAT() - Formats how a field is to be displayed

57
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Tip: The aggregate functions and the scalar functions will be explained in details in the next
chapters.

AVG() Function

The AVG() function returns the average value of a numeric column.

SQL AVG() Syntax

SELECT AVG(column_name) FROM table_name

SQL AVG() Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer


1 2008/11/12 1000 Pathirana
2 2008/10/23 1600 Nawarathna
3 2008/09/02 700 Pathirana
4 2008/09/03 300 Pathirana
5 2008/08/30 2000 Jayaweera
6 2008/10/04 100 Nawarathna

Now we want to find the average value of the "OrderPrice" fields.


We use the following SQL statement:
SELECT AVG(OrderPrice) AS OrderAverage FROM Orders

The result‐set will look like this:

OrderAverage

950

Now we want to find the customers that have an OrderPrice value higher than the average
OrderPrice value.

We use the following SQL statement:

SELECT Customer FROM Orders


WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders)

58
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

The result‐set will look like this:

Customer
Pathirana
Nawarathna
Jayaweera

Count()Function

The COUNT() function returns the number of rows that matches a specified criteria.

SQL COUNT(column_name) Syntax

The COUNT(column_name) function returns the number of values (NULL values will not be
counted) of the specified column:

SELECT COUNT(column_name) FROM table_name

SQL COUNT(*) Syntax

The COUNT(*) function returns the number of records in a table:


SELECT COUNT(*) FROM table_name

SQL COUNT(DISTINCT column_name) Syntax

The COUNT(DISTINCT column_name) function returns the number of distinct values of the
specified column:
SELECT COUNT(DISTINCT column_name) FROM table_name

Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with
Microsoft Access.

SQL COUNT(column_name) Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Pathirana

2 2008/10/23 1600 Nawarathna

3 2008/09/02 700 Pathirana

4 2008/09/03 300 Pathirana

5 2008/08/30 2000 Jayaweera

6 2008/10/04 100 Nawarathna

59
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Now we want to count the number of orders from "Customer Nawarathna".

We use the following SQL statement:

SELECT COUNT(Customer) AS CustomerNawarathna FROM Orders


WHERE Customer='Nawarathna'

The result of the SQL statement above will be 2, because the customer Nawarathna has
made 2 orders in total:

CustomerNawarathna

SQL COUNT(*) Example

If we omit the WHERE clause, like this:

SELECT COUNT(*) AS NumberOfOrders FROM Orders

The result‐set will look like this:

NumberOfOrders
6

which is the total number of rows in the table.

SQL COUNT(DISTINCT column_name) Example

Now we want to count the number of unique customers in the "Orders" table.

We use the following SQL statement:

SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Orders

The result‐set will look like this:

NumberOfCustomers

which is the number of unique customers (Pathirana, Nawarathna, and Jayaweera) in


the "Orders" table.

60
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

Notes:

61
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP
DBMS HNDA II ATI-Sammanthurai

62
MIM Riyath
MSc-Management (R-SJP), BBA-Finance, ACMA, HANDA, CAB, AMGARP

Оценить