Phpugph Mysql v3

download Phpugph Mysql v3

of 79

Transcript of Phpugph Mysql v3

  • 8/6/2019 Phpugph Mysql v3

    1/79

    MySQL Database Essentials

    Cherrie Ann B. Domingo, CCNAPresident, PHP User Group Philippines (PHPUGPH)

  • 8/6/2019 Phpugph Mysql v3

    2/79

    O bjectives for the Session

    Understand relational database conceptsIntroduce MySQL RDBMSRetrieve row and column data from tables with the SELECT statementUse DML statements INSERT, UPDATE, DELETEControl database transactions using C O MMIT and R O LLBACK statements

  • 8/6/2019 Phpugph Mysql v3

    3/79

    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 filesystems

    3

  • 8/6/2019 Phpugph Mysql v3

    4/79

    Disadvantages of File Systems

    Data redundancy and inconsistency

    Difficulty in accessing data

    Data isolation

    Concurrent access anomalies

    Security problems

    4

  • 8/6/2019 Phpugph Mysql v3

    5/79

    Database Management Systems vs. File Systems

    5

  • 8/6/2019 Phpugph Mysql v3

    6/79

    Database Systems Terms

    Database - a collection of related data

    Insta nc e - a collection of information stored in a database at a given pointin time

    Schema - over -all design of a database

    6

  • 8/6/2019 Phpugph Mysql v3

    7/79

    Database Management System (DBMS)

    consists of a collection of interrelated data and a collection of programsused to access the data

    introduced to address the data -dependency problem and at the sametime remove unnecessary burdens from the application programmer

    Primary goal of a DBMS is to provide a convenient and efficientenvironment for retrieving and storing information

    7

  • 8/6/2019 Phpugph Mysql v3

    8/79

    Functions of DBMS

    Data definitionmust be able to accept data definitions (internal, external, conceptualschemas and all associated mappings) in source form and convert tothe appropriate object form (DDL)

    Data Manipulationmust be able to handle requests from the user to retrieve and possiblyupdate 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 toviolate the security and integrity checks defined by the DBA

    8

  • 8/6/2019 Phpugph Mysql v3

    9/79

    Functions of DBMS

    Data Recovery and Concurrency must have the capability to recover from or minimize the effects of asystem crash

    Data dictionary management must provide a system database called database dictionary. It containsmetadata (data about data) or the definition of other objects in thesystem

    9

  • 8/6/2019 Phpugph Mysql v3

    10/79

  • 8/6/2019 Phpugph Mysql v3

    11/79

    Advantages of DBMS

    Data Consistency format (name and size) of data being stored

    E asier use of data

    a database system provides a user -friendly query language as part of thepackage

    Less storagesince data redundancy is reduced if not eliminated, the database will occupyless storage space

    11

  • 8/6/2019 Phpugph Mysql v3

    12/79

    Disadvantages of DBMS

    Complex require special skills to implement and use

    E xpensive

    since it is complex, it will require additional training to those who will makeuse of the system. Also, the design and implementation is not cheap

    V ulnerablesince all data are stored in one central location, it is vulnerable to partial orcomplete destruction when a breakdown of hardware components occur

    Incompatibility with other database systems

    files created in one product are not easily transferred to another databaseproduct

    12

  • 8/6/2019 Phpugph Mysql v3

    13/79

    a popular open source RDBMSsource code is available under terms of the GNU General Public License, aswell as under a variety of proprietary agreementsowned 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 codebasecommonly used by free software projects which require a full -featureddatabase management system, such as WordPress, phpBB and othersoftware built on the LAMP software stack

    also used in very high -scale World Wide Web productsincluding Google and Facebook

    13

  • 8/6/2019 Phpugph Mysql v3

    14/79

    open source tool written in PHP intended to handle the administrationof MySQL over the World Wide Webcan perform various tasks such as:

    creating, modifying or deleting databases, tables, fields or rows

    executing SQL statements; or managing users and permissions.

    14

  • 8/6/2019 Phpugph Mysql v3

    15/79

    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, O racle,Sybase, etc.

    SQL (Structured Query Language)

    15

  • 8/6/2019 Phpugph Mysql v3

    16/79

    SQLData Manipulation Language (DM L)

    SelectUpdateDelete

    Insert into

    Data Definition Language (DD L)

    Create tableAlter tableDrop tableCreate indexDrop index

    16

  • 8/6/2019 Phpugph Mysql v3

    17/79

    SQLData Control Language (DC L)

    Rollback

    Commit

    17

  • 8/6/2019 Phpugph Mysql v3

    18/79

    Capabilities of SELECT Statement

    Selection - choose rows in a table that should be returned by a query

    P rojection - choose columns in a table that should be returned by a query

    Join - bring together data stored in different tables by creating a linkthrough a column that both tables share

    18

  • 8/6/2019 Phpugph Mysql v3

    19/79

    Capabilities of SELECT StatementS electionProjection

    Table 1 Table 2

    Table 1Table 1

    Join

    19

  • 8/6/2019 Phpugph Mysql v3

    20/79

    SELECT Syntax

    SELECT * | column_name(s)FROM table_name;

    SELECT identifies the columns to be displayed

    FROMidentifies the table containing those columns.

    20

  • 8/6/2019 Phpugph Mysql v3

    21/79

    Column Alias

    Renames a column headingIs useful with calculationsImmediately follows the column name (There can also be the optionalA S keyword between the column name and alias.)

    Requires double quotation marks if it contains spaces or specialcharacters or if it is case sensitive

    SELECT column_name column_aliasFROM table_name;

    SELECT column_name A S column_aliasFROM table_name;

    *A multiple word headi ng c a n be spe c ified by putti ng it i n q uotes

    21

  • 8/6/2019 Phpugph Mysql v3

    22/79

    Arithmetic O perators

    + Addition- Subtraction/ Division* Multiplication% Modulo

    SELECT ProductID, ProductName, UnitPrice * 10

    FROM Products

    22

  • 8/6/2019 Phpugph Mysql v3

    23/79

    O perator Precedence

    * / %+ -

    Parentheses are used to force prioritized evaluation and to clarify statements

    SELECT ProductName, UnitPrice*UnitsInStock+12

    FROM Products

    23

  • 8/6/2019 Phpugph Mysql v3

    24/79

    Defining a NULL value

    A null is a value that is unavailable, unassigned, unknown value orinapplicable

    A null is not the same as a zero or blank space

    24

  • 8/6/2019 Phpugph Mysql v3

    25/79

    Null Values in Arithmetic Expressions

    Arithmetic expressions containing a null value evaluate to null.

    25

  • 8/6/2019 Phpugph Mysql v3

    26/79

    Duplicate Rows

    The default display of queries is all rows, including duplicate rows

    To eliminate duplicate values, use DISTINCT keyword

    SELECT DISTINCT department_idFROM employees;

    26

  • 8/6/2019 Phpugph Mysql v3

    27/79

    Displaying Table Structure

    DESCRIBE | DESC- used to display table structure

    Syntax:

    DESC[RIBE] tablename

    DESCRIBE employees

    27

  • 8/6/2019 Phpugph Mysql v3

    28/79

    Limiting rows that are selected

    Restrict the rows that are returned by using the WH ERE clause

    SELECT *|{[DISTINCT] column|expression [ alias ],...}FROM table[ WH ERE condition(s) ];

    The WH ERE clause follows the FROMclause.

    SELECT employee_id, last_name, job_id, department_id FROM employees

    WHERE department_id = 90 ;

    28

  • 8/6/2019 Phpugph Mysql v3

    29/79

    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' ;

    29

  • 8/6/2019 Phpugph Mysql v3

    30/79

    Comparison ConditionOperator Meaning

    = Equal to

    > Greater than

    >= Greater than or equal to

    < Less than

  • 8/6/2019 Phpugph Mysql v3

    31/79

    Using Comparison Conditions

    SELECT last_name, salaryFROM employees

    WHERE salary

  • 8/6/2019 Phpugph Mysql v3

    32/79

    BETWEEN condition

    Used to display rows based on a range of values

    SELECT last_name, salaryFROM employees

    WHERE salary B ETWEEN 2500 AND 3500 ;

    Lower limit Upper limit

    32

  • 8/6/2019 Phpugph Mysql v3

    33/79

    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) ;

    33

  • 8/6/2019 Phpugph Mysql v3

    34/79

    LIKE conditionUse the LIKE condition to perform wildcard searches of valid search stringvalues.

    Search conditions can contain either literal characters or numbers:% denotes zero or many characters.

    _ denotes one character.

    SELECT first_nameFROM employees

    WHERE first_name LIKE 'S%' ;

    34

  • 8/6/2019 Phpugph Mysql v3

    35/79

    LIKE condition

    You can combine pattern -matching characters:

    You can use the ESC A PE identifier to search for the actual % and _ symbols.

    SELECT last_nameFROM employees

    WHERE last_name LIKE '_o%' ;

    35

  • 8/6/2019 Phpugph Mysql v3

    36/79

    NULL Conditions

    Test for nulls with the IS NULL operator

    SELECT last_name, manager_id FROM employees

    WHERE manager_id IS NULL ;

    36

  • 8/6/2019 Phpugph Mysql v3

    37/79

    LO GICAL Conditions

    Operator Meaning

    AND R eturns TRUE if both componentconditions are true

    OR R eturnsTRUE

    if ei th er componentcondition is true

    NOT R eturns TRUE if the followingcondition is false

    37

  • 8/6/2019 Phpugph Mysql v3

    38/79

    Sorting using O RDER BY

    Sort retrieved rows with the ORDER BY clause

    A SC: ascending order, default

    DESC: descending order

    The ORDER BY clause comes last in the SELECT statement:

    38

  • 8/6/2019 Phpugph Mysql v3

    39/79

    O btaining Data from Multiple Tables

    EMPLOYEES DEPARTMENTS

    39

  • 8/6/2019 Phpugph Mysql v3

    40/79

    Types of Joins

    Joins that are compliant with the SQL:1999 standard include the following:

    Cross joinsFull (or two -sided) outer joins

    Arbitrary join conditions for outer joins

    40

  • 8/6/2019 Phpugph Mysql v3

    41/79

    JO INUsed to display data from multiple tables

    EMPLOYEES DEPARTMENTS

    Foreign key Primary key

    41

  • 8/6/2019 Phpugph Mysql v3

    42/79

    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 namesbut reside in different tables.

    42

  • 8/6/2019 Phpugph Mysql v3

    43/79

    Using Table Aliases

    Use table aliases to simplify queries.Use table aliases to improve performance.

    43

  • 8/6/2019 Phpugph Mysql v3

    44/79

    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);

    44

  • 8/6/2019 Phpugph Mysql v3

    45/79

    Self -Joins Using the ONClause

    MANAGER_ID in the WORKER table is equal toEMPLOYEE_ID in the MANAGER table.

    EMPLOYEES (WORKER) EMPLOYEES (MANAGER)

    45

  • 8/6/2019 Phpugph Mysql v3

    46/79

    Self -Joins Using the ONClause

    SELECT e.last_name emp, m.last_name mgrFROM employees e JOIN employees m ON (e.manager_id = m.employee_id);

    46

  • 8/6/2019 Phpugph Mysql v3

    47/79

  • 8/6/2019 Phpugph Mysql v3

    48/79

    Inner J O IN

    Inner Join - the typical join operation which uses some comparisonoperator like = or ). These include equi - joins and natural joins.

    48

  • 8/6/2019 Phpugph Mysql v3

    49/79

    O uter J O INcan be a left or a right outer joinspecified with one of the following sets of keywords when they arespecified in the FR O M clause

    DEPARTMENTS EMPLOYEES

    There are no employees indepartment 190.

    49

  • 8/6/2019 Phpugph Mysql v3

    50/79

    INNER Versus O UTER Joins

    In SQL:1999, the join of two tables returning only matched rows iscalled 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 aleft (or right) outer join.

    A join between two tables that returns the results of an inner join aswell as the results of a left and right join is a full outer join.

    50

  • 8/6/2019 Phpugph Mysql v3

    51/79

    LEFTO UTER JO IN

    SELECT e.last_name, e.department_id, d.department_nameFROM employees e LEFT OUTER JOIN departments d ON (e.department_id = d.department_id) ;

    51

  • 8/6/2019 Phpugph Mysql v3

    52/79

  • 8/6/2019 Phpugph Mysql v3

    53/79

    FULLO UTER JO IN

    SELECT e.last_name, d.department_id, d.department_nameFROM employees e FULL OUTER JOIN departments d ON (e.department_id = d.department_id) ;

    53

  • 8/6/2019 Phpugph Mysql v3

    54/79

    Cartesian Products

    A Cartesian product is formed when:

    A join condition is omittedA 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.

    54

  • 8/6/2019 Phpugph Mysql v3

    55/79

    Generating a Cartesian Product

    Cartesian product:20 x 8 = 160 rows

    EMPLOYEES (20 rows) DEPARTMENTS (8 rows)

    55

  • 8/6/2019 Phpugph Mysql v3

    56/79

    Creating CR O SS JO IN

    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_nameFROM employeesCROSS JOIN departments ;

    56

  • 8/6/2019 Phpugph Mysql v3

    57/79

    Adding a New Row to a TableDEPARTMENTS Newrow

    Insert new rowinto theDEPARTMENTS table

    57

  • 8/6/2019 Phpugph Mysql v3

    58/79

    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... ]);

    58

  • 8/6/2019 Phpugph Mysql v3

    59/79

    Inserting New Rows Insert a new row containing values for each column. List values in the default order of the columns in the table. O ptionally, list the columns in the INSERT clause.

    Enclose character and date values in single quotation marks.

    INSERT INTO departments(department_id,department_name, manager_id, location_id)

    VALUES (70, 'Public Relations', 100, 1700);1 row created.

    59

  • 8/6/2019 Phpugph Mysql v3

    60/79

    UPDA TE Statement Syntax

    Modify existing rows with the UPDA TE statement:

    Update more than one row at a time (if required).

    UPDATE tableSET column = value [, column = value, ... ][WHERE condition ];

    60

  • 8/6/2019 Phpugph Mysql v3

    61/79

    Updating Rows in a Table

    Specific row or rows are modified if you specify the WH ERE clause:

    All rows in the table are modified if you omit the WH ERE clause:

    UPDATE employeesSET department_id = 70

    WHERE employee_id = 113;1 row updated.

    UPDATE copy_empSET department_id = 110;22 rows updated.

    61

  • 8/6/2019 Phpugph Mysql v3

    62/79

    Removing a Row from a Table

    Delete a row from the DEPARTMENTStable:

    DEPARTMENTS

    62

  • 8/6/2019 Phpugph Mysql v3

    63/79

    DELETE Statement

    You can remove existing rows from a table by using the DELETEstatement:

    DELETE [FROM] table

    [WHERE condition ];

    63

  • 8/6/2019 Phpugph Mysql v3

    64/79

    Deleting Rows from a Table

    Specific rows are deleted if you specify the WHERE clause:

    All rows in the table are deleted if you omit the WHEREclause:

    DELETE FROM departments WHERE department_name = 'Finance';1 row deleted.

    DELETE FROM copy_emp;22 rows deleted.

    64

  • 8/6/2019 Phpugph Mysql v3

    65/79

    TRUNCATE Statement

    Removes all rows from a table, leaving the table empty and the tablestructure intactIs a data definition language (DDL) statement rather than a DMLstatement; cannot easily be undone

    Syntax:

    Example:

    TRUNCATE TA B LE table_name ;

    TRUNCATE TA B LE copy_emp;

    65

  • 8/6/2019 Phpugph Mysql v3

    66/79

    DRO P 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 T A BLE statement.

    DROP TA B LE dept80;Table dropped.

    66

  • 8/6/2019 Phpugph Mysql v3

    67/79

    Database Transactions

    A database transaction consists of one of the following:DML statements that constitute one consistent change to the dataO ne DDL statementO ne data control language (DCL) statement

    67

  • 8/6/2019 Phpugph Mysql v3

    68/79

    Database Transactions

    Begin when the first DML SQL statement is executedEnd with one of the following events:

    A COMMIT or ROLLBA CK statement is issued.

    A DDL or DCL statement executes (automatic commit).The system crashes.

    68

  • 8/6/2019 Phpugph Mysql v3

    69/79

    Advantages of COMMITand ROLLBA CK Statements

    With COMMITand ROLLBA CK statements, you can:

    Ensure data consistencyPreview data changes before making changes permanent

    Group logically related operations

    69

  • 8/6/2019 Phpugph Mysql v3

    70/79

    Controlling Transactions

    DELETE

    INSERT

    UPDATE

    INSERT

    COMMIT T ime

    T ransaction

    ROLLB ACK

    70

  • 8/6/2019 Phpugph Mysql v3

    71/79

    State of the Data Before COMMITor ROLLBA CK

    The previous state of the data can be recovered.The current user can review the results of the DML operations by usingthe SELECT statement.O ther users cannot view the results of the DML statements by the

    current user.The affected rows are locked ; other users cannot change the data inthe affected rows.

    71

  • 8/6/2019 Phpugph Mysql v3

    72/79

    State of the Data After COMMITData 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.

    72

  • 8/6/2019 Phpugph Mysql v3

    73/79

    Committing Data

    Make the changes:

    Commit 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;Commit complete.

    73

  • 8/6/2019 Phpugph Mysql v3

    74/79

    State of the Data After ROLLBA CKDiscard all pending changes by using the ROLLBA CKstatement:

    Data changes are undone.Previous state of the data is restored.

    Locks on the affected rows are released.

    74

  • 8/6/2019 Phpugph Mysql v3

    75/79

    State of the Data After ROLLBA CK

    DELETE FROM test;25,000 rows deleted.

    ROLLB ACK;Rollback complete.

    DELETE FROM test WHERE id = 100;1 row deleted.

    SELECT * FROM test WHERE id = 100; No rows selected.

    COMMIT;Commit complete.

    75

  • 8/6/2019 Phpugph Mysql v3

    76/79

    SummaryThis session covers the following topics:

    RDBMS concepts

    Selecting all data from different tablesDescribing the structure of tablesPerforming arithmetic calculations and specifying column names

    Use of the statements below:

    F unction Description

    INSERT Adds a new row to the table

    UPDATE Modifies existing rows in the table

    DELETE R emoves existing rows from the tableCOMMIT Makes all pending changes permanent

    ROLLB ACK Discards all pending data changes

  • 8/6/2019 Phpugph Mysql v3

    77/79

    Presentation Slides ^___^

    Y ou may get the copy fromhttp://www.slideshare.net/cherrieanndomingo/php -roadshow -mysql -database -essentials

  • 8/6/2019 Phpugph Mysql v3

    78/79

  • 8/6/2019 Phpugph Mysql v3

    79/79

    Contact Me ^__^

    Cherrie Ann B. Domingo, CCNA

    blue_cherie29

    cherrie.ann.domingo

    cherrie.ann.domingo

    cherrie.ann.domingo

    http://www.plurk.com/chean

    http://www.twitter.com/betelguese

    [email protected]

    [email protected]

    http://www.cherrieanndomingo.com

    +63917.865.2412/+63915.441.0707

    (632) 975.6976

    http://www.facebook.com/cherrieann