php roadshow - mysql database essentials
Post on 26-Jun-2015
706 Views
Preview:
TRANSCRIPT
MySQL Database Essentials
Cherrie Ann B. Domingo, CCNAPresident, PHP User Group Philippines (PHPUGPH)
Acting Secretary/Treasurer, Philippine SQL Server Users Group (PHISSUG)
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
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
Disadvantages of File Systems
� Data redundancy and inconsistency
� Difficulty in accessing data
� Data isolation
� Concurrent access anomalies
� Security problems
4
Database Management Systems vs. File Systems
5
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� Schema - over-all design of a database
6
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
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� 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
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 • must provide a system database called database dictionary. It
contains metadata (data about data) or the definition of other objects
in the system
9
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 datathe 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
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
packagepackage
� Less storage
• since data redundancy is reduced if not eliminated, the database will occupy
less storage space
11
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 cheapuse 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
• 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
Disadvantages of DBMS
– files created in one product are not easily transferred to another database
product
13
� 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 codebasewhich 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
� 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
� 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.
SQL (Structured Query Language)
Sybase, etc.
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.Oracle, Sybase, etc.
17
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
SQL� Data Control Language (DCL)
• Rollback
• Commit
19
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 sharethrough a column that both tables share
20
Capabilities of SELECT Statement
SelectionProjection
Table 1 Table 2
Table 1Table 1
Join
21
SELECT Syntax
SELECT * | column_name(s)
FROM table_name;
• SELECT identifies the columns to be displayed
• FROM identifies the table containing those columns.
22
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 sensitivecharacters 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
Arithmetic Operators
+ Addition
- Subtraction
/ Division
* Multiplication
% Modulo
SELECT ProductID, ProductName, UnitPrice * 10
FROM Products
24
Operator Precedence
* / %
+ -
Parentheses are used to force prioritized evaluation and to clarify statements
SELECT ProductName, UnitPrice*UnitsInStock+12
FROM Products
25
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
Null Values in Arithmetic Expressions
� Arithmetic expressions containing a null value evaluate to null.
27
Duplicate Rows
� The default display of queries is all rows, including duplicate rows
� To eliminate duplicate values, use DISTINCT keyword
SELECT DISTINCT department_idSELECT DISTINCT department_id
FROM employees;
28
Displaying Table Structure
� DESCRIBE | DESC - used to display table structure
Syntax:
DESC[RIBE] tablenameDESC[RIBE] tablename
DESCRIBE employees
29
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
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_idSELECT last_name, job_id, department_id
FROM employees
WHERE last_name = 'Whalen' ;
31
Comparison ConditionOperator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to<= Less than or equal to
<> Not equal to
BETWEEN
...AND...Between two values
(inclusive)
IN(set) Match any of a list of values
LIKE Match a character pattern
IS NULL Is a null value
32
Using Comparison Conditions
SELECT last_name, salary
FROM employees
WHERE salary <= 3000 ;
33
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
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
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.• _ denotes one character.
SELECT first_name
FROM employees
WHERE first_name LIKE 'S%' ;
36
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
NULL Conditions
Test for nulls with the IS NULL operator
SELECT last_name, manager_id
FROM employees
WHERE manager_id IS NULL ;
38
LOGICAL Conditions
Operator Meaning
AND Returns TRUE if both component
conditions are true
OR Returns TRUE if either component
condition is truecondition is true
NOT Returns TRUE if the following
condition is false
39
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
Obtaining Data from Multiple Tables
EMPLOYEES DEPARTMENTS
…
…
41
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
JOIN� Used to display data from multiple tables
EMPLOYEES DEPARTMENTS
… …
Foreign key Primary key
43
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.but reside in different tables.
44
Using Table Aliases
� Use table aliases to simplify queries.
� Use table aliases to improve performance.
45
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
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
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
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;ON d.location_id = l.location_id;
49
Inner JOIN
� Inner Join - the typical join operation which uses some comparison
operator like = or <>). These include equi-joins and natural joins.
50
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
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.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
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
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
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
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
Generating a Cartesian Product
EMPLOYEES (20 rows) DEPARTMENTS (8 rows)
…
Cartesian product:
20 x 8 = 160 rows
…
57
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 employeesFROM employees
CROSS JOIN departments ;
…
58
Adding a New Row to a Table
DEPARTMENTS
New row
Insert new rowinto the
DEPARTMENTS table
59
INSERT statement
� Add new rows to a table by using the INSERT statement:
� With this syntax, only one row is inserted at a time.
INSERT INTO table [(column [, column...])]
VALUES (value [, value...]);
60
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);
– Enclose character and date values in single quotation marks.
VALUES (70, 'Public Relations', 100, 1700);
1 row created.
61
UPDATE Statement Syntax
� Modify existing rows with the UPDATE statement:
� Update more than one row at a time (if required).
UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];
62
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
Removing a Row from a Table
DEPARTMENTS
Delete a row from the DEPARTMENTS table:
64
DELETE Statement
� You can remove existing rows from a table by using the DELETE
statement:
DELETE [FROM] table
[WHERE condition];
65
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
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:
� Example:
TRUNCATE TABLE table_name;
TRUNCATE TABLE copy_emp;
67
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
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
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.• The system crashes.
70
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
Controlling Transactions
DELETE
INSERT
COMMITTime
Transaction
INSERT
UPDATE
INSERT
ROLLBACK
72
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 are locked; other users cannot change the data in
the affected rows.
73
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
Committing Data
� Make the changes:
DELETE FROM employees
WHERE employee_id = 99999;
1 row deleted.
INSERT INTO departments
� Commit the changes:
INSERT INTO departments
VALUES (290, 'Corporate Tax', NULL, 1700);
1 row created.
COMMIT;
Commit complete.
75
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
State of the Data After ROLLBACK
DELETE FROM test;
25,000 rows deleted.
ROLLBACK;
Rollback complete.
DELETE FROM test WHERE id = 100;DELETE FROM test WHERE id = 100;
1 row deleted.
SELECT * FROM test WHERE id = 100;
No rows selected.
COMMIT;
Commit complete.
77
SummaryThis 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:� 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
Be a PHPUGPH’er! ^__^
Register now at http://www.phpugph.com
It’s totally FREE!
Contact Me ^__^
Cherrie Ann B. Domingo, CCNA
blue_cherie29chean@phpugph.com
chean@cherrieanndomingo.com
cherrie.ann.domingo
cherrie.ann.domingo
cherrie.ann.domingo
http://www.plurk.com/chean
http://www.twitter.com/betelguese
http://www.cherrieanndomingo.com
+63917.865.2412 (Globe)
(632) 975.6976
http://www.facebook.com/cherrieann
top related