0% found this document useful (0 votes)
117 views43 pages

DAMASYS Students

The document provides an introduction to database management systems. It defines what a database and DBMS are, lists some popular DBMS like MySQL, SQL Server, and Oracle, and describes the advantages of using a DBMS like reduced data redundancy, improved data integrity, and concurrent access. It also discusses database tables, how they represent entities with attributes, and common database operations like create, read, update, and delete.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views43 pages

DAMASYS Students

The document provides an introduction to database management systems. It defines what a database and DBMS are, lists some popular DBMS like MySQL, SQL Server, and Oracle, and describes the advantages of using a DBMS like reduced data redundancy, improved data integrity, and concurrent access. It also discusses database tables, how they represent entities with attributes, and common database operations like create, read, update, and delete.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

DATABASE MANAGEMENT SYSTEM

(DAMASYS)

SOFTWARE DEPARTMENT

Quality Education within Reach


TOPIC 1: INTRODUCTION TO DATABASE MANAGEMENT SYSTEM

OBJECTIVES

At the end of the period, learners should be able to:


1. Learn and understand basic Database concepts.
2. Learn and understand DBMS Concepts.
3. Identify popular Database Management System.
4. Identify different advantages of DBMS.
5. Learn and understand database Tables
6. Learn and understand basic MS SQL Server concepts.

LECTURE

What is a database (DB)?

● `a collection of data that exists over a long period of time, often many managed through
a database management system.
● a very large, integrated collection of data.
● A database is a collection of related, logically coherent data used by the application
programs in an organization.

Advantages of Database

Comparing the flat-file system, we can mention several advantages for a database
system.

1. Less redundancy
- In a flat-file system there is a lot of redundancy. For example, in the flat file
system for a university, the names of professors and students are stored in more
than one file.
2. Inconsistency avoidance
- If the same piece of information is stored in more than one place, then any
changes in the data need to occur in all places that data is stored.
3. Efficiency
- A database is usually more efficient that a flat file system, because a piece of
information is stored in fewer locations.

4. Data integrity
- In a database system it is easier to maintain data integrity because a piece of
data is stored in fewer locations.
5. Confidentiality

2
- It is easier to maintain the confidentiality of the information if the storage of data
is centralized in one location.

What is a database management system (DBMS?

⚫ A DBMS is a software system


designed to maintain a database.
⚫ A Database Management System (DBMS) is a software system designed to store,
manage, and facilitate access to databases.

Popular Database Management System

1. MySQL - one of the most influential and widely spread open source database
applications that manipulates large databases and can be accessed over the Web is
MySQL database server.
2. Microsoft SQL Server designed to create web, enterprise, and desktop database
systems. It is used with various goals and at different levels.
3. Microsoft Office Access combines software development tools and the relational
Microsoft Jet Database Engine with easy-to-use GUI.
4. Microsoft Visual FoxPro, generally abbreviated as VFP, is closely integrated with its
own relational database engine, which broadens FoxPro's xBase capabilities to
maintain SQL inquiry and data manipulation. Unlike most DBMSs, Visual FoxPro is a
full-function, dynamic programming language that does not demand the use of an
additional universal programming environment. It can be used to write not just
conventional "thick client" applications, but also web application programs and
middleware. Since 2007 Microsoft renounced updating FoxPro therefore recently
data is usually converted in one-way direction from FoxPro into the other DBMSs.
5. PostgreSQL is a relational DBMS that many web application developers prefer as
the back-end data management component. It's principally used by many
distinguished organizations applying it for mission critical or wide-ranging
applications. The .info and .org domain name registries use it as their primary data
store, so do many financial institutions and large companies.
6. SQLite is a small C library that performs a standalone, embeddable, zero-
configuration SQL database engine. This database engine provides a rapid and easy
method to work with flat file databases. The SQLite engine is not a self-contained
process with which the program connects. Unlike server database management
systems, the SQLite is an integral part of the program.
7. Firebird is a fully featured and powerful RDBMS despite of its installer size. It can
manipulate databases from only a few kilobytes to many gigabytes with good
execution and almost free support. It's equally suitable both for commercial and open
source applications.
8. Oracle is one of the leading commercial SQL relational database management
systems. It is available in a variety of configurations from small personal versions to
fail-safe, enterprise-class versions.

Why do we need database systems?


3
● there is a large amount of data
● security and integrity of the data are important
● many users access the data concurrently

Advantages of a DBMS

• Data independence
• Efficient data access
• Data integrity & security
• Data administration
• Concurrent access, crash recovery
• Reduced application development time
• So why not use them always?
– Expensive/complicated to set up & maintain
– This cost & complexity must be offset by need
– General-purpose, not suited for special-purpose tasks (e.g. text search!)

DBMS vs. `just a file system'

● DBMS's evolved from file systems


● file systems also store large amounts of data over a long period of time in secondary
memory
● however, file systems
o can lack efficient access
o have no direct support for queries
o limit organization to directory creation and hierarchical organization
o have no sophisticated support for concurrency
o do not ensure durability

ACID properties

(all good DBMS's should guarantee these)

● Atomicity
o should not be able to execute half of an operation
o either all or none of the effects of a transaction are made permanent
● Consistency
o there should be no surprises in the world, e.g., gpa > 4.0, balance < 0, cats
should never have more than 1 tail!
o the effect of concurrent transactions is equivalent to some serial execution
o use constraints, triggers, active DB elements (context-free)
● Isolation
o concurrency control
o transactions should not be able to observe the partial effects of other
transactions
o use locks (whole relations or individual tuples?)
● Durability
o if power goes out, nothing bad should happen

4
o once accepted, the effects of a transaction are permanent (until, of course,
changed by another transaction)
o use logs

A1

Who uses DBMS's?

● parametric users, e.g., the travel agent, the application programmer


o create, update, or query content
o use DML (Data Manipulation Language) or query language: language which
changes the instance (contents)
● database administrators (DBA)
o create or modify schema
o uses DDL (Data Definition Language): language which programs the schema
(structure)

Applications of database systems

● reservation systems, banking systems


● record/book keeping (corporate, university, medical), statistics
● bioinformatics, e.g., gene databases
● criminal justice
o fingerprint matching
o how do you encode `looks like'?
● multimedia systems
o require terabytes (1012 bytes) of storage
o tertiary storage devices, e.g., CD, DVDs
o image/audio/video retrieval
o streaming, interactivity
● satellite imaging; can require petabytes (1015 bytes) of storage
● the web
o client-server and multi-tier architectures
o almost all data-intensive websites are database-driven; IMDB.com is an
exception
● information integration
o over the web
o legacy systems; must deal with issues of
▪ synonymy: different words having the same meaning, e.g., coffee shop
vs. café
▪ polysemy: same word (homonym) having different meanings, e.g., shot
o data warehouses
o data mining (KDD, Knowledge Discovery in Databases), e.g., association rules:
`diapers → beer'; we pass these on to the marketing folks
● in sum, databases are everywhere!

Refers to the most common Database Operations:


• Create

• Read

5
• Update

• Delete

Operations occur at all levels: Tables, Records, Columns

Database Tables
• Tables represent entities

• Tables are always named in the singular, such as: Vehicle, Order, Grade, etc.

• Tables in database jargon are “flat files”, dBase or Spreadsheet like..

Attributes
• Characteristics of an entity

• Examples:

• Vehicle (VIN, color, make, model, mileage)

• Student (SSN, Fname, Lname, Address)

• Fishing License (Type, Start_date, End_date)

Database Table Example

Figure 1: A simple – and flawed – table design.

Figure 2: An improved database table.

6
MS SQL Server

SQL Server is a client / server Relational Database Management System (RDBMS) which has
been developed by Microsoft and is made up several different client and server programs that
make up the entire product.

SQL Server Database Engine (Server)

SQL Server's database engine is the primary server application of the SQL sever package. Its
main functions are:

● Provide reliable storage


● Rows of data are stored as pages, each 8kb in size.
● Provide a means to rapidly access the data; this is done through utilizing indexes both
clustered and non-clustered to search for data, which removes the need for all data to be
scanned from the database tables.
● Ensure consistent access to the data; Consistent access basically means only allowing
one client to modify/changing the data at anyone time
● Implement security; Microsoft SQL Server has multiple security levels Server Level,
database level and database object level. Access to the server can be controlled by a
Username or password or through Windows security in LAN/Networked environment.
● Enforce data integrity; ensure the data stays consistent.

SQL Service Manager (Server)

The Service Manager is a small applet that allows easy controls of the SQL Services on the
SQL Server:

● SQL Server
● SQL Agent
● SQL Search, a full text search engine
● Distributed Transaction Coordinator
● OLAP Server; a separate service used for warehousing

SQL Server Agent (Server)

In this SQL Server overview, The SQL Server Agent is a scheduler tool used to manage
the timely execution of jobs and scripts. These can be used for any purpose, but one of the
main uses is the scheduling of maintenance tasks such as Nightly backups that are better (due
to performance) to be run out of hours or off peak times.

SQL Profiler

The SQL Profiler monitors activity on the select SQL Server and can be used for many tasks
including performance monitoring (how efficiently queries are running) and real time auditing of
the SQL Server overview.

Data Transformation Services (Client)

7
Data Transformation Services (DTS) is a useful tool that allows data to be moved from one data
source to another. Its simple GUI interface is the DTS Designer which can be accessed through
Enterprise Manager and allows the tasks to be developed quickly; on the fly.

SQL Server Enterprise Manager (Client)

SQL Server Enterprise Manager (EM) is one of the client tools supplied with SQL Server that
provides users with a GUI interface to manage all SQL Servers installed within your
environment and also allows you to manage the databases that reside on the servers. This is
discussed in more detail in a later article.

Query Analyser

Microsoft’s Query Analyser allows you to write and run your own Transact SQL statements. It
allows you to parse your code before running it to check for syntax errors and also provides
some useful colour co-ordination that changes the colour of key words etc.
8
Replication (Server)

Replication is one of the more advanced features available in SQL Server and although not
covered in this series of articles is worth mentioning at this point. SQL Server Replication allows
data to be synchronised between two or more databases on different SQL Servers or even
other platforms as long as they accessible by ODBC or OLEDB

Microsoft Full Text Searching Services

This service provides full text searching capabilities and is useful for searching large text fields.

SQL Server Analysis Services

Is an essential service when implementing a data warehouse solution using SQL Server, these
Service are often referred to Online Analytical Processing (OLAP).

9
SQL Server Data Types
String types:
Data type Description Storage
char(n) Fixed width character string. Maximum 8,000 characters Defined width
2 bytes + number of
varchar(n) Variable width character string. Maximum 8,000 characters
chars
Variable width character string. Maximum 1,073,741,824 2 bytes + number of
varchar(max)
characters chars
4 bytes + number of
text Variable width character string. Maximum 2GB of text data
chars
nchar Fixed width Unicode string. Maximum 4,000 characters Defined width x 2
nvarchar Variable width Unicode string. Maximum 4,000 characters
Variable width Unicode string. Maximum 536,870,912
nvarchar(max)
characters
ntext Variable width Unicode string. Maximum 2GB of text data
bit Allows 0, 1, or NULL
binary(n) Fixed width binary string. Maximum 8,000 bytes
varbinary Variable width binary string. Maximum 8,000 bytes
varbinary(max) Variable width binary string. Maximum 2GB
image Variable width binary string. Maximum 2GB
Number types:
Data type Description Storage
tinyint Allows whole numbers from 0 to 255 1 byte
smallint Allows whole numbers between -32,768 and 32,767 2 bytes
int Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes
Allows whole numbers between -9,223,372,036,854,775,808 and
bigint 8 bytes
9,223,372,036,854,775,807
Fixed precision and scale numbers.
Allows numbers from -10^38 +1 to 10^38 –1.
The p parameter indicates the maximum total number of digits that can
be stored (both to the left and to the right of the decimal point). p must 5-17
decimal(p,s)
be a value from 1 to 38. Default is 18. bytes
The s parameter indicates the maximum number of digits stored to the
right of the decimal point. s must be a value from 0 to p. Default value
is 0
Fixed precision and scale numbers.
Allows numbers from -10^38 +1 to 10^38 –1.
The p parameter indicates the maximum total number of digits that can
be stored (both to the left and to the right of the decimal point). p must 5-17
numeric(p,s)
be a value from 1 to 38. Default is 18. bytes
The s parameter indicates the maximum number of digits stored to the
right of the decimal point. s must be a value from 0 to p. Default value
is 0
smallmoney Monetary data from -214,748.3648 to 214,748.3647 4 bytes
Monetary data from -922,337,203,685,477.5808 to
money 8 bytes
922,337,203,685,477.5807
Floating precision number data from -1.79E + 308 to 1.79E + 308.
The n parameter indicates whether the field should hold 4 or 8 bytes. 4 or 8
float(n)
float(24) holds a 4-byte field and float(53) holds an 8-byte field. Default bytes
value of n is 53.
10
real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes
Date types:
Data type Description Storage
From January 1, 1753 to December 31, 9999 with an accuracy of 3.33
datetime 8 bytes
milliseconds
From January 1, 0001 to December 31, 9999 with an accuracy of 100
datetime2 6-8 bytes
nanoseconds
smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute 4 bytes
date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes
time Store a time only to an accuracy of 100 nanoseconds 3-5 bytes
8-10
datetimeoffset The same as datetime2 with the addition of a time zone offset
bytes
Stores a unique number that gets updated every time a row gets
created or modified. The timestamp value is based upon an internal
timestamp
clock and does not correspond to real time. Each table may have only
one timestamp variable

11
SUMMATIVE QUIZ

Self-Check Activity 1.1


Problem No. 1 (10 points)
1. Create a database given the following field names, name you database as
dbTimeShare.

Procedures:
1. Set the data type for most fields to Text, with the exception of the following:
Set the Fees field data type to Currency and zero decimal points.
Set the Code field’s data type to Number and Long Integer.
Set the Owner and Paid up Member fields data type to Yes/No with No as the default.

2. Use Input masks for Phone fields.


3. Ensure you have two tables to store the relevant data.
4. Set up a Primary Keys in each table as an index.
5. Ensure that a common field is in both tables so that a relationship can be established
between the tables.
6. Write the table name and add your suggested fields to the Field Names part of the form
on the next page. Add your suggestions in the Field Sizes and Data Type areas.
7. Populate your tables with at least 10 records each.

Also note the appropriate Format.

2. Create your own database applying the correct data type for each field.
(5 points)
Note: Populate you records with at least 10 records each.
3. Create an Employee Information Database with a minimum of four tables.(Apply
the correct assignment of data type for each field) (10 points)
Note: Populate you records with at least 10 records each.

12
TOPIC 2: RELATIONAL DATABASE MANAGEMENT SYSTEM W/ TABLE
NORMALIZATION

OBJECTIVES

At the end of the period, learners should be able to:


1. Identify Three Classical Model
2. Understand the Relational Database Concepts
3. Identify Types of Table Keys
4. Understand Table Join Relationships
5. Learn and Understand Table Normalization

LECTURE

RELATIONAL DATABASE

Three classical data models

1. hierarchical model
2. network model
o each tuple is a separate record, e.g., (AN 145) --- [Perugini] --- (CPS 430)
o no separation between logical and physical views
o used record-at-a-time languages
o too low-level
3. relational model
o proposed by E.F. Codd in 1969
o most popular and successful model
o de facto standard for databases
o (relational) databases are one of the most popular success stories of simple
theoretical ideas
o the focus of CPS 430/542

Relational Database
• Definition:

• Data stored in tables that are associated by shared attributes (keys).

• Any data element (or entity) can be found in the database through the name of
the table, the attribute name, and the value of the primary key.

Relational Database Definitions


• Entity: Object, Concept or event (subject)

13
• Attribute: a Characteristic of an entity

• Row or Record: the specific characteristics of one entity

• Table: a collection of records

• Database: a collection of tables

The Relational Database model


• Developed by E.F. Codd, C.J. Date (70s)

• Table = Entity = Relation

• Table row = tuple = instance

• Table column = attribute

• Table linkage by values

• Entity-Relationship Model

The Relational Model


• Each attribute has a unique name within an entity

• All entries in the column are examples of it

• Each row is unique

• Ordering of rows and columns is unimportant

• Each position (tuple) is limited to a single entry.

Data Model: What’s a model?


• A data model is a representation of reality

• It’s used to define the storage and manipulation of a data base.

14
Relational Database Definitions
• Entity: Object, Concept or event (subject)

• Attribute: a Characteristic of an entity

• Row or Record: the specific characteristics of one entity

• Table: a collection of records

• Database: a collection of tables

The Relational Database model


• Developed by E.F. Codd, C.J. Date (70s)

• Table = Entity = Relation

• Table row = tuple = instance

• Table column = attribute

• Table linkage by values

• Entity-Relationship Model

The Relational Model


• Each attribute has a unique name within an entity

• All entries in the column are examples of it

• Each row is unique

• Ordering of rows and columns is unimportant

• Each position (tuple) is limited to a single entry.

Advantages of Relational Database over Flat File

1. Avoids Data Duplication

2. Avoid Inconsistent Records

3. Easier to change Data

4. Easier to change data format

5. Data can be added and remove easily

6. Easier to maintain security

Database Table Keys

15
Definition:
A key of a relation is a subset of attributes with the following attributes:
• Unique identification

• Non-redundancy

Types of Keys
a. PRIMARY KEY

• Serves as the row level addressing mechanism in the relational database model.

• It can be formed through the combination of several items.

• Indicates uniqueness within records or rows in a table

b. FOREIGN KEY

• A column or set of columns within a table that are required to match those of a
primary key of a second table.

• the primary key from another table, this is the only way join relationships can be
established.

These keys are used to form a RELATIONAL JOIN - thereby connecting row to row
across the individual tables.

Keys
• Primary key – minimal subset of fields that is unique identifier for a tuple

• sid is primary key for Students

• cid is primary key for Courses

• Foreign key –connections between tables

• Courses (cid, instructor, quarter, dept)

• Students (sid, name, login, age, gpa)

• How do we express which students take each course?

Constructing Join Relationships


• One-to-many relationships include the Primary Key of the ‘one’ table and a Foreign Key
(FK) in the ‘many’ table.

• Cardinality: one-to-one, one-to-many, many-to-many relationships

Optionality: the relationship is either mandatory or optional

16
Normalization
• Normalization: a process for analyzing the design of a relational database

• Database Design - Arrangement of attributes into entities

• It permits the identification of potential problems in your database design

• Concepts related to Normalization:

• KEYS and FUNCTIONAL DEPENDENCE

8. Database Normalization (1)

• Sample Student Activities DB Table

• Poorly Designed

• Non-unique records

• John Smith

• Test the Design by developing


sample reports and queries

9. Database Normalization (2)


● Created a unique “ID” for each Record
in the Activities Table
● Required the creation of an “ID” look-
up table for reporting (Students Table)
● Converted the “Flat-File into a
Relational Database

3. Database Normalization (3)


• Wasted Space

• Redundant data entry

• What about taking a 3rd Activity?

• Query Difficulties - trying to find all swimmers

• Data Inconsistencies - conflicting prices

4. Database Normalization (4)

17
● Students table is fine

● Elimination of two columns and


an Activities Table restructuring,
Simplifies the Table

● BUT, we still have Redundant


data (activity fees) and data
insertion anomalies.
Problem: If student #219
transfers we lose all references
5. Database Normalization (5) to Golf and its price.
• Modify the Design to ensure that
“every non-key field is dependent
on the whole key”
• Creation of the Participants
Table, corrects our problems and
forms a union between 2 tables.

This is a Better Design!

18
Database Design: Basic Steps
Step 1: Determine the entities involved and create a separate table for each type of entity (thing,
concept, event, theme) and name it.
Step 2: Determine the Primary Key for each table.
Step 3: Determine the properties for each entity (the non-key attributes).
Step 4: Determine the relationships among the entities

Database Views
• A View is an individual’s picture of a database. It can be composed of many tables,
unbeknownst to the user.

• It’s a simplification of a complex data model

• It provides a measure of database security

• Views are useful, primarily for READ-only users and are not always safe for
CREATE, UPDATE, and DELETE.

Table Indexing
• An Index is a means of expediting the retrieval of data.

• Indexes are “built” on a column(s).niIndexes aren’t technically necessary for operation


and must be maintained by the database administrator.

19
SUMMATIVE QUIZ

Self-Check Activity 2.1

Problem No. 1 (5 points)

a. A company database needs to store information about employees (identified by ssn,


with salary and phone as attributes), departments (identified by dno, with dname and
budget as attributes), and children of employees (with name and age as attributes).

b. Employees work in departments; each department is managed by an employee; a


child must be identified uniquely by name when the parent (who is an employee; assume
that only one parent works for the company) is known. We are not interested in
information about a child once the parent leaves the company.

Note: Populate your tables with at least 10 records.

Problem No. 2 (10 points)

a. Although you always wanted to be an artist, you ended up being an expert on


databases because you love to cook data and you somehow confused database with
data baste. Your old love is still there, however, so you set up a database company,
ArtBase that builds a product for art galleries. The core of this product is a database with
a schema that captures all the information that galleries need to maintain.
b. Galleries keep information about artists, their names (which are unique), birthplaces,
age,and style of art. For each piece of artwork, the artist, the year it was made, its
unique title, its type of art (e.g., painting, lithograph, sculpture, photograph), and its price
must be stored. Pieces of artwork are also classified into groups of various kinds, for
example, portraits, still lifes, works by Picasso, or works of the 19th century; a given
piece may belong to more than one group.
c. Each group is identified by a name (like those just given) that describes the group.
Finally, galleries keep information about customers. For each customer, galleries keep
that person’s unique name, address, total amount of dollars spent in the gallery (very
important!), and the artists and groups of art that the customer tends to like.

Note: Populate your tables with at least 10 records.

20
Problem No. 3 (10 points)

Design a Relational Database for Access Registrar’s Office. The Office maintains data about
each class, including the instructor, the number of student enrolled, and the time and place of
the class meetings. For each student-class pair, a grade is recorded.

Underlined attributes indicate the primary key.

Student (StudentID, Name, Program)


Course (CourseNo, Title, Syllabus, Credits)
CourseOffering (CourseNo, SectionNo, Year, Semester, Time, Room)
Instructor (InstructoNo, Name, Department, Title)
Enrols (StudentNo, CourseNo, SectionNo, Semester, Year, Grade)
Teaches (CourseNo, SectionNo, Semester, Year, InstructorNo)
Requires (MainCourse, PreRequisite)

21
TOPIC 3: SQL BASIC QUERIES, INSERT, UPDATE AND DELETE STATEMENT

OBJECTIVES

At the end of the period, learners should be able to:


1. Understand Structured Query Language
2. Identify Common SQL Commands
3. Learn and understand SQL Insert Statement
4. Learn and understand SQL Update Statement
5. Learn and understand SQL Delete Statement

What is SQL?

⚫ SQL (Structured Query Language)


is the standard language for commercial DBMSs

⚫ SEQUEL (Structured English QUEry Language)


was originally defined by IBM for SYSTEM R

mid 1970s

unofficial pronunciation (see-kwuhl) still sometimes used

⚫ standardization of SQL began in the 80s

⚫ current standard is SQL-99n subsequent revisions are not fully accepted by all vendors

⚫ SQL is a standard database protocol, adopted by most ‘relational’ databases

22
COMMON COMMANDS

1. CREATE TABLE SALESREP

2. DELETE table WHERE expression

Data Retrieval
3. SELECT list FROM table WHERE condition

• list - a list of items or * for all items

• WHERE - a logical expression limiting the number of records selected

• can be combined with Boolean logic: AND, OR, NOT

• ORDER may be used to format results

Example:
SELECT Ssn
FROM EMPLOYEE
WHERE Salary > 60000;

4. UPDATE tables SET item = expression WHERE expression

5. INSERT INTO table VALUES …..

SQL commands

⚫ Administration: ⚫ Data Modification:


⚫ CREATE DATABASE INSERT
⚫ CREATE SCHEMA DELETE
⚫ SET ROLE UPDATE
⚫ GRANT PRIVILEGES
⚫ Queries:
⚫ Data Definition: SELECT
⚫ CREATE TABLE
⚫ ALTER TABLE
⚫ DROP TABLE
⚫ CREATE VIEW

23
SQL INSERT STATEMENT

STEP by STEP Instruction:


1. Create a SQL SERVER Database and name it dbSample.
2. Create two (2) new tables and name it as Students and Persons.
TableName: Students
FieldName DataType
StudentNo nchar(11)
LastName nvarchar(30)
FisrtName nvarchar(30)
Course Nvarchar(10)
YearLevel int
Graduating bit
Birthday Date

TableName: Persons
FieldName DataType
PersonID int
LastName nvarchar(30)
FisrtName nvarchar(30)
ContactNumber nchar(20)

Create/Open a new Query window. Make sure that you have selected dbSample database

Using SQL INSERT STATEMENT:

Type the following code and hit execute (F5). Record your observation.

INSERT INTO Students ( StudentNo, LastName, FirstName,


Course, YearLevel, Graduating,
Birthday)
VALUES ('2012012345', 'Gates', 'Bill', 'BSCpE', 2, 0, '11/4/80')

Type the following code and hit execute (F5) to verify if a new record has been inserted:
SELECT * FROM Students

Insert another record using this following code. Execute (F5) and record your observation.
INSERT Students (StudentNo, LastName, FirstName, Course)
VALUES ('2012012346', 'Allen, 'Paul', 'BSChE')

24
SELECT * FROM Students

Insert another record using this following code. Execute (F5) and record your observation.

25
INSERT Students
VALUES ('2012012347', 'Lenon', ‘John’, 'BSMath', 4, 1,
'3/1/1981')
SELECT * FROM Students

Insert another record using this following code. Execute (F5) and record your observation.

INSERT Students
VALUES ('2012012348', 'Aquino', 'Noynoy', 'BSMath', 4, 1)
SELECT * FROM Students
(note: record the error that will appear and try to understand what causes it)

Type the following code and hit execute (F5). Record your observation.

INSERT Persons
VALUES (101, 'De' + '-' + 'Leon', 'Joey', ‘123-2234’)
SELECT * FROM Persons

Type the following code and hit execute (F5). Record your observation.

INSERT Persons
VALUES (102, 'Sotto', 'Vic', ‘8890-908’),
(103, 'Sotto', 'Tito', ‘768-6789’),
(104, 'Santos', 'Jimmy',’5778-678’)
SELECT * FROM Persons

INSERT Persons
SELECT 102, 'Sotto', 'Vic', ‘789-8900’
UNION ALL
SELECT 103, 'Sotto', 'Tito', ‘4566-789’
UNION ALL
SELECT 104, 'Santos', 'Jimmy', ‘779-8900’

SELECT * FROM Persons

Type the following code and hit execute (F5). Record your observation.

INSERT Students (StudentNo, LastName, FirstName, Course, YearLevel)


SELECT '2012012348', LastName, FirstName, 'BSCPE', 1 FROM Persons
WHERE FirstName = 'Vic'
SELECT * FROM Students

26
SQL UPDATE STATEMENT:

Type the following code and hit execute (F5). Record your observation.

UPDATE Students
SET YearLevel = 3
WHERE StudentNo = '2012012345'

SELECT * FROM Students

Type the following code and hit execute (F5). Record your observation.

UPDATE Students
SET Course = 'BS CompEng'
WHERE Course = 'BSCpE'
SELECT * FROM Students

Type the following code and hit execute (F5). Record your observation.
UPDATE Students
SET Course = 'BSME', YearLevel = 2, Birthday = '1/1/1985'
WHERE StudentNo = '2012012346'
SELECT * FROM Students
Type the following code and hit execute (F5). Record your observation.

UPDATE Students
SET Course = REPLACE (Course, 'BS CompEng', 'BSCpE')
SELECT * FROM Students

SQL DELETE STATEMENT:

Type the following code and hit execute (F5). Record your observation.

SELECT * FROM Persons


DELETE FROM Persons
WHERE PersonID = 104

SELECT * FROM Persons

Type the following code and hit execute (F5). Record your observation.

DELETE FROM Persons

SELECT * FROM Persons

27
SUMMATIVE QUIZ

Self-Check Activity 3.1

Using SQL INSERT, UPDATE, and DELETE statement, Write the corresponding SQL
Query that will accomplish the following operations:

Problem No. 1 (5 points)


Below is the ERD from the previous section for a generic sales system. Write the INSERT
statements to insert the data provided below.

A. PRODUCTS

1, 2012-01-01 12:30:45, 1, Chair, 10.00, 1


2, 2012-01-01 12:46:19, 1, Table, 26.40, 1

B. SALES_AGENTS

1, 2012-01-01 11:35:11, 1, Joe Bloggs, 1


2, 2012-01-01 11:48:12, 1, Bob the Builder, 1

C. SALES

1, 2012-01-02 14:39:10, 1, 1, 6, 1, 2012-01-02, 1


2, 2012-01-02 14:48:00, 1, 2, 1, 1, 2012-01-02, 1
3, 2012-01-02 15:40:38, 1, 1, 10, 1, 2012-01-02, 1
4, 2012-01-02 16:01:34, 1, 1, 8, 2, 2012-01-02, 1
5, 2012-01-02 16:45:01, 1, 2, 2, 2, 2012-01-02, 1
6, 2012-01-03 09:49:10, 1, 1, 6, 2, 2012-01-03, 1
7, 2012-01-03 10:28:00, 1, 2, 1, 1, 2012-01-03, 1
8, 2012-01-03 12:30:28, 1, 1, 2, 2, 2012-01-03, 1
9, 2012-01-03 16:21:34, 1, 1, 8, 1, 2012-01-03, 1

28
Problem No. 2 (10 points)

Create a Student’s Information Database with 2 tables as shown below:

1. Insert ten (10) records to Students table. Records must be diverse. (Note:. YearLevel varies
from 1 to 5, Course like BSEE, BSCpE, BSEcE, BSIT etc.)
2. Copy (using Insert) all student records with Course ‘BSCpE’ to Persons table.
3. Change the Graduating field value to 1 for all student records having YearLevel of 5.
4. Delete all EcE students.

Problem No. 3 (10 points)

Below is a selection from the "Customers" table:

1. Write a query that will delete the record of ‘Alfreds Futterkiste’.


2. Write a query that will delete the record of ‘Around the Horn’.
3. Insert the following using SQL Insert Statement:
6, Bill Gates, Bill_Gates, Tondo, Manila, 1201, Philippines
7, John Brain, John_Brain, San Fernando, Pampanga, 12002, Philippines
8, Maria Sy, Maria_Sy, Obando, Bulacan, 2302, Philippines
4. Modify the records of Bill Gates using SQL Update Statement; change his address into
Cavite and his City address into Cavite City.
5. Modify the records of Maria Sy except her CustomerID and Contact Name using SQL
Update Statement.

29
TOPIC 4: SQL QUERIES (Advance Select Statement)

OBJECTIVES

At the end of the period, learners should be able to:


1. Learn and understand Single Table Queries
2. Learn and understand Join Tables
3. Learn and understand Where Clause
4. Learn and understand SQL Query Aliasing
5. Learn and understand SQL Query Operations and Functions

LECTURE

SQL Queries
⚫ Queries in SQL are variations
of the SELECT command

SELECT <attribute list>


FROM <table list>
WHERE <condition>;

1. Single Table Queries

SELECT Ssn
FROM EMPLOYEE
WHERE Salary > 60000;
SELECT City, State
FROM AIRPORT
WHERE Airport_code = ‘SFO’;
2. Join as Select & Cross

● Retrieve the name and address of all employees who work


for the 'Research' department.
SELECT FNAME, LNAME, ADDRESS
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND DNUMBER=DNO

● For every project located in 'Stafford', list the project number,


the controlling department number, and
the department manager's last name, address, and birthdate.

SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS


FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNUM=DNUMBER AND MGRSSN=SSN
AND PLOCATION='Stafford’

30
▪ Tuple Variables (Aliases)

⚫ We can give names to the tuples coming


from each of the input relations

SELECT E.Lname, D.Dname


FROM EMPLOYEE E, DEPARTMENT D
WHERE E.Ssn = D.Mgr_ssn;

⚫ This can disambiguate common attribute names


and improve readability

⚫ Attributes can also be renamed in the FROM clause

⚫ similar to alternate rename syntax in the algebra

SELECT Fn, Ln
FROM EMPLOYEE E(Fn, Mi, Ln, Bd, Ad, Sx, Sl, Sssn, Dn)
WHERE Dn = 4;

▪ Self-Join

⚫ For each employee, retrieve the employee's name,


and the name of his or her immediate supervisor.

SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME


FROM EMPLOYEE E, EMPLOYEE S
WHERE E.SUPERSSN=S.SSN

⚫ Aliases are necessary for this query

⚫ Think of E and S as two different copies of EMPLOYEE

E represents employees in role of supervisees and


S represents employees in role of supervisors

31
▪ Aliases: alternate syntax

⚫ Can also use the AS keyword to specify aliases

SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME


FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.SUPERSSN=S.SSN

⚫ Can also simply use the relation names


(when non-ambiguous)

SELECT EMPLOYEE.Lname, DEPARTMENT.Dname


FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.Ssn = DEPARTMENT.Mgr_ssn;

⚫ To retrieve all the attribute values of the selected tuples,


use *, which stands for all the attributes

SELECT *
FROM EMPLOYEE
WHERE DNO=5

SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND
DNO=DNUMBER

32
▪ Tables as Sets 🡪 DISTINCT

⚫ SQL does not treat a relation as a set;


duplicate tuples can appear

⚫ To eliminate duplicate tuples in a query result,


the keyword DISTINCT is used

SELECT SALARY
FROM EMPLOYEE May contain duplicates
SELECT DISTINCT SALARY
FROM EMPLOYEE

▪ Set Operations Duplicates eliminated

⚫ union operation (UNION)


intersection (INTERSECT)
set difference (MINUS, sometimes called EXCEPT)

some implementations of SQL do not support all set operations

Set operation results are sets of tuples


duplicate tuples are eliminated from the result

The set operations apply only to union compatible relations:


the two relations must have the same attributes and
the attributes must appear in the same order

▪ Set Operations: Example

⚫ List project numbers for all projects that involve


an employee whose last name is 'Smith' as a worker
or as a manager of the department that controls the project.

(SELECT PNAME
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith')

UNION

(SELECT PNAME
FROM PROJECT, WORKS_ON, EMPLOYEE
WHERE PNUMBER=PNO AND ESSN=SSN AND NAME='Smith')

▪ Multiset Operations

⚫ UNION ALL, INTERSECT ALL, EXCEPT ALL

⚫ Multiset operation results are multisets of tuples


duplicate tuples are not eliminated

33
(SELECT PNAME
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith')
UNION ALL
(SELECT PNAME
FROM PROJECT, WORKS_ON, EMPLOYEE
WHERE PNUMBER=PNO AND ESSN=SSN AND NAME='Smith')

▪ WHERE Clause

⚫ WHERE clause is a general boolean expression

⚫ Boolean operators:
AND, OR, NOT

⚫ Comparison operators:
=, <, <=, >, >=, <>

⚫ String comparison operators:


LIKE

⚫ Parentheses can be used to set precedence

⚫ String literals can be enclosed in "…" or '…'

34
▪ String Comparison

⚫ The LIKE comparison operator


is used to compare partial strings

⚫ Two wildcard characters are used:

'%' replaces an arbitrary number of characters

'_' replaces a single arbitrary character

▪ String Comparison Example

⚫ Retrieve all employees


whose address is in Houston, Texas.

⚫ The value of the ADDRESS attribute must


contain the substring “Houston, TX”.

SELECT FNAME, LNAME


FROM EMPLOYEE
WHERE ADDRESS LIKE '%Houston, TX%'
⚫ Retrieve all employees who were born during the 1960s.

‘6' must be the 3rd character of the 10 character date string

SELECT FNAME, LNAME


FROM EMPLOYEE
WHERE BDATE LIKE '_ _ 6 _ _ _ _ _ _ _'
Following would also work:
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE BDATE LIKE '_ _ 6 %'

35
▪ Arithmetic Operation

⚫ The standard arithmetic operators '+', '-'. '*', and '/'


can be applied to numeric values in an SQL query result

⚫ Show the effect of giving all employees who work


on the 'ProductX' project a 10% raise.

SELECT FNAME, LNAME, 1.1*SALARY


FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE SSN=ESSN AND PNO=PNUMBER AND
PNAME='ProductX’

▪ Aggregate Functions

⚫ Aggregate functions are applied to result attributes


COUNT, SUM, MAX, MIN, and AVG

⚫ Find the maximum salary, the minimum salary,


and the average salary among all employees.

SELECT MAX(Salary), MIN(Salary), AVG(Salary)


FROM EMPLOYEE
⚫ Find the total salary paid to employees
who work for the 'Research' department.

SELECT SUM(Salary)
FROM EMPLOYEE, DEPARTMENT
WHERE Dno=Dnumber AND Dname='Research'

36
⚫ Retrieve the total number of employees in the
company and the number of employees in the
Research' department.

SELECT COUNT (*)


FROM EMPLOYEE
SELECT COUNT (*)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME='Research’

▪ Join

SELECT * FROM r;
+---+------+ SELECT * FROM s;
| x | y | +---+------+
+---+------+ | a | b |
| 3 | 4 | +---+------+
| 5 | 6 | | 2 | 3 |
| 7 | 8 | | 4 | 7 |
| 9 | 6 | +---+------+
SELECT
+---+------+r,s WHERE y=a;
* FROM
+---+------+---+------+
| x | y | a | b |
+---+------+---+------+
| 3 | 4 | 4 | 7 |
+---+------+---+------+

37
▪ Explicit Join

⚫ Joins can be explicitly stated in the FROM clause.

SELECT * FROM (r JOIN s ON y=a);


+---+------+---+------+
| x | y | a | b |
+---+------+---+------+
▪ Left/Right Outer Join
| 3 | 4 | 4 | 7 |
+---+------+---+------+

SELECT * FROM (r LEFT JOIN s ON y=a);


+---+------+------+------+ SELECT * FROM (r RIGHT JOIN
| x | y | a | b | s ON y=a);
+---+------+------+------+ +------+------+---+------+
| 3 | 4 | 4 | 7 | | x | y | a | b |
| 5 | 6 | NULL | NULL | +------+------+---+------+
| 7 | 8 | NULL | NULL | | NULL | NULL | 2 | 3 |
| 9 | 6 | NULL | NULL | | 3 | 4 | 4 | 7 |
+------+------+---+------+
+---+------+------+------+ ▪ Ordering Results

⚫ An ORDER BY clause can be added


to order the result tuples

SELECT * FROM SELECT * FROM t


SELECT * FROM t ORDER BY i;
t;
ORDER BY j; +----+--------+
+----+--------+
+----+--------+ | i | j |
| i | j |
| i | j | +----+--------+
+----+--------+
+----+--------+ | 4 | four |
| 10 | ten |
| 11 | eleven | | 10 | ten |
| 11 | eleven |
| 4 | four | | 11 | eleven |
| 20 | twenty |
| 10 | ten | | 20 | twenty |
| 4 | four |
| 20 | twenty | +----+--------+
+----+--------+
+----+--------+

38
▪ ORDER BY Examples

⚫ order by Lname first,


then by Fname if Lname is the same:

SELECT Lname, Fname


FROM Employee
WHERE salary > 60000
ORDER BY Lname, Fname
⚫ order by Lname in ascending order,
then by salary in descending order

SELECT Lname, salary


FROM Employee
WHERE salary > 60000
ORDER BY Lname ASC, salary DESC

▪ Grouping

⚫ Forms groups (subsets) of result tuples


before applying aggregate functions

⚫ Example: count the number of employees


in each department
(group employees by DNO, then count tuples in each group)

+-----+--------+
| Dno | COUNT |
+-----+--------+
SELECT Dno, COUNT(*)
| 8 | 120 |
FROM Employee
| 22 | 238 |
GROUP BY Dno
| 7 | 82 |
| 20 | 169 |
+-----+--------+

39
▪ GROUP BY Example

⚫ For each project, get the project name,


project number and the number of employees
working on that project

SELECT Pnumber, Pname, COUNT(*)


FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno
GROUP BY Pnumber, Pname

▪ Filtering Groups: HAVING

⚫ We can throw away some groups


by adding a condition in a HAVING clause

⚫ example:
for each project that has more than two employees,
get the project name, project number and
the number of employees working on that project

SELECT Pnumber, Pname, COUNT(*)


FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno
GROUP BY Pnumber, Pname
HAVING COUNT(*) > 2

▪ GROUP BY Examples
SELECT COUNT(*) FROM e
GROUP BY dept;
+----------+
| count(*) |
+----------+
SELECT * FROM e;
| 3 |
+-----+--------+-------+
| 3 |
| eid | salary | dept |
| 1 | SELECT dept, COUNT(*)
+-----+--------+-------+
+----------+ FROM e GROUP BY dept;
| E01 | 65000 | ADMIN |
| E12 | 58400 | ENGR | +-------+----------+
| E08 | 76900 | ENGR | | dept | count(*) |
| E23 | 63800 | ADMIN | +-------+----------+
| E07 | 56900 | ADMIN | | ADMIN | 3 |
| E27 | 76400 | ENGR | | ENGR | 3 |
| E14 | 48000 | TEST | | TEST | 1 |
+-----+--------+-------+ +-------+----------+

40
SELECT: Syntax Summary

SELECT <attribute and function list> required


FROM <table list>
WHERE <condition>
SELECT: conceptual execution
GROUP BY <grouping attributes>
HAVING <groupcross
condition> optional
1. FROM: product of tables
ORDER BY <attribute list>
2. WHERE: select tuples

3. GROUP BY: group tuples

4. HAVING: filter groups

5. SELECT: project attributes and apply aggregates

6. ORDER BY: sort the tuples

41
SUMMATIVE QUIZ

Self-Check Activity 4.1

Problem No. 1 (5 points)


1. Create a database given the following table name and field name:

Emp(eid: integer, ename: string, age: integer, salary: real)


Works(eid: integer, did: integer, pcttime: integer)
Dept(did: integer, dname: string, budget: real, managerid: integer
2. Populate your tables with at least 10 records.

3. Write the SQL statements required to create the preceding relations, including
appropriate versions of all primary and foreign key integrity constraints.

Problem No. 2 (5 points)


1. Create a database given the following table name and field name:

Emp(eid: integer, ename: string, age: integer, salary: real)


Works(eid: integer, did: integer, pcttime: integer)
Dept(did: integer, dname: string, budget: real, managerid: integer

2. Populate your tables with at least 10 records.

3. Define the Dept relation in SQL so that every department is guaranteed to have a
manager.

Problem No. 3 (5 points)


3. Create a database given the following table name and field name:

Emp(eid: integer, ename: string, age: integer, salary: real)


Works(eid: integer, did: integer, pcttime: integer)
Dept(did: integer, dname: string, budget: real, managerid: integer

4. Populate your tables with at least 10 records.

5. Write an SQL statement to add John Doe as an employee with eid = 101, age = 32 and
salary = 15, 000.

42
Problem No. 4 (5 points)

1. Create a database given the following table name and field name:

Emp(eid: integer, ename: string, age: integer, salary: real)


Works(eid: integer, did: integer, pcttime: integer)
Dept(did: integer, dname: string, budget: real, managerid: integer

2. Populate your tables with at least 10 records.


3. Write an SQL statement to give every employee a 10 percent raise.

Problem No. 5 (5 points)

Below is an ERD for a generic library system.

1) Write the SELECT statements to return the number of books available, and the number of
books out on loan.

2) Write an SQL SELECT query to produce the following report:

43

You might also like