CH6 WEB Lecture
CH6 WEB Lecture
DATABASE
MYSQL Database System
MySQL is a very popular, open source database.
Officially pronounced “my Ess Que Ell”.
Handles very large databases; very fast
performance.
Why are we using MySQL?
Free (much cheaper than Oracle!)
Each student can install MySQL locally.
Easy to use Shell for creating tables, querying tables, etc.
Easy to use with Java JDBC
2
MySQL Architecture
Three layer model: The application layer contains common
network services for connection handling,
authentication and security. This layer is where
different clients interact with MySQL these
clients can written in different API's:.NET, Java,
C, C++, PHP, Python, Ruby, Tcl, Eiffel, etc...
The Logical Layer is where the MySQL
intelligence resides, it includes functionality for
query parsing, analysis, caching and all built-in
functions (math, date...). This layer also
provides functionality common wit
across the
storage engines. s
Web
Web
Server
Browser
(Client)
PHP
5
3-Tier Architecture
6
Client-Server Interaction
Make a request
(SQL query)
MySQL Client
Server Get results Program
7
Entering commands (1)
Show all the databases
SHOW DATABASES;
mysql> SHOW DATABASES;
+-------------+
| Database |
+-------------+
| bookstore |
| employee_db |
| mysql |
| student_db |
| test |
| web_db |
+-------------+
8
Entering commands (2)
Choosing a database and showing its
tables
USE test;
SHOW tables;
mysql> USE test;
Database changed
mysql> SHOW tables;
+----------------+
| Tables_in_test |
+----------------+
| books |
| name2 |
| names |
| test |
+----------------+
4 rows in set (0.00 sec)
mysql>
9
Entering commands (3)
Show the structure of a table
DESCRIBE names;
mysql> DESCRIBE names;
+-----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+----------------+
| id | int(11) | | PRI | NULL | auto_increment |
| firstName | varchar(20) | | | | |
| lastName | varchar(20) | | | | |
+-----------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
mysql>
10
Entering commands (4)
Show the rows of a table (all columns)
SELECT * FROM names;
mysql> SELECT * FROM names;
+----+-----------+------------+
| id | firstName | lastName |
+----+-----------+------------+
| 1 | Fred | Flintstone |
| 2 | Barney | Rubble |
+----+-----------+------------+
2 rows in set (0.00 sec)
mysql>
11
Entering commands (5)
Inserting a new record
INSERT INTO names (firstName,
lastName) VALUES ('Rock','Quarry');
SELECT * FROM names;
mysql> INSERT INTO names (firstName, lastName) VALUES ('Ralph', 'Quarry');
Query OK, 1 row affected (0.02 sec)
mysql> SELECT * FROM names;
+----+-----------+------------+
| id | firstName | lastName |
+----+-----------+------------+
| 1 | Fred | Flintstone |
| 2 | Barney | Rubble |
| 3 | Ralph | Quarry |
+----+-----------+------------+
3 rows in set (0.00 sec)
mysql>
12
Entering commands (6)
Updating a record
UPDATE names SET lastName = 'Stone'
WHERE id=3;
SELECT * FROM names;
mysql> UPDATE names SET lastName = 'Stone' WHERE id=3;
Query OK, 1 row affected (0.28 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> SELECT * FROM names;
+----+-----------+------------+
| id | firstName | lastName |
+----+-----------+------------+
| 1 | Fred | Flintstone |
| 2 | Barney | Rubble |
| 3 | Ralph | Stone |
+----+-----------+------------+
3 rows in set (0.00 sec)
mysql>
13
Database concepts (1)
A relational database management
system consists of a number of
databases.
Each database consists of a number of
column
tables. headings
Example table
isbn title author pub year price
books
rows
table
(records)
14
Some SQL data types (1)
Each entry in a row has a type
specified by the column.
Numeric data types
TINYINT, SMALLINT, MEDIUMINT,
INT, BIGINT
FLOAT(display_length, decimals)
DOUBLE(display_length, decimals)
DECIMAL(display_length, decimals)
NUMERIC is the same as DECIMAL
15
Some SQL data types (2)
Date and time types
DATE
format is YYYY-MM-DD
DATETIME
format YYYY-MM-DD HH:MM:SS
TIMESTAMP
format YYYYMMDDHHMMSS
TIME
format HH:MM:SS
YEAR
default length is 4
16
SQL data types (3)
String types
CHAR
fixed length string, e.g., CHAR(20)
VARCHAR
variable length string, e.g., VARCHAR(20)
BLOB, TINYBLOB, MEDIUMBLOB, LONGBLOB
same as TEXT, TINYTEXT ...
ENUM
list of items from which value is selected
17
SQL commands SHOW,
USE
SHOW
Display databases or tables in current
database;
Example (command line client):
show databases;
show tables;
USE
Specify which database to use
Example
use bookstore;
18
The CREATE Command (1)
CREATE creates a database table
CREATE TABLE table_name
(
column_name1 column_type1,
column_name2 column_type2,
...
column_nameN column_typeN
);
22
Conditional Creation
Conditional database creation
CREATE DATABASE IF NOT EXISTS
db_name;
Conditional table creation
CREATE TABLE IF NOT EXISTS
table_name;
23
The DROP Command
To delete databases and tables use the
DROP command
Examples
DROP DATABASE db_name;
DROP DATABASE IF EXISTS db_name;
DROP TABLE table_name;
DROP TABLE IF EXISTS table_name;
24
The INSERT Command
Inserting rows into a table
INSERT INTO table_name
( col_1, col_2, ..., col_N)
VALUES
( val_1, val_2, ...,
val_N);
25
The SELECT Command (1)
Selecting rows from a table
Simplest form: select all columns
SELECT * FROM table_name;
Select specified columns
SELECT column_list FROM table_name;
Conditional selection of rows
SELECT column_list FROM table_name
WHERE condition;
26
The SELECT Command (2)
Specifying ascending row ordering
SELECT column_list FROM table_name
WHERE condition
ORDER by ASC;
Specifying descending row ordering
SELECT column_list FROM table_name
WHERE condition
ORDER by DESC;
27
The SELECT Command (3)
There are many other variations of the
select command.
Example: finding the number of records
in a table assuming a primary key
called id:
SELECT COUNT(id) FROM table_name
USE test;
CREATE TABLE marks (
studentID SMALLINT AUTO_INCREMENT NOT NULL,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(20) NOT NULL,
mark SMALLINT DEFAULT 0 NOT NULL,
PRIMARY KEY (studentID)
);
30
marks.sql (2)
-- Insert some rows into marks table
INSERT INTO marks (first_name, last_name,
mark) VALUES ('Fred', 'Jones', 78);
INSERT INTO marks (first_name, last_name,
mark) VALUES ('Bill', 'James', 67);
INSERT INTO marks (first_name, last_name,
mark) VALUES ('Carol', 'Smith', 82);
INSERT INTO marks (first_name, last_name,
mark) VALUES ('Bob', 'Duncan', 60);
INSERT INTO marks (first_name, last_name,
mark) VALUES ('Joan', 'Davis', 86);
31
The Marks Table
Selecting the complete table
SELECT * FROM marks;
+-----------+------------+-----------+------+
| studentID | first_name | last_name | mark |
+-----------+------------+-----------+------+
| 1 | Fred | Jones | 78 |
| 2 | Bill | James | 67 |
| 3 | Carol | Smith | 82 |
| 4 | Bob | Duncan | 60 |
| 5 | Joan | Davis | 86 |
+-----------+------------+-----------+------+
5 rows in set (0.00 sec)
32
The WHERE Clause (1)
Select rows according to some criterion
SELECT * FROM marks WHERE studentID > 1
AND studentID < 5;
+-----------+------------+-----------+------+
| studentID | first_name | last_name | mark |
+-----------+------------+-----------+------+
| 2 | Bill | James | 67 |
| 3 | Carol | Smith | 82 |
| 4 | Bob | Duncan | 60 |
+-----------+------------+-----------+------+
3 rows in set (0.01 sec)
33
The WHERE Clause (2)
Select rows with marks >= 80
SELECT * FROM marks WHERE mark >= 80;
+-----------+------------+-----------+------+
| studentID | first_name | last_name | mark |
+-----------+------------+-----------+------+
| 3 | Carol | Smith | 82 |
| 5 | Joan | Davis | 86 |
+-----------+------------+-----------+------+
2 rows in set (0.00 sec)
34
The ORDER BY Clause
Select rows according to some criterion
SELECT * FROM marks ORDER BY mark DESC;
+-----------+------------+-----------+------+
| studentID | first_name | last_name | mark |
+-----------+------------+-----------+------+
| 5 | Joan | Davis | 86 |
| 3 | Carol | Smith | 82 |
| 1 | Fred | Jones | 78 |
| 2 | Bill | James | 67 |
| 4 | Bob | Duncan | 60 |
+-----------+------------+-----------+------+
5 rows in set (0.00 sec)
35
Searching Using LIKE (1)
LIKE is used to search a table for
values containing a search string:
There are two wild-card characters
used to specifiy patterns:
_ matches a single character
% matches zero or more characters
Can also use NOT LIKE
Searching is case insensitive
36
Searching Using LIKE (2)
Example: last names in marks table
that begin with J
SELECT * FROM marks WHERE last_name
LIKE 'J%';
37
Quoting strings
If a string contains a single quote it
must be backquoted (escaped) before
it can be used in a query
Example: find records containing
O'Reilly in the last_name field.
SELECT * FROM marks WHERE last_name
= 'O\'Reilly';
38
Limiting number of rows
LIMIT can be used to specify the
maximum number of rows that are to
be returned by a select query. Example
SELECT * FROM marks LIMIT 3;
This query will return only the first 3
rows from the marks table
To return 15 rows beginning at row 5
use
SELECT * FROM marks LIMIT 5, 15;
39
MySQL Functions (1)
How many rows are there ?
SELECT COUNT(*) FROM marks;
+----------+
| COUNT(*) |
+----------+
| 5 |
+----------+
1 row in set (0.00 sec)
+-----------+
| SUM(mark) |
+-----------+
| 373 |
+-----------+
1 row in set (0.00 sec)
41
MySQL Functions (3)
What is the average mark?
SELECT AVG(mark) FROM marks;
+-----------+
| AVG(mark) |
+-----------+
| 74.6000 |
+-----------+
1 row in set (0.00 sec)
42
MySQL Functions (4)
What is the minimum mark?
SELECT MIN(mark) FROM marks;
+-----------+
| MIN(mark) |
+-----------+
| 60 |
+-----------+
1 row in set (0.00 sec)
43
MySQL Functions (5)
What is the maximum mark?
SELECT MAX(mark) FROM marks;
+-----------+
| MAX(mark) |
+-----------+
| 86 |
+-----------+
1 row in set (0.00 sec)
44
books.sql (1)
isbn title author pub year price
books this is a
table simple
design
USE web_db;
CREATE TABLE books (
isbn CHAR(15) PRIMARY KEY NOT NULL,
title VARCHAR(100) NOT NULL,
author VARCHAR(100) NOT NULL,
pub VARCHAR(20) NOT NULL,
year YEAR NOT NULL,
price DECIMAL(9,2) DEFAULT NULL
);
45
books.sql (2)
-- Insert some books into books table
INSERT INTO books VALUES ('0-672-31784-2',
'PHP and MySQL Web Development',
'Luke Welling, Laura Thomson',
'Sams', 2001, 74.95
);
INSERT INTO books VALUES ('1-861003-02-1',
'Professional Apache',
'Peter Wainwright',
'Wrox Press Ltd', 1999, 74.95
);
46
employee_db.sql (1)
employeeID name position address
employees
table
employeeID hours
jobs
table
49
Select Queries With Joins
(1)
Cartesian product query
SELECT * FROM employees, jobs;
+------------+------+------------+--------------+------------+-------+
| employeeID | name | position | address | employeeID | hours |
+------------+------+------------+--------------+------------+-------+
| 1001 | Fred | programmer | 13 Windle St | 1001 | 13.50 |
| 1002 | Joan | programmer | 23 Rock St | 1001 | 13.50 |
| 1003 | Bill | manager | 37 Front St | 1001 | 13.50 |
| 1001 | Fred | programmer | 13 Windle St | 1002 | 2.00 |
| 1002 | Joan | programmer | 23 Rock St | 1002 | 2.00 |
| 1003 | Bill | manager | 37 Front St | 1002 | 2.00 |
| 1001 | Fred | programmer | 13 Windle St | 1002 | 6.25 |
| 1002 | Joan | programmer | 23 Rock St | 1002 | 6.25 |
| 1003 | Bill | manager | 37 Front St | 1002 | 6.25 |
50
Select Queries With Joins
(2)
Cartesian product query (continued)
| 1001 | Fred | programmer | 13 Windle St | 1003 | 4.00 |
| 1002 | Joan | programmer | 23 Rock St | 1003 | 4.00 |
| 1003 | Bill | manager | 37 Front St | 1003 | 4.00 |
| 1001 | Fred | programmer | 13 Windle St | 1001 | 1.00 |
| 1002 | Joan | programmer | 23 Rock St | 1001 | 1.00 |
| 1003 | Bill | manager | 37 Front St | 1001 | 1.00 |
| 1001 | Fred | programmer | 13 Windle St | 1003 | 7.00 |
| 1002 | Joan | programmer | 23 Rock St | 1003 | 7.00 |
| 1003 | Bill | manager | 37 Front St | 1003 | 7.00 |
| 1001 | Fred | programmer | 13 Windle St | 1003 | 9.50 |
| 1002 | Joan | programmer | 23 Rock St | 1003 | 9.50 |
| 1003 | Bill | manager | 37 Front St | 1003 | 9.50 |
+------------+------+------------+--------------+------------+-------+
21 rows in set (0.01 sec)
51
Select Queries With Joins
(3)
Substitution
SELECT name, hours FROM employees, jobs WHERE
employees.employeeID = jobs.employeeID;
+------+-------+
| name | hours |
+------+-------+
| Fred | 13.50 |
Here we are replacing
| Joan | 2.00 | the employeeID
| Joan | 6.25 | numbers in the jobs
| Bill | 4.00 |
| Fred | 1.00 | table by the employee's
| Bill | 7.00 | name
| Bill | 9.50 |
+------+-------+
7 rows in set (0.00 sec)
52
Select Queries With Joins
(4)
Entries only for Fred
SELECT name, hours FROM employees, jobs WHERE
employees.employeeID = jobs.employeeID AND
name = 'Fred';
+------+-------+
| name | hours |
+------+-------+
| Fred | 13.50 |
| Fred | 1.00 |
+------+-------+
2 rows in set (0.00 sec)
53
Select Queries With Joins
(5)
Total hours worked for each person
SELECT name, SUM(hours) FROM employees, jobs
WHERE employees.employeeID = jobs.employeeID
GROUP BY name;
+------+------------+
| name | SUM(hours) |
+------+------------+
| Bill | 20.50 |
| Fred | 14.50 |
| Joan | 8.25 |
+------+------------+
3 rows in set (0.00 sec)
54
Select Queries With Joins
(6)
Total hours worked, for Fred
SELECT name, SUM(hours) FROM employees, jobs
WHERE employees.employeeID = jobs.employeeID
AND name = 'Fred' GROUP BY name;
+------+------------+
| name | SUM(hours) |
+------+------------+
| Fred | 14.50 |
+------+------------+
1 row in set (0.00 sec)
55