DAMASYS Students
DAMASYS Students
(DAMASYS)
SOFTWARE DEPARTMENT
OBJECTIVES
LECTURE
● `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.
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.
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!)
ACID properties
● 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
• Read
5
• Update
• Delete
Database Tables
• Tables represent entities
• Tables are always named in the singular, such as: Vehicle, Order, Grade, etc.
Attributes
• Characteristics of an entity
• Examples:
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's database engine is the primary server application of the SQL sever package. Its
main functions are:
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
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.
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 (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
This service provides full text searching capabilities and is useful for searching large text fields.
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
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. 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
LECTURE
RELATIONAL DATABASE
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:
• 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.
13
• Attribute: a Characteristic of an entity
• Entity-Relationship Model
14
Relational Database Definitions
• Entity: Object, Concept or event (subject)
• Entity-Relationship Model
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.
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
16
Normalization
• Normalization: a process for analyzing the design of a relational database
• Poorly Designed
• Non-unique records
• John Smith
17
● Students table is fine
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.
• 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.
19
SUMMATIVE QUIZ
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.
21
TOPIC 3: SQL BASIC QUERIES, INSERT, UPDATE AND DELETE STATEMENT
OBJECTIVES
What is SQL?
mid 1970s
⚫ current standard is SQL-99n subsequent revisions are not fully accepted by all vendors
22
COMMON COMMANDS
Data Retrieval
3. SELECT list FROM table WHERE condition
Example:
SELECT Ssn
FROM EMPLOYEE
WHERE Salary > 60000;
SQL commands
23
SQL INSERT STATEMENT
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
Type the following code and hit execute (F5). Record your observation.
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’
Type the following code and hit execute (F5). Record your observation.
26
SQL UPDATE STATEMENT:
Type the following code and hit execute (F5). Record your observation.
UPDATE Students
SET YearLevel = 3
WHERE StudentNo = '2012012345'
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
Type the following code and hit execute (F5). Record your observation.
Type the following code and hit execute (F5). Record your observation.
27
SUMMATIVE QUIZ
Using SQL INSERT, UPDATE, and DELETE statement, Write the corresponding SQL
Query that will accomplish the following operations:
A. PRODUCTS
B. SALES_AGENTS
C. SALES
28
Problem No. 2 (10 points)
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.
29
TOPIC 4: SQL QUERIES (Advance Select Statement)
OBJECTIVES
LECTURE
SQL Queries
⚫ Queries in SQL are variations
of the SELECT command
SELECT Ssn
FROM EMPLOYEE
WHERE Salary > 60000;
SELECT City, State
FROM AIRPORT
WHERE Airport_code = ‘SFO’;
2. Join as Select & Cross
30
▪ Tuple Variables (Aliases)
SELECT Fn, Ln
FROM EMPLOYEE E(Fn, Mi, Ln, Bd, Ad, Sx, Sl, Sssn, Dn)
WHERE Dn = 4;
▪ Self-Join
31
▪ Aliases: alternate syntax
SELECT *
FROM EMPLOYEE
WHERE DNO=5
SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND
DNO=DNUMBER
32
▪ Tables as Sets 🡪 DISTINCT
SELECT SALARY
FROM EMPLOYEE May contain duplicates
SELECT DISTINCT SALARY
FROM EMPLOYEE
(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
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
⚫ Boolean operators:
AND, OR, NOT
⚫ Comparison operators:
=, <, <=, >, >=, <>
34
▪ String Comparison
35
▪ Arithmetic Operation
▪ Aggregate Functions
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.
▪ 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
38
▪ ORDER BY Examples
▪ Grouping
+-----+--------+
| Dno | COUNT |
+-----+--------+
SELECT Dno, COUNT(*)
| 8 | 120 |
FROM Employee
| 22 | 238 |
GROUP BY Dno
| 7 | 82 |
| 20 | 169 |
+-----+--------+
39
▪ GROUP BY Example
⚫ 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
▪ 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
41
SUMMATIVE QUIZ
3. Write the SQL statements required to create the preceding relations, including
appropriate versions of all primary and foreign key integrity constraints.
3. Define the Dept relation in SQL so that every department is guaranteed to have a
manager.
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:
1) Write the SELECT statements to return the number of books available, and the number of
books out on loan.
43