100890_633608325477500000

Upload: praveen-manohar

Post on 06-Apr-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 100890_633608325477500000

    1/107

    SQL- Study note

    By Maggie Zhou

    Sep, 2008

  • 8/3/2019 100890_633608325477500000

    2/107

    2

    Preface

    This is one of my study note for SQL Main part of this note is from

    Head First SQL: Your Brain on SQL -- A Learner's Guide

    By Lynn Beighley

    August 2007

    Pages: 607

    Series: Head First

    ISBN 10: 0-596-52684-9 | ISBN 13: 9780596526849

    This is a great book for beginner, and you will have a lot

    of fun when you go through this book (trust me, this is

    not a commercial)

    But it isnt only from this book:

    I organized this note in my understanding way.

    I added several concepts which I think are important

  • 8/3/2019 100890_633608325477500000

    3/107

    3

    Basic concepts

    SQL: /sikwl/, Structured QueryLanguage,

    RDBMS: Relational DataBase

    Management Systems SQL Appeared in 1974

    MySQL: SQL/PSM

    SQL/Persistent Stored Module (as in ISO

    SQL:2003)

    Oracle: PL/SQL

    Procedural Language/SQL (based on Ada)

  • 8/3/2019 100890_633608325477500000

    4/107

    4

    MySQL installation

    MySQL community ServerOfficial free version of the MySQL RDBMS

    Steps to install MySQL on windowsDownload

    http://dev.mysql.com/downloads/ Choose windows from list

    Choose Windows ZIP/Setup.exe option

    Pick a mirror

    Run Setup Wizard

    Choose typical Install to default location: c:\program files\mysql\mysql

    server 5.0

    Finally install it

  • 8/3/2019 100890_633608325477500000

    5/107

    5

    Create (1)

    Case insensitive DatabaseCREATE DATABASE name

    Table

    CREATE TABLE name(

    data_name1 CHAR/CHARACTER(x~256),

    data_name2 DEC/DECIMAL(x,x),

    data_name3 INT/INTEGER,

    data_name4 BLOB,data_name5 DATE,

    data_name6 DATETIME/TIMESTAMP,

    data_name7 VARCHAR(x~256)

    );

  • 8/3/2019 100890_633608325477500000

    6/107

    6

    Create (2)

    Columns / AttributesMandatory value

    (

    data_name CHAR(10) NOT NULL,

    )

    set default value

    (

    data_name DEC(3.2) NOT NULL DEFAULT 1.00,

    )

    Use keyword as columns name

    BAD, but can do INT is ok

  • 8/3/2019 100890_633608325477500000

    7/107

    7

    Data type (1)

    BOOLEANRDBMS store a 1 for true, 0 for false

    You can insert: 1/true, 0/false, null

    INTUnsigned integer: values in the range 0 to

    4294967295

    Signed integer: INT(SIGNED)

    SMALLINT

    BIGINT

    MySQL also has: TINYINT, MEDIUMINT

  • 8/3/2019 100890_633608325477500000

    8/107

    8

    Data type (2)

    DATE and TIMEDATE: yyyy-mm-dd

    DATATIME: yyyy-mm-dd hh:mm:ss

    TIMESTAMP: yyyymmddhhmmss

    TIME: hh:mm:ss

    DATE_FORMAT tells function the date_formatyou wantSELECT

    DATE_FORMAT (date, %M %Y)

    FROM table_name;

    Result will be: Auguest 2007

  • 8/3/2019 100890_633608325477500000

    9/107

    9

    CAST

    CAST (column, TYPE); Types

    CHAR()

    DATE, DATETIME, TIME

    DECIMALSIGNED [INTEGER]

    UNSIGNED [INTEGER]

    CAN

    Be included inside the INSERT, SELECT CANT

    DEC to INT

    TIME, DATE, DATETIEM, CHAR to DEC, or INT

  • 8/3/2019 100890_633608325477500000

    10/107

    10

  • 8/3/2019 100890_633608325477500000

    11/107

    11

    Maintain

    Change databaseUSE database_name;

    Check structure of table

    DESC table_name;

    Check table content

    SELECT * FROM table_name

    Change

    Please see from Slides 23

    Delete

    DROP TABLE table_name;

    Only can use on empty table

  • 8/3/2019 100890_633608325477500000

    12/107

    12

    Add data

    Insert dataINSERT INTO table_name

    (column_name1, column_name2,)

    VALUES (value1, value2,); For the AUTO_INCREMENT column, can use , instead input

    value Synax for column

    Using column name can control the insert order, the valueorder should match

    Not using column name, value need including all the value,

    in exact order in table Synax for value:

    CHAR, VARCHAR, DATE, BLOB need single quote

    INT, DEC do not use quote

  • 8/3/2019 100890_633608325477500000

    13/107

    13

    Select (1)

    Show all data & all columnSELECT * FROM table_name;

    Show chosen data & all columnSELECT *

    FROM table_name

    WHERE column_name = value; Can use =, >, =,

  • 8/3/2019 100890_633608325477500000

    14/107

    14

    Select (2)

    Show multiple choose conditionsSELECT *

    FROM table_name

    WHERE condition1

    AND, OR

    AND: match all the conditions

    OR: match only one condition is enough

    Condition2;

    Comparison operators=, >, =,

  • 8/3/2019 100890_633608325477500000

    15/107

    15

    Select (3)

    Wide cardSELECT *FROM table_name

    WHERE column_name LIKE %XX; % any number of unknown characters

    _ just only one unknown character

    Given RangeSELECT *

    FROM table_name

    WHERE column_name BETWEEN xx AND xx;

    Given Group

    SELECT *FROM table_name

    WHERE column_name IN (value, value,); IN the data match conditions

    NOT IN the data do not match conditions

  • 8/3/2019 100890_633608325477500000

    16/107

    16

    Select (4)

    NOT conditionsCombine AND, OR, IS with NOT

    Right after AND, OR AND NOT

    IS NOT NULL means WHERE NOT name IS NULL

    Could do, but you shouldnt do double

    negative

    Bad: WHERE NOTcolumn value;

  • 8/3/2019 100890_633608325477500000

    17/107

    17

    Database design

    Steps to designPick one thing your table want to describe

    Make a list of information using the table

    Break down information into pieces and organizing table

    Atomic dataColumn with atomic data cant have several value of the

    same type of data

    Table with atomic data cant have multiple columns with

    same type of data

    Normal tableNormal table wont have duplicate data

    With less data to search through

  • 8/3/2019 100890_633608325477500000

    18/107

    18

    1NF FIRST NORMAL FORM

    Each row of data must only contain atomicvalues

    Each row of data must have a unique

    identifier

  • 8/3/2019 100890_633608325477500000

    19/107

    19

    Primary key Create

    CREATE TABLE table_name

    (key_name data_type NOT NULL,PRIMARY KEY (key_name)

    );

    OR

    CREATE TABLE table_name

    (key_name data_type NOT NULL PRIMARY KEY,

    );

    Key:Can not be NULL

    Must be compact

    Can not be changed

    Auto incrementally(key_name INT NOT NULL AUTO_INCREMENT PRIMARY KEY,

    );

    Data has same key value wont be accepted

    The key can be overwritten you still can make own value

    AUTO-INCREMENT

    Only one per table, must be INT, cannot beNOT NULL

  • 8/3/2019 100890_633608325477500000

    20/107

  • 8/3/2019 100890_633608325477500000

    21/107

    21

    Delete row

    Delete row/rows base on conditionDELETE FROM table_name

    WHERE condition;

    Without condition, you will delete alldata

  • 8/3/2019 100890_633608325477500000

    22/107

  • 8/3/2019 100890_633608325477500000

    23/107

    23

    ALTER Table (1)

    All about the columns table structure Change

    Change name, data type of existing column

    ModifyData type or position of existing column

    Add

    Add new column Drop

    Delete column from table

  • 8/3/2019 100890_633608325477500000

    24/107

    24

    ALTER Table (2) ADD COLUMN

    Alter tableALTER TABLE table_name

    Add column

    ADD COLUMN column_name type NOT NULL

    AUTO_INCREMENT FIRST, (dont forget , )ADD PRIMARY KEY (column_name);

    OR

    ADD COLUMN column_name type

    AFTER another_column_name; Define the position;

    Can use: FIRST, LAST, AFTER, BEFORE

    Even can use: SECOND, FIFTH

  • 8/3/2019 100890_633608325477500000

    25/107

    25

    ALTER Table (3) CHANGE/RENAME

    Rename tableALTER TABLE table_name

    RENAME TO new_table_name

    Change column name and typeALTER TABLE table_name

    CHANGE COLUMN column_name

    new_column_name new_type ,

    ;

  • 8/3/2019 100890_633608325477500000

    26/107

    26

    ALTER Table (3) MODIFY

    Modify columnALTER TABLE table_name

    MODIFY COLUMN column_name

    new_type/size;

    Cannot change order of columns

    It wont matter, due to you can use SELECT

    to control order

  • 8/3/2019 100890_633608325477500000

    27/107

    27

    ALTER Table (3) DROP

    Delete columnALTER TABLE table_nameDROP COLUMN column_name;

    Remove AUTO_INCREMENTALTER TABLE table_name

    CHANGE column_name new_column_namenew_type; withoutAUTO_INCREMENT Just simply without AUTO_INCREMENT

    After remove AUTO_INCREMENT, then you candrop the PRIMARY KEY, otherwise, will be error

    Remove PRIMARY KEYALTER TABLE table_name

    DROP PRIMARY KEY;

  • 8/3/2019 100890_633608325477500000

    28/107

    28

  • 8/3/2019 100890_633608325477500000

    29/107

    29

    String functions (1)

    SELECT RIGH

    T(column_name, number) FROM table_name;Can use RIGHT, LEFT start from right or left side of

    column

    Number: how many characters to select

    SELECT SUBSTRING_INDEX (column_name,key, index)

    FROM table_name;

    SUBSTRING_INDEX

    subestring, everything in frontof it

    key the key character, key string is looking for

    Index 1 means looking for the first key, 2 meanslooking for the second key

  • 8/3/2019 100890_633608325477500000

    30/107

    30

    String functions (2)

    SUBSTRING(string, index, index); SUBSTR(string, index)Shortening the length of the string start right after the index

    UPPER(string);

    LOWER(string);

    REVERSE(string);

    LTRIM( string);

    RTRIM(string );

    LENGTH(string);

  • 8/3/2019 100890_633608325477500000

    31/107

    31

    Copy

    Change all the data in a columnUPDATE table_name

    SET column_name = new_value;

    Copy columnUPDATE table_name

    SET column_name = source_column_name;

    Can use all the string function

  • 8/3/2019 100890_633608325477500000

    32/107

    32

    Group data (1) Category

    UPDATE table_name

    SET category = value WHERE conditions

    Update statements help you classify data

    Update statements order matters, due to they maychange same value

    group data data have same value in the

    column

    SELECT * FROM table_nameGROUP BY column_name;

    Only show the only one and the first one record

  • 8/3/2019 100890_633608325477500000

    33/107

    33

    Group data (2)

    Choose valueUPDATE table_nameSET column_name =

    CASE

    WHEN condition1 THEN new_value1

    WHEN condition2 AND condition3 THEN new_value2

    ELSE new_value3 elseisoptional

    END;

    or

    END WHERE condition4; usethisconditiontochoosespecificrows;

    CASE expression can be used with SELECT,INSERT, DELETE and UPDATE

  • 8/3/2019 100890_633608325477500000

    34/107

    34

    Order data (1)

    Show ordered dataSELECT column_names,

    FROM table_name

    WHERE conditions,

    ORDER BY column_name;

    Order rulesNon-alphabet

    Number < text character

    NULL < Number

    NULL < alphabet character

    Uppercase < Lowercase

    Space < number

  • 8/3/2019 100890_633608325477500000

    35/107

    35

    Order data (2)

    Ordered data by multiple columnsORDER BY column_name1,

    column_name2, ;

    First order by column_name1, then 2

    Descending order

    ORDER BY column_name DESC;

    Can use DESCRIBE for DESC table_name

    But can not use DESCENDING

    Default order

    ASC means default order

  • 8/3/2019 100890_633608325477500000

    36/107

    36

    Calculate data (1)

    NULL is not used by all the calculationfunctions (absence)

    SUM()SELECT columns, SUM (column_name1)

    FROM table_name

    GROUP BY column_name1;

    Group all the date with same value in column_name1

    Sum all value within the group

    AVG()SELECT columns, AVG (column_name1)

    FROM table_name

    GROUP BY column_name1;

  • 8/3/2019 100890_633608325477500000

    37/107

    37

    Calculate data (2)

    MIN()SELECT columns, MIN (column_name1)

    FROM table_name

    GROUP BY column_name1;

    MAX()

    SELECT columns, MAX (column_name1)

    FROM table_name

    GROUP BY column_name1;

  • 8/3/2019 100890_633608325477500000

    38/107

    38

    Calculate data (3)

    COUNT(): Count number of the rows in the columnSELECT COUNT (column_name)

    FROM table_name;

    GROUP BY another_column;

    DISTINCT: Remove all the duplicate records

    SELECT DISTINCT column_nameFROM table_name

    Be careful DISTINCT is a keyword

    DISTINCT + COUNT() use to calculate the number ofabsolute different data

    DISTINCT is used to remove duplicate record

    COUNT is used the count the number of the rows

    Thus this avoid count duplicate records

  • 8/3/2019 100890_633608325477500000

    39/107

    39

    Calculate data (4)

    Limit the number of resultsSELECT columns, SUM (column_name1)

    FROM table_name

    GROUP BY column_name1;

    ORDER BY SUM (column_name1);LIMIT number;

    ORDER BY must after the GROUP BY

    Limit number by rangeLIMIT index1, index2

    index1 is start point Start from 0

    Index2 is number of showing result

  • 8/3/2019 100890_633608325477500000

    40/107

    40

    SCHEMA

    Schema is : Adescription of thedata (columns andtables) in yourdatabase, along with

    any other relatedobjects and the waythey all connect

    Diagram for tabledesign

    Split the non-atomicfield into anothertable

  • 8/3/2019 100890_633608325477500000

    41/107

    41

    Connect tables (1)

    FOREIGN KEYIs a column in a table that reference the

    PRIMARY KEY of another table

    Child_tables FOREIGN KEY is the PRIMARY KEY

    of Parent_table FOREIGN KEY is parent key, is from parent table

    FOREIGN KEY can be different name

    FOREIGN KEY can be NULL

    means there is no matching primary key in parenttable

    FOREIGN KEY dont have to be unique

  • 8/3/2019 100890_633608325477500000

    42/107

    42

    Connect tables (2)

    Foreign key + constraintReferential integrity

    Only be able to insert values into your

    foreign key that in parent table

    Use a foreign key to reference a unique value

    in the parent table

    UNIQUE

    Not available in MySQL

    CHECK

  • 8/3/2019 100890_633608325477500000

    43/107

    43

    Create child table (1)

    CREATE TABLE table_name (Columns ,

    child_column_name INT NOT NULL, Define child table column name, type,

    Dont forget ,CONSTRAINT parent_id_fk

    name: parent_table_name +parent_column_name + fk(foreign key)

    FOREIGN KEY (child_column_name)

    REFERENCES parent_table_name(parent_column_name)

    ) ; book has mistake here

  • 8/3/2019 100890_633608325477500000

    44/107

    44

    Relationships

    One-to-one: plain lineFaster queries

    Isolate column to avoid NULL in main table

    Make part of data less accessible

    Put large piece data into a separate table

    One-to-many: black arrow line, only onearrow at the end of many

    Many-to-many: black arrow line, arrows atboth endsTwo one-to-many relationships with ajunction table in between

  • 8/3/2019 100890_633608325477500000

    45/107

    45

    Junction table

    Avoid duplicate data in many-to-manyrelationship

    A table step in between two many-to-

    many tables and simplify therelationship to one-to-many.

    Contain the two primary key columns of

    the two related table.

  • 8/3/2019 100890_633608325477500000

    46/107

    46

    Composite primary key

    Is a primary key Uses several columns together to form

    a unique primary key in a table

  • 8/3/2019 100890_633608325477500000

    47/107

    47

    Dependent column

    The A column functionally depend B column, A must change when Bs data is modified

    Notations

    T.x ; T.y

    Relational table T, column y is functionally dependenton column x

    Partial functional dependency

    Non-key column is dependent on some but not all, of

    the columns in a composite primary key Transitive functional dependency

    Non-key column is related to any of the other non-

    key columns

  • 8/3/2019 100890_633608325477500000

    48/107

    48

    2NF- Second Normal Form

    2NF focuses on how the primary keyrelates to the data

    2NF rules:

    Be in 1NF

    Have no partial functional dependencies

    1NF is also 2NF

    If all the columns in the table are part of the

    primary key

    OR

    It has a signal column primary key

  • 8/3/2019 100890_633608325477500000

    49/107

    49

    3NF- Third Normal Form

    3NF rules:Be in 2NF

    Have not transitive dependencies

    Table is in 2NFIf it has an artificial primary key and no

    composite primary key

  • 8/3/2019 100890_633608325477500000

    50/107

    50

  • 8/3/2019 100890_633608325477500000

    51/107

    51

    Pre-populate table (1)

    Create table, then insert with selectCREATE TABLE table_name normalway

    (

    Create Primary_key column,

    Column_name

    );

    INSERT INTO table_name (column_name)

    SELECT column_name

    FROM parent_table_nameGROUP BY column_name

    ORDER BY column_name;

  • 8/3/2019 100890_633608325477500000

    52/107

    52

    Pre-populate table (2)

    Create table with select, then alter to addprimary keyCREATE TABLE table_name

    AS

    SELECT column_name

    FROM parent_table_nameGROUP BY column_name

    ORDER BY column_name;

    ALTER TABLE table_name

    ADD COLUMN primary_key column; AS funneling all the output of the SELECT

    into the new table

  • 8/3/2019 100890_633608325477500000

    53/107

    53

    Pre-populate table (3)

    Create, select and insert at the same timeCREATE TABLE table_name

    (

    Create Primary_key column,

    Column_name) AS

    SELECT column_name

    FROM parent_table_name

    GROUP BY column_name ORDER BY column_name

    ;

  • 8/3/2019 100890_633608325477500000

    54/107

    54

    alias

    SQL allow to temporarily give the columnsand tables new names

    Column aliasesSELECT column_name AS column_alias

    temporary

    FROM table_nameGROUP BY column_alias

    ORDER BY column_alias;

    Table aliases: called correlation nameSELECT column_name AS column_alias

    FROM table_name AS table_alias

    OR

    FROM table_name table_alias without AS

  • 8/3/2019 100890_633608325477500000

    55/107

    55

    Cartesian Join (1)

    Different names: Cartesian product, crossproduct, cross join, no join

    SELECT TableA.column1, TableB.column2

    FROM TableA CROSS JOIN TableB

    OR FROM TableA , TableB

    COMMA JOIN use , instead of CROSS JOIN

    Return every row from table_A cross withevery row from table_B

    The column which has more values, thecolumn show up in groups.

  • 8/3/2019 100890_633608325477500000

    56/107

    56

    Cartesian Join (2)

    UsageCan help with fix the joins

    Used to test the speed of the RDBMS and its

    configuration

    Cartesian join is a type of inner join

  • 8/3/2019 100890_633608325477500000

    57/107

    57

    InnerJoin

    InnerJoin combine records from two tablesusing comparison operator in a condition

    Columns only return the matched join rows

    InnerJoin is a Cross Join with some result rows

    removed by a condition in the query Create InnerJoin

    SELECT A.columns, ... , B.columns, , columns

    From table_A AS A INNER JOIN Table_B AS B

    ON A.column = B.column; relationship Also can use WHERE

    Matches the two columns in different tables

  • 8/3/2019 100890_633608325477500000

    58/107

    58

    InnerJoin in actions

    Equijoin INNER JOIN

    ON A.id = B.id;

    Inner join test for equality

    Non-euqijoin

    INNER JOIN ON A.id B.id;

    Inner join test for inequality

    Natural join

    SELECT columns, FROM table_A NATURAL JOIN table_B;

    Inner join identify matching column names

    Do not need ON conditions

  • 8/3/2019 100890_633608325477500000

    59/107

    59

    Subquery (1)

    A query is wrapped within anotherquery

    OUTER query

    INNER query Subquery

    Take the result of one query and use it

    as the input to another query

    Can be used to

    Avoid duplicate data

    Make queries more dynamic

  • 8/3/2019 100890_633608325477500000

    60/107

    60

    Subquery (2)

    Subquery is always a single SELECT statement

    Subqueries are always inside () parentheses

    Subqueries do not get their own ; semicolonOne ; semicolon goes at the end of entire query

    Subqueries can be show up in four places

    SELECT clauseSELECT column List

    FROM clause

    HAVING clause

    Subqueries can be used withINSERT

    DELETE

    UPDATE

    SELECT

  • 8/3/2019 100890_633608325477500000

    61/107

    61

    Subquery (3)

    SELECT columns FROM table_A

    NATURAL JOIN

    table_B WHERE column_name

    IN (SELECT column FROM table_C);

    SubqueryAll others are OUTER query

  • 8/3/2019 100890_633608325477500000

    62/107

    62

    Subquery (4)

    SELECT columns

    FROM table_name

    WHERE condition (subquery)

    Usually, Subquery return single value, one rowfrom one column

    where column = (subquery)Subquery return more than one value when using

    IN

    where column IN (subquery)

    Subquery also can use WHERE condition Can use subquery instead the INNER JOIN

    Join combine all columns from two tables

    Subquery can only use the columns from one table

  • 8/3/2019 100890_633608325477500000

    63/107

    63

    Subquery as SELECT column

    Used as a column expression inSELECT statement

    Can only return one value from one

    columnSELECT columns

    (SELECT column

    FROM table

    WHERE conditions)

    FROM table

  • 8/3/2019 100890_633608325477500000

    64/107

    64

    Noncorrelated subquery

    Correlated subquery is slow Noncorrelated subquery

    Subquery stands alone

    Doesnt reference anything from the outer query

    Inner query in no way depends on valuesfrom the outer query

    It can run as a standalone query

    Noncorrelated subquery with IN, NOT INUse IN, NOT IN to test if the values returned in

    subquery are members of a set(or not)

  • 8/3/2019 100890_633608325477500000

    65/107

    65

    Correlated subquery

    Correlated subqueryInner query relies on the outer query before it

    can be resolved

    Use the same alias or correlated name from

    the outer query

    Common use

    Find all the rows in the outer query for which

    no rows exist in a related tableEXISTS

    NOT EXISTS

  • 8/3/2019 100890_633608325477500000

    66/107

    66

    EXISTS and NOT EXISTS EXISTS: Find the results in table_A which at least shows

    in table_B onceSELECT columns

    FROM table_A

    WHERE EXISTS

    (SELECT * FROM table_B

    WHERE condition usuallyconditioninvolveouterquery);

    NOT EXISTS: Find the results in table_A which is not intable_BSELECT columns

    FROM table_AWHERE NOT EXISTS

    (SELECT * FROM table_B

    WHERE condition usuallyconditioninvolveouterquery

    );

  • 8/3/2019 100890_633608325477500000

    67/107

    67

    OuterJoin (1)

    Deal with two tables which dont have anymatching counterpart

    Relationship between two tables

    One-to-many relationship

    LEFT OUTER JOIN:SELECT columns

    FROM Left_table

    LEFT OUTER JOIN Right_table

    ON relationship;

    Takes all the rows in the Left_table and

    matches them to rows in the Right_table.

  • 8/3/2019 100890_633608325477500000

    68/107

    68

    OuterJoin (2) RIGHT OUTER JOIN:

    SELECT columns

    FROM Left_table

    RIGHT OUTER JOIN Right_table

    ON relationship;

    Takes all the rows in the Right_table and matches them to

    rows in the Left_table.Reverse the LEFT OUTER JOIN Reason to use these two: change the key word is easier than

    change the order of the tables

    Similar with INNER JOIN but not OUTER JOIN givesall the rows whetherthere is a match with the other

    table or notUse NULL value to show no match exists

    In LEFT OUTER JOIN, NULL means the Right_table has no valuethat correspond to the Left_table

    Some RDBMS use FULL OUTER JOIN, but not inMySQL, SQL Server or Access

  • 8/3/2019 100890_633608325477500000

    69/107

    69

    Self-join (1)

    Self-referencing foreign keymeans that it is a key is referencing another field inthe same table

    The primary key of a table used in that sametable for another purposeThe primary key use to describe other attribute of the

    elements

    Join a single table to itself

    Used to simulate having two tables with

    exactly same informationIn a normalized database, would never have two

    copies of the same table

  • 8/3/2019 100890_633608325477500000

    70/107

    70

    Self-join (2)

    Use different alias to separate the sametable act as two tables

    SELECT alias1.column, , alias.column, ,

    FROM table_name AS alias1

    INNER JOIN

    Table_name AS alias2

    ON alias1.primary_key =

    alias2.self_referencing_key;

  • 8/3/2019 100890_633608325477500000

    71/107

    71

    Union Combine the results of queries

    Combine the results from multiple tablesSELECT column FROM table_A

    UNION

    OR

    UNION ALL Return every match, including the duplicate values

    By default, results removed duplicate values

    SELECT column FROM table_B

    ORDER BY column; Only can add ORDER BY at the end of the statement

    Rules:

    Number of columns in each SELECT statement must matchMust have same expression and aggregate function in each

    SELECT statement

    Order of SELECT statement doesnt matter

    The data types in the columns need to either same orconvertible to each other

  • 8/3/2019 100890_633608325477500000

    72/107

    72

    INTERSECT & EXCEPT

    UNION, INTERSECT, EXCEPT are usedto find parts of queries that overlap

    INTERSECT:

    Returns only those values that are in the first

    query and also in the second query

    EXCEPT:

    Returns only those values that are in the first

    query but not in the second query

    MySQL do not have INTERSECT and

    EXCEPT

  • 8/3/2019 100890_633608325477500000

    73/107

    73

    Subqueries vs. Joins (1) Subquery ORDER BY + LIMIT

    SELECT title FROM job_listingsWHERE salary =

    (SELECT MAX(salary) from job_listings);

    Howabout:SELECT title FROM job_listings

    ORDER BY salary DESC

    LIMIT 1; Self-join subquery

    SELECT f1.name, f2.name AS boss

    FROM friend f1

    INNER JOIN friend f2

    ON f1.id = f2.boss;

    Howabout:SELECT f1.name,

    (SELECT name FROM friend WHERE f1.boss = id) AS boss

    FROM friend f1;

  • 8/3/2019 100890_633608325477500000

    74/107

    74

    Subqueries vs. Joins (2)

    InnerJoin Subquery

    SELECT title

    FROM job_listings jl

    INNER JOIN job_current jc

    ON jl.title = jc.title;

    Howabout:SELECT title

    FROM job_listings

    WHERE title IN

    (SELECT title from job_current);

  • 8/3/2019 100890_633608325477500000

    75/107

    75

    Database management

    Defensive databaseAvoid entering wrong data

    Stop concurrent operation on the same data

    at the same time

    CHECK constraints and views both help maintaincontrol when you have multiple users

    Limit authority to allow operate on part of

    data

  • 8/3/2019 100890_633608325477500000

    76/107

    76

    CHECK CONSTRAINT Constraint

    Is a restriction on what you can insert into a columnExample: NOT NULL, PRIMARY KEY, FOREIGN KEY, UNIQUE

    CHECKCREATE TABLE table_name (

    Column_name type CHECK (column_name IN (F, M))

    Condition can be any);

    ORALTER TABLE table_name

    ADD CONSTRAINT CHECK column_name IN () ; condition

    CHECK constraint restricts what values you can insert into a columnTry to INSERT INTO wrong data will get a error and nothing be inserted

    Use the same conditions as a WHERE clause, such as AND, OR, IN,

    NOT, BETWEEN, but not subquery

    CHECK doesnt enforce data integrity in MySQLCan create table with check, but MySQL wont do anything and just ignores

    it.

  • 8/3/2019 100890_633608325477500000

    77/107

    77

    View (1)

    View

    Is basically a table that only exists when you use view in

    query

    Virtual table

    Can turn any query as a SELECT into a view

    View can do more than SELECT data from tables,also can UPDATE, INSERT, DELETE

    Benefits

    Keep change database structure from breaking the

    applications that depend on the tablesMake easier by simplifying the complex query into a simple

    command

    Create view to hide information that isnt needed by the use

  • 8/3/2019 100890_633608325477500000

    78/107

    78

    View (2) Create a view

    CREATE VIEW view_name ASConditions Allthe queries youwanttodo

    ;

    Use the viewSELECT * FROM view_name;

    Actually viewdo allthe job ofthe queries youdefinedwhenithas beencreated

    Delete viewDROP VIEW view_name;

    Different RDBMSs has different behaviors

    Best drop views before drop the table it is based on

    MySQL wont let you drop views without its base table isexisting, but you can drop table which has view

    Check structureDESC view_name;

  • 8/3/2019 100890_633608325477500000

    79/107

    79

    View (3)

    CHECK OPTIONCREATE VIEW view_name AS

    WHERE Conditions

    WITH CHECK OPTION;

    Force all inserts and updates to satisfy the

    WHERE clause in the view

    MySQL use CHECK OPTION to imitate

    the CH

    ECK CONSTRAINTIf the update/insert data is not according the

    condition of view, it will show error

  • 8/3/2019 100890_633608325477500000

    80/107

    80

    View (4)

    Updatable viewAn updatable view includes all the NOT NULL

    columns from the table it references

    Allow this kind of view to do the INSERT, UPDATE,DELETE due to all the NOT NULL column can be

    touched via the view Non-updatable view

    doesnt include all the NOT NULL columns

    Only can do is SELECT

    CANNOT update views that containsaggregate operatorsSUM, COUNT and AVG

    BETWEEN, HAVING, IN, and NOT IN

  • 8/3/2019 100890_633608325477500000

    81/107

    81

    ACID

    A: ATOMICITYAll the pieces of transaction must be completed or

    none of them be completed.

    C: CONSISTENCYKeep database in a consistent state at the end of

    transaction.

    I: ISOLATIONEvery transaction has a consistent view of the

    database regardless of other transaction take placeat the same time.

    D: DURABILITYAfter transaction, the database needs to save thedata correctly and protect it from power outages orother threats.

  • 8/3/2019 100890_633608325477500000

    82/107

    82

    Transaction (1)

    Transaction is a set of SQL statementsto accomplish a single unit of work

    During a transaction, if all the steps

    cant be completed without interference,

    none of them should be completed.

    Avoid concurrent problem

  • 8/3/2019 100890_633608325477500000

    83/107

    83

    Transaction (2)

    START TRANSACTION;START TRANSACTION keeps track of all the SQL

    COMMIT;Make the actions permanent

    ROLLBACK;Reverse everything to the way it was before youSTART TRANSACTION

    No change will occur to the database untilyou COMMIT

    RDBMS keep record of everything that hasbeen done when you inside a transactionIt cost storage space

  • 8/3/2019 100890_633608325477500000

    84/107

    84

    Storage engines

    Make sure your storage engine is eitherBDB or InnoDB,

    BDB, InnoDB are two possible way that

    support transaction

    RDBMS can store data behind the scenes.

    Change storage engine

    ALTER TABLE table_name TYPE = InnoDB;

  • 8/3/2019 100890_633608325477500000

    85/107

    85

    Root user account ROOT user

    The first user ROOT user has complete control overeverything in the database.

    Set passwordSET PASSWORD FOR

    root @ localhost

    = PASSWORD(password);ORACLE use:

    ALTER user root IDENTIFIED BY new_password; Root users user name: root

    localhost indicates that this is where the SQL software isinstalled and running

    localhost is the default value, and it is optional

    Remote accessYou have to tell the query: IP address, or a hostname instead

    of localhost. [email protected]

    C

  • 8/3/2019 100890_633608325477500000

    86/107

    86

    Create new user

    SQL doesnt specify how to manageusers

    Need check RDBMSs documentation

    Most use statements:

    CREATE USER user_name

    IDENTIFIED BY user_password;

    GRANT (1)

  • 8/3/2019 100890_633608325477500000

    87/107

    87

    GRANT (1) Control exactly what users can do to tables

    and columns Typical

    GRANT SELECT Can change to INSERT, DELETE, UPDATE

    ON table_name

    TO user_name;

    Give multiple privilegeGRANT SELECT, INSERT

    ON table_name

    TO user_name; Name multiple users

    GRANT DELETE

    ON table_name

    TO user1, user2;

    GRANT (2)

  • 8/3/2019 100890_633608325477500000

    88/107

    88

    GRANT (2)

    Assign ALL privilegesGRANT ALLON table_name

    TO user_name;

    Allow all permission with SELECT, INSERT,DELETE, UPDATE

    Allow current user gives this privilegeto any other user

    GRANT SELECTON table_name

    TO user_name WITH GRANT OPTION

    GRANT (3)

  • 8/3/2019 100890_633608325477500000

    89/107

    89

    GRANT (3)

    Specific column: only can used for SELECT

    GRANT SELECT (column_name, column_name 2)

    ON table_name

    TO user_name

    Wildcard: Give the user the privilege for everytable in the database

    GRANT SELECT

    ON database_name.*

    TO user_name

    GRANT global privileges in MySQL

    GRANT SELECT ON *.*

    TO user_name;

    REVOKE (1)

  • 8/3/2019 100890_633608325477500000

    90/107

    90

    REVOKE (1)

    REVOKE privilegesREVOKE SELECT

    ON table_name

    FROM user_name;

    If the unassigned privilege with get an error

    Revoke GRANT OPTION privilege: Withoutremove the privilege on current user, justremove the GRANT OPTION privilegeREVOKE GRANT OPTION

    ON DELETE

    ON table_nameFROM user_name;

    CAN NOT assign this privilege to others any more

    But, all the usergot the privilege from this user, willlose their permission as well

    REVOKE (2)

  • 8/3/2019 100890_633608325477500000

    91/107

    91

    REVOKE (2)

    CASCADE: Remove the privilege from currentuser as well as anyone else that current usergave permission to. (usually is default)REVOKE DELETE

    ON table_name

    FROM user_name CASCADE;

    RESTRICT: both current user and thesub_user can retain the privilege, the root getan error, if the current user gave any otheruser this privilege before

    REVOKE DELETEON table_name

    FROM user_name RESTRICT;

    REVOKE (3)

  • 8/3/2019 100890_633608325477500000

    92/107

    92

    REVOKE (3)

    If the user get the privilege fromdifferent time/people

    Different RDBMSs have different response

    Some will pay attention to where GRANT

    came from when CASCADE is used

    Some will ignore it

    Just check the documentation

    Both GRANT, REVOKE can use on VIEW,but be careful with the non-updatable

    view

    R l (1)

  • 8/3/2019 100890_633608325477500000

    93/107

    93

    Role (1)

    There is no ROLE in MySQL

    To give groups the privileges instead ofassign them individually

    CreateCREATE ROLE role_name;

    Define roles privilegesGRANT SELECT

    ON table_name

    TO role_name;

    Assign user to the roleGRANT role_name

    TO user_name;

    R l (2)

  • 8/3/2019 100890_633608325477500000

    94/107

    94

    Role (2)

    Delete roleDROP ROLE role_name;

    Drop a role in use, it also cut related users off

    from the permissions

    Revoke role from userREVOKE role_name

    FROM user_name;

    A user can have more than one role at a time

    Need make sure do not have conflicting

    permissions

    Denied permission > Grant permission

    R l (3)

  • 8/3/2019 100890_633608325477500000

    95/107

    95

    Role (3)

    Allow the roles users to grant this roleto anyone elseGRANT role_name

    TO user_name WITH ADMIN OPTION

    CASCADEREVOKE role_name

    FROM user_name CASCADE;

    RESTRICTREVOKE role_name

    FROM user_name RESTRICT;

    Combine ser creation and grant

  • 8/3/2019 100890_633608325477500000

    96/107

    96

    Combine user creation and grant

    GRANT SELECT ON table_name

    TO user_name

    IDENTIFIED BY password;

    Check status

  • 8/3/2019 100890_633608325477500000

    97/107

    97

    Check status

    Check current userSELECT CURRENT_USER;

    root@localhost

    Check current

    SELECT CURRENT_DATE;

    SELECT CURRENT_TIME;

    Reserved words

  • 8/3/2019 100890_633608325477500000

    98/107

    98

    Reserved words

    There are bunch of reserved words.When try to use single-world, you glance

    through the lists to make sure

    SQL has a list of non-reserved words

    may become reserved in future releasesof SQL.

    Special characters

  • 8/3/2019 100890_633608325477500000

    99/107

    99

    Special characters

    *

    ()

    ;

    ,

    .

    _

    %

    !

    \

    +

    Comparison

    >

    !=

  • 8/3/2019 100890_633608325477500000

    100/107

    100

    ALL

    BeforeSELECT columns FROM table_name

    WHERE column IN

    (SELECT column FROM table_name);

    ALL:Greater than ALL finds any values larger than the

    biggest value in the set

    SELECT columns FROM table_name

    WHERE column > ALL

    (SELECT column FROM table_name);

    Less than ALL finds any values smaller than thesmallest value in the set

    WHERE column < ALL

    ANY

  • 8/3/2019 100890_633608325477500000

    101/107

    101

    ANY

    ANY

    Greater than ANY finds any values larger than

    the smallest value in the set

    SELECT columns FROM table_name

    WHERE column >ANY(SELECT column FROM table_name);

    Less than ANY finds any values smaller than

    the largest value in the set

    SELECT columns FROM table_nameWHERE column < ANY

    (SELECT column FROM table_name);

    SOME

  • 8/3/2019 100890_633608325477500000

    102/107

    102

    SOME

    Means the things as ANY in standardSQL syntax, and in MySQL .

    Check the RDBMS to confirm that it

    works which way

    Temporary table

  • 8/3/2019 100890_633608325477500000

    103/107

    103

    Temporary table

    Temporary table exists from the time youcreate it until you drop it, oruntil the usersession endsSession means from signed in to sign out

    RDBMS syntax varies greatly with this, please check

    first

    CREATE TEMPORARY TABLE table_name

    ( columns);

    OR

    CREATE TEMPORARY TABLE table_name

    AS

    SELECT * FROM permanent_table;

    Numeric functions

  • 8/3/2019 100890_633608325477500000

    104/107

    104

    Numeric functions

    ABS(x)

    ACOS(x) ASIN(x)

    ATAN(x,y)

    CELL(x)

    COS(x) COT(x)

    EXP(x)

    FLOOR(x)

    FORMAT(x,y)

    LN(x) LOG(x), LOG(x,y)

    MOD(x,y)

    PI()

    POWER(x,y)

    RADIANS(x)

    RAND(x)

    ROUND(x), ROUND(x,y)

    SIGN(x)

    SIN(x)

    SQRT(x)

    TAN(x)

    TRUNCATE(x,y)

    Indexing

  • 8/3/2019 100890_633608325477500000

    105/107

    105

    Indexing

    Index help RDBMS speed upIf you search the column frequently

    Add index

    ALTER TABLE table_name

    ADD INDEX (column_name);

    To becontinue

    Get a GUI for RDBMS

  • 8/3/2019 100890_633608325477500000

    106/107

    106

    Get a GUI for RDBMS

    MySQL GUI toolshttp://dev.mysql.com/downloads/gui-tools/5.0.html

    CocoaMySQLhttp://cocoamysql.sourceforge.net/

    Web solution: phphMySQLhttp://www.phpmysql.net/

    Navicat offer 30 days free trailhttp://www.navicat.com/

    SQLyog offers a free community editionhttp://www.webyog.com/en/

    To becontinue

    PHP/MySQL

  • 8/3/2019 100890_633608325477500000

    107/107

    PHP/MySQL

    PH

    P help you get data via web PHP code take all date from database

    and store it in an array

    To becontinue