Whats a Database?
Database Basics
a repository of information
a collection of records
Examples:
CS 391 Advanced Programming in Java
Database management systems (DBMS)
collections of tools used to manage databases
Four basic functions performed by all DBMS are:
your phone book
Airline reservation system
Medical records and billing data
Employment records
Schema:
Create,
modify, and delete data structures, e.g. tables
modify, and delete data
Retrieve data selectively
Generate reports based on data
describes the objects that are represented
in the database, and the relationships
among them.
Add,
Database Models
a number of different ways of modeling the database
structure: these are known as database models (or
data models).
The model in most common use today is the relational
model, which in layman's terms represents all
information in the form of multiple related tables each
consisting of rows and columns
Database Components
Related tables/Relations
Fields
Records
Table
Fields
A table is a collection of related records.
For example, employee table, product
table, customer, and orders tables.
In a table, records are represented by
rows and fields are represented as
columns.
an area (within a record) reserved for a specific
piece of data.
Examples: customer id, customer name, street
address, city, phone, current balance.
defined by:
Field
name
type
Field size (Amount of space reserved for storing data )
Data
Record/Tuple
A record is the collection of values for all
the fields pertaining to one entity: i.e. a
person, product, company, transaction,
etc.
Column (DOB is an attribute/field)
key field
Row/tuple/record
CustomerNo
Name
DOB
..
..
..
1234
Bilal
10/10/1977
Relationships
One-to-One
One-to-Many
Many-to-Many
Customer
Product
Order
Order
One-to-Many relationship: Customer-Order, each order has only one customer, but
a customer can make many orders.
One-to-Many relationships consist of two tables, the "one" table, and the "many"
table.
Many-to-Many relationship: Order-Product, an order can contain many products,
and a product can be on many orders.
A Many-to-Many relationship consists of three tables: two "one" tables, both in a
One-to-Many relationship with a third table. The third table is sometimes referred to
as the lien.
Example
Key Fields
Primary key: A Primary key is a field or a combination of two or more
fields. The value in the primary key field for each record uniquely
identifies that record.
CustomerId
Name
Address
Phone
Bilal
abc
12345
Ali
Xyz
54321
In our previous example, customer number is the Primary key for the
Customer table. A customer number identifies one and only one customer
in the Customer table.
Foreign key: When a "one" table's primary key field is added to a
related "many" table in order to create the common field which relates
the two tables, it is called a foreign key in the "many" table.
CUSTOMER
the primary key (customer number) from the Customer table ("one" table) is
a foreign key in the Orders table ("many" table). For the "many" records of
the Order table, the foreign key identifies with which unique record in the
Customer table they are associated.
Data types
CHAR
This will hold between 0 and 255 characters. You have to specify the maximum
amount of characters that you will be putting here when you create your column.
VARCHAR
This will hold as many characters as you like up to 2 gigabytes of space.
BIT
This can hold a value of 0 or 1. It is primarily used for yes/no and true/false issues.
It is also referred to as a Boolean or Yes/No field.
FLOAT
This type is used to store decimal numbers. It is primarily used for mathematical
purposes.
INT
This type indicates that you are storing whole numbers here. You can store any
whole number between -2147483648 and 2147483648.
SMALLINT
Same as above except you are limited to numbers between -32768 and 32768.
DATE
This stores a date. I know you're shocked.
DATETIME
This will store a date and time. It is also commonly referred to as a TIMESTAMP
since it is primarily used to Time Stamp entries or updates to a row or table.
ITEM
ItemID
Description
Price
QuantityInHand
Java: The Complete Reference
700
20
C++: The Complete Reference
700
25
ORDER
OrderId
1
CustomerId
1
Date
10/10/2006
AmountPayable
0
15/10/2006
500
20/10/2006
700
How Do I Create a Table?
Using an SQL statement.
CREATE TABLE contacts (
contact_id INT IDENTITY (1, 1) NOT NULL ,
first_name CHAR
(30) NULL ,
last_name CHAR
(50) NULL ,
email
VARCHAR (75) NULL
);
You will also find that every DBMS has its own quirks and syntax. That means the same Data Type can be referenced by different
names in different DBMS's. You'll have to check your DBMS documentation for specifics.
Designing a Table in a
Database Tool? .
Using Microsoft Access
INSERT statement
INSERT INTO contacts
(first_name, last_name, email)
VALUES (Bilal',Afzal',[email protected]);
UPDATE Statement
What is that NULL thing?
NULL
is how you tell the DBMS that you have
nothing to enter in this column.
Should I always list all of my table
columns?
Yes,
it improves readability for future code
updates
SELECT Statement
SELECT * FROM contacts;
SELECT first_name, email
FROM
contacts
WHERE
first_name = Bilal';
UPDATE contacts
SET
email = [email protected]
WHERE
contact_id = 1;
Example Queries
AND/OR operators
LIKE
There are a whole host of operators that you can use to make comparisons
and filter data. Keep in mind, though, each DBMS can be different and the
operators they choose to use can change from DBMS to DBMS.
Here are some of the most common operators that DBMSs use: =, <>, <, >,
<=,>=, IS NULL
Grouping
Imagine a scenario where you are running
a gift catalog business for corporations
and you want to know how many items
have been sold to each corporate client
you have. To accomplish this task you will
need to learn about COUNT and GROUP
BY.
SELECT * FROM contacts WHERE(first_name=Bilal' AND
last_name=Afzal') OR last_name=Ahmed';
SELECT * FROM contact WHERE last_name LIKE '%al';
ORDER BY Clause:
SELECT * FROM contacts ORDER BY last_name DESC;
COUNT
keeps a running total of the number of records
retrieved.
SELECT COUNT(*) AS sales_total FROM sales;
So, what you end up with here is the total number of all
of the rows on the "sales" table which will be stored in
the temporary column of "sales_total".
GROUP BY
Aggregate Functions
SELECT company_name, COUNT(*) AS
sales_by_company_total FROM sales GROUP BY
company_name;
The output would look something like this:
Function
Description
MAX()
This returns a selected column's highest value
MIN()
This returns a selected column's lowest value
company_name
sales_by_company_total
SUM()
This returns the sum of a selected column
----------------
-------------------------
AVG()
This returns the average value of a selected column
Amazon.com
478
COUNT()
This counts the number of rows in a selected column
Sears
222
CompUSA
512
Dollar General Stores
For sorted output:
SELECT company_name, COUNT(*) AS sales_by_company_total FROM sales
GROUP BY company_name ORDER BY company_name ASC;
Examples using Aggregate Functions
What's So Great About DISTINCT?
SELECT MAX(sale_total)FROM daily_receipts WHERE
sales_date = '01/01/2002
SELECT DISTINCT category FROM discussion_group;
SELECT MIN(event_date) FROM event WHERE
event_date > GETDATE();
SELECT COUNT(DISTINCT category) FROM
discussion_group;
SELECT SUM(sales) FROM daily_receipts WHERE
sales_date = '01/01/2002';
SELECT AVG(sales) FROM daily_receipts WHERE
sales_date = '01/01/2002';
This will give you the total number of unique categories in your
discussion group.
DELETE statement
References
DELETE
FROM contacts
WHERE contact_id = 3;
Database Systems: Principles Design and
Implementation by Catherine M. Ricardo.
Database Basics:
http://www.htmlgoodies.com/primers/database/article.ph
p/3478051
What if you dont provide the WHERE clause?