1. MySQL Database Essentials
Cherrie Ann B. Domingo, CCNA
President, PHP User Group Philippines (PHPUGPH)
Acting Secretary/Treasurer, Philippine SQL Server Users Group (PHISSUG)
2. Objectives for the Session
Understand relational database concepts
Introduce MySQL RDBMS
Retrieve row and column data from tables with the SELECT statement
Use DML statements – INSERT, UPDATE, DELETE
Control database transactions using COMMIT and ROLLBACK statements
3. Historical Roots of Databases
First applications focused on clerical tasks: order/entry processing, payroll,
work scheduling and so on.
Small organizations keep track of their files using a manual file system
(folders, filing cabinets whose contents were logically related)
As organizations grew and reporting requirements became more complex,
keeping track of data in a manual file system became more difficult.
DP (data processing) Specialists were hired to computerize the manual file
systems
3
4. Disadvantages of File Systems
Data redundancy and inconsistency
Difficulty in accessing data
Data isolation
Concurrent access anomalies
Security problems
4
6. Database Systems Terms
Database - a collection of related data
Instance - a collection of information stored in a database at a given point
in time
Schema - over-all design of a database
6
7. Database Management System (DBMS)
consists of a collection of interrelated data and a collection of programs
used to access the data
introduced to address the data-dependency problem and at the same
time remove unnecessary burdens from the application programmer
Primary goal of a DBMS is to provide a convenient and efficient
environment for retrieving and storing information
7
8. Functions of DBMS
Data definition
• must be able to accept data definitions (internal, external, conceptual
schemas and all associated mappings) in source form and convert to
the appropriate object form (DDL)
Data Manipulation
• must be able to handle requests from the user to retrieve and possibly
update existing data in the database or to add new data to the
database (DML)
Data Security and Integrity
• must be able to monitor user requests and reject any attempts to
violate the security and integrity checks defined by the DBA
8
9. Functions of DBMS
Data Recovery and Concurrency
• must have the capability to recover from or minimize the effects of a
system crash
Data dictionary management
• must provide a system database called database dictionary. It
contains metadata (data about data) or the definition of other objects
in the system
9
10. Advantages of DBMS
Reduced data redundancy
• can be avoided by keeping a single copy of the data
Data Integrity
• since there is only one copy of a particular data, it is certain that the changes to
the data will be reflected in all future uses of that data
Data independence
• structure of the database system requires that data be independent of other
data in the database and the software used to access the database
Data Security
• different access levels to different users
10
11. Advantages of DBMS
Data Consistency
• format (name and size) of data being stored
Easier use of data
• a database system provides a user-friendly query language as part of the
package
Less storage
• since data redundancy is reduced if not eliminated, the database will occupy
less storage space
11
12. Disadvantages of DBMS
• Complex
• require special skills to implement and use
• Expensive
• since it is complex, it will require additional training to those who will make
use of the system. Also, the design and implementation is not cheap
• Vulnerable
• since all data are stored in one central location, it is vulnerable to partial or
complete destruction when a breakdown of hardware components occur
• Incompatibility with other database systems
• files created in one product are not easily transferred to another database
product
12
13. Disadvantages of DBMS
• Vulnerable
– since all data are stored in one central location, it is vulnerable to partial or
complete destruction when a breakdown of hardware components occur
• Incompatibility with other database systems
– files created in one product are not easily transferred to another database
product
13
14. a popular open source RDBMS
source code is available under terms of the GNU General Public License, as
well as under a variety of proprietary agreements
owned and sponsored by a single for-profit firm,
the Swedish company MySQL AB, now a subsidiary of Sun Microsystems,
which holds the copyright to most of the codebase
commonly used by free software projects which require a full-featured
database management system, such as WordPress, phpBB and other
software built on the LAMP software stack
also used in very high-scale World Wide Web products
including Google and Facebook
14
15. open source tool written in PHP intended to handle the administration
of MySQL over the World Wide Web
can perform various tasks such as:
• creating, modifying or deleting databases, tables, fields or rows
• executing SQL statements; or managing users and permissions.
15
16. SQL (Structured Query Language)
ANSI standard for accessing database systems
used to retrieve, insert, update and delete records from a database
Works with database programs like MS Access, DB2, Informix, SQL Server, Oracle,
Sybase, etc.
16
17. SQL (Structured Query Language)
ANSI standard for accessing database systems
used to retrieve, insert, update and delete records from a database
Works with database programs like MS Access, DB2, Informix, SQL Server,
Oracle, Sybase, etc.
17
18. SQL
Data Manipulation Language (DML)
• Select
• Update
• Delete
• Insert into
Data Definition Language (DDL)
• Create table
• Alter table
• Drop table
• Create index
• Drop index
18
20. Capabilities of SELECT Statement
Selection - choose rows in a table that should be returned by a query
Projection - choose columns in a table that should be returned by a query
Join - bring together data stored in different tables by creating a link
through a column that both tables share
20
22. SELECT Syntax
SELECT * | column_name(s)
FROM table_name;
• SELECT identifies the columns to be displayed
• FROM identifies the table containing those columns.
22
23. Column Alias
Renames a column heading
Is useful with calculations
Immediately follows the column name (There can also be the optional
AS keyword between the column name and alias.)
Requires double quotation marks if it contains spaces or special
characters or if it is case sensitive
SELECT column_name column_alias
FROM table_name;
SELECT column_name AS column_alias
FROM table_name;
*A multiple word heading can be specified by putting it in quotes
23
25. Operator Precedence
* / %
+-
Parentheses are used to force prioritized evaluation and to clarify statements
SELECT ProductName, UnitPrice*UnitsInStock+12
FROM Products
25
26. Defining a NULL value
A null is a value that is unavailable, unassigned, unknown value or
inapplicable
A null is not the same as a zero or blank space
26
27. Null Values in Arithmetic Expressions
Arithmetic expressions containing a null value evaluate to null.
27
28. Duplicate Rows
The default display of queries is all rows, including duplicate rows
To eliminate duplicate values, use DISTINCT keyword
SELECT DISTINCT department_id
FROM employees;
28
29. Displaying Table Structure
DESCRIBE | DESC - used to display table structure
Syntax:
DESC[RIBE] tablename
DESCRIBE employees
29
30. Limiting rows that are selected
Restrict the rows that are returned by using the WHERE clause
SELECT *|{[DISTINCT] column|expression [alias],...}
FROM table
[WHERE condition(s)];
The WHERE clause follows the FROM clause.
SELECT employee_id, last_name, job_id, department_id
FROM employees
WHERE department_id = 90 ;
30
31. Character Strings and Dates
Character strings and date values are enclosed in single quotation marks.
Character values are case sensitive, and date values are format sensitive.
The default date format is YYYY-MM-DD.
SELECT last_name, job_id, department_id
FROM employees
WHERE last_name = 'Whalen' ;
31
32. Comparison Condition
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to
BETWEEN Between two values
...AND... (inclusive)
IN(set) Match any of a list of values
LIKE Match a character pattern
IS NULL Is a null value
32
34. BETWEEN condition
Used to display rows based on a range of values
SELECT last_name, salary
FROM employees
WHERE salary BETWEEN 2500 AND 3500 ;
Lower limit Upper limit
34
35. IN condition
test for values in a list
SELECT employee_id, last_name, salary, manager_id
FROM employees
WHERE manager_id IN (100, 101, 201) ;
35
36. LIKE condition
Use the LIKE condition to perform wildcard searches of valid search string
values.
Search conditions can contain either literal characters or numbers:
• % denotes zero or many characters.
• _ denotes one character.
SELECT first_name
FROM employees
WHERE first_name LIKE 'S%' ;
36
37. LIKE condition
You can combine pattern-matching characters:
SELECT last_name
FROM employees
WHERE last_name LIKE '_o%' ;
You can use the ESCAPE identifier to search for the actual % and _ symbols.
37
38. NULL Conditions
Test for nulls with the IS NULL operator
SELECT last_name, manager_id
FROM employees
WHERE manager_id IS NULL ;
38
39. LOGICAL Conditions
Operator Meaning
AND Returns TRUE if both component
conditions are true
OR Returns TRUE if either component
condition is true
NOT Returns TRUE if the following
condition is false
39
40. Sorting using ORDER BY
Sort retrieved rows with the ORDER BY clause
ASC: ascending order, default
DESC: descending order
The ORDER BY clause comes last in the SELECT statement:
40
42. Types of Joins
Joins that are compliant with the SQL:1999 standard include the following:
• Cross joins
• Full (or two-sided) outer joins
• Arbitrary join conditions for outer joins
42
43. JOIN
Used to display data from multiple tables
EMPLOYEES DEPARTMENTS
… …
Foreign key Primary key
43
44. Qualifying Ambiguous Column Names
Use table prefixes to qualify column names that are in multiple tables.
Use table prefixes to improve performance.
Use column aliases to distinguish columns that have identical names
but reside in different tables.
44
45. Using Table Aliases
Use table aliases to simplify queries.
Use table aliases to improve performance.
45
46. Retrieving Records with the ON Clause
SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id);
46
47. Self-Joins Using the ON Clause
EMPLOYEES (WORKER) EMPLOYEES (MANAGER)
…
MANAGER_ID in the WORKER table is equal to
EMPLOYEE_ID in the MANAGER table.
47
48. Self-Joins Using the ON Clause
SELECT e.last_name emp, m.last_name mgr
FROM employees e JOIN employees m
ON (e.manager_id = m.employee_id);
…
48
49. Creating Three-Way Joins with the ON Clause
SELECT employee_id, city, department_name
FROM employees e
JOIN departments d
ON d.department_id = e.department_id
JOIN locations l
ON d.location_id = l.location_id;
49
50. Inner JOIN
Inner Join - the typical join operation which uses some comparison
operator like = or <>). These include equi-joins and natural joins.
50
51. Outer JOIN
can be a left or a right outer join
specified with one of the following sets of keywords when they are
specified in the FROM clause
DEPARTMENTS EMPLOYEES
…
There are no employees in
department 190.
51
52. INNER Versus OUTER Joins
In SQL:1999, the join of two tables returning only matched rows is
called an inner join.
A join between two tables that returns the results of the inner join as
well as the unmatched rows from the left (or right) tables is called a
left (or right) outer join.
A join between two tables that returns the results of an inner join as
well as the results of a left and right join is a full outer join.
52
53. LEFT OUTER JOIN
SELECT e.last_name, e.department_id, d.department_name
FROM employees e LEFT OUTER JOIN departments d
ON (e.department_id = d.department_id) ;
…
53
54. RIGHT OUTER JOIN
SELECT e.last_name, e.department_id, d.department_name
FROM employees e RIGHT OUTER JOIN departments d
ON (e.department_id = d.department_id) ;
…
54
55. FULL OUTER JOIN
SELECT e.last_name, d.department_id, d.department_name
FROM employees e FULL OUTER JOIN departments d
ON (e.department_id = d.department_id) ;
…
55
56. Cartesian Products
A Cartesian product is formed when:
• A join condition is omitted
• A join condition is invalid
• All rows in the first table are joined to all rows in the second table
To avoid a Cartesian product, always include a valid join condition.
56
58. Creating CROSS JOIN
The CROSS JOIN clause produces the cross-product of two tables.
This is also called a Cartesian product between the two tables.
SELECT last_name, department_name
FROM employees
CROSS JOIN departments ;
…
58
59. Adding a New Row to a Table
New
DEPARTMENTS row
Insert new row
into the
DEPARTMENTS table
59
60. INSERT statement
Add new rows to a table by using the INSERT statement:
INSERT INTO table [(column [, column...])]
VALUES (value [, value...]);
With this syntax, only one row is inserted at a time.
60
61. Inserting New Rows
– Insert a new row containing values for each column.
– List values in the default order of the columns in the table.
– Optionally, list the columns in the INSERT clause.
INSERT INTO departments(department_id,
department_name, manager_id, location_id)
VALUES (70, 'Public Relations', 100, 1700);
1 row created.
– Enclose character and date values in single quotation marks.
61
62. UPDATE Statement Syntax
Modify existing rows with the UPDATE statement:
UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];
Update more than one row at a time (if required).
62
63. Updating Rows in a Table
Specific row or rows are modified if you specify the WHERE clause:
UPDATE employees
SET department_id = 70
WHERE employee_id = 113;
1 row updated.
All rows in the table are modified if you omit the WHERE clause:
UPDATE copy_emp
SET department_id = 110;
22 rows updated.
63
64. Removing a Row from a Table
DEPARTMENTS
Delete a row from the DEPARTMENTS table:
64
65. DELETE Statement
You can remove existing rows from a table by using the DELETE
statement:
DELETE [FROM] table
[WHERE condition];
65
66. Deleting Rows from a Table
Specific rows are deleted if you specify the WHERE clause:
DELETE FROM departments
WHERE department_name = 'Finance';
1 row deleted.
All rows in the table are deleted if you omit the WHERE
clause:
DELETE FROM copy_emp;
22 rows deleted.
66
67. TRUNCATE Statement
Removes all rows from a table, leaving the table empty and the table
structure intact
Is a data definition language (DDL) statement rather than a DML
statement; cannot easily be undone
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE copy_emp;
67
68. DROP Statement
All data and structure in the table are deleted.
Any pending transactions are committed.
All indexes are dropped.
All constraints are dropped.
You cannot roll back the DROP TABLE statement.
DROP TABLE dept80;
Table dropped.
68
69. Database Transactions
A database transaction consists of one of the following:
DML statements that constitute one consistent change to the data
One DDL statement
One data control language (DCL) statement
69
70. Database Transactions
Begin when the first DML SQL statement is executed
End with one of the following events:
• A COMMIT or ROLLBACK statement is issued.
• A DDL or DCL statement executes (automatic commit).
• The system crashes.
70
71. Advantages of COMMIT and ROLLBACK Statements
With COMMIT and ROLLBACK statements, you can:
Ensure data consistency
Preview data changes before making changes permanent
Group logically related operations
71
73. State of the Data Before COMMIT or ROLLBACK
The previous state of the data can be recovered.
The current user can review the results of the DML operations by
using the SELECT statement.
Other users cannot view the results of the DML statements by the
current user.
The affected rows are locked; other users cannot change the data in
the affected rows.
73
74. State of the Data After COMMIT
Data changes are made permanent in the database.
The previous state of the data is permanently lost.
All users can view the results.
Locks on the affected rows are released; those rows are available for
other users to manipulate.
74
75. Committing Data
Make the changes:
DELETE FROM employees
WHERE employee_id = 99999;
1 row deleted.
INSERT INTO departments
VALUES (290, 'Corporate Tax', NULL, 1700);
1 row created.
Commit the changes:
COMMIT;
Commit complete.
75
76. State of the Data After ROLLBACK
Discard all pending changes by using the ROLLBACK statement:
Data changes are undone.
Previous state of the data is restored.
Locks on the affected rows are released.
76
77. State of the Data After ROLLBACK
DELETE FROM test;
25,000 rows deleted.
ROLLBACK;
Rollback complete.
DELETE FROM test WHERE id = 100;
1 row deleted.
SELECT * FROM test WHERE id = 100;
No rows selected.
COMMIT;
Commit complete.
77
78. Summary
This session covers the following topics:
RDBMS concepts
Selecting all data from different tables
Describing the structure of tables
Performing arithmetic calculations and specifying column names
Use of the statements below:
Function Description
INSERT Adds a new row to the table
UPDATE Modifies existing rows in the table
DELETE Removes existing rows from the table
COMMIT Makes all pending changes permanent
ROLLBACK Discards all pending data changes
79. Be a PHPUGPH’er! ^__^
Register now at http://www.phpugph.com
It’s totally FREE!
80. Contact Me ^__^
Cherrie Ann B. Domingo, CCNA
chean@phpugph.com
chean@cherrieanndomingo.com blue_cherie29
http://www.cherrieanndomingo.com cherrie.ann.domingo
+63917.865.2412 (Globe) cherrie.ann.domingo
cherrie.ann.domingo
(632) 975.6976
http://www.plurk.com/chean
http://www.twitter.com/betelguese
http://www.facebook.com/cherrieann