12-sql73

Upload: smita-r-s

Post on 03-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 12-SQL73

    1/73

    1

    SQLSQL

    (Structured Query Language)(Structured Query Language)

  • 7/28/2019 12-SQL73

    2/73

    2

    Disclaimer & Acknowledgements

    Even though Sang Shin is a full-timeemployee of Sun Microsystems, the contentshere are created as his own personal

    endeavour and thus does not reflect anyofficial stance of Sun Microsystems.

    Sun Microsystems is not responsible for anyinaccuracies in the contents.

  • 7/28/2019 12-SQL73

    3/73

    3

    Revision History 01/24/1998: version 1, created with speaker notes (Edward Haynes) 02/02/2003: version 2, cosmetic change (Sang) 10/10/2004: version 3, cosmetic change (Sang)

  • 7/28/2019 12-SQL73

    4/73

    4

    AgendaWhat is SQL?

    SQL Terminology

    Creating and Deleting Tables

    Select Statement for queryingJoin Statement

    Aliases

    Sub-query

    Comparison, Character match, Numericalexpression

    Insert, Update, Delete

    SQL Data-types

  • 7/28/2019 12-SQL73

    5/73

    5

    What is SQL?What is SQL?

  • 7/28/2019 12-SQL73

    6/73

    6

    What is SQL?

    SQL provides a way to retrieve andmanipulate data in a relational database

    SQL is used for all relational databaseoperations, including administration,schema creation and data retrieval

    Data definition

    Data manipulation

  • 7/28/2019 12-SQL73

    7/737

    What SQL IS NotSQL is a not a programming language

    It does not provide any flow-of-controlprogramming constructs, function definitions,

    do-loops, or if-then-else statements Unlike modern programming languages that

    enable you to define a data type for a specificpurpose, SQL forces you to choose from a setof predefined data types when you create ormodify a column.

    SQL is not a procedural language You use SQL to tell the database what data to

    retrieve or modify without telling it how to do it

  • 7/28/2019 12-SQL73

    8/738

    Similarity with Programming

    LanguageThey both usually give you more than oneway to accomplish the same goal

    Various SQL statements may achieve the sameresults (but differ in processing efficiency andclarity of code)

  • 7/28/2019 12-SQL73

    9/739

    Case Sensitivity

    SQL is not case sensitive

    You can mix uppercase and lowercase

    when referencing SQL keywords(SELECT, INSERT, ...), table names andcolumn names

    However, case does matter when

    referring to the contents of a column; ifyou ask for all the store's where the storename is lower case, but in the databaseall the names are stored in upper case,

    you wont retrieve any rows at all

  • 7/28/2019 12-SQL73

    10/7310

    SQL TerminologySQL Terminology

  • 7/28/2019 12-SQL73

    11/7311

    SQL TermsTable

    A set of rows

    Analogous to a file

    ColumnA column is analogous to a field of a record

    Each column in a given row has a single value

  • 7/28/2019 12-SQL73

    12/7312

    SQL Terms (Continued)Row

    Analogous to a record of a file

    All rows of a table have the same set ofcolumns

    Primary Key

    One of more columns whose contents areunique within a table and thus can be used toidentify a row of that table

  • 7/28/2019 12-SQL73

    13/73

    13

    Creating & DeletingCreating & DeletingTables and otherTables and otherOperations via DDLOperations via DDL

  • 7/28/2019 12-SQL73

    14/7314

    Data Definition Language (DDL)DDL is used for defining the databasestructure

    Create Table, Alter Table, Drop table

    Create Index, Drop Index

    Create User, Alter User, Drop User

    Create Role, Drop RoleCreate Schema, Drop Schema

    Create View, Drop View

    Create Trigger, Drop Trigger

  • 7/28/2019 12-SQL73

    15/7315

    CREATE TABLEcreate table store

    (store_id NUMERIC,

    name VARCHAR(25),city VARCHAR(25),

    state VARCHAR(2),

    zip VARCHAR(25));

  • 7/28/2019 12-SQL73

    16/73

    16

    ALTER TABLEALTER TABLE store ADD UNIQUE (C1);

    ALTER TABLE store ADD ORDER_NUM INT;

    ALTER TABLE store ADD CONSTRAINTconstraint_0 FOREIGN KEY (C1)REFERENCES T1 (C1);

    ALTER TABLE store DROP ORDER_NUMCASCADE;

    ALTER TABLE store RENAME TO T1;

  • 7/28/2019 12-SQL73

    17/73

    17

    DROP TABLEDROP TABLE store;

  • 7/28/2019 12-SQL73

    18/73

    18

    CREATE INDEX & DROP INDEXCREATE INDEX customer_idx

    ON "PBPUBLIC"."CUSTOMER_TBL"

    ( "CUSTOMER_NUM" ASC ,"NAME" ASC )

    DROP INDEX ORDER_TBL.ORDER;

  • 7/28/2019 12-SQL73

    19/73

    19

    CREATE/ALTER/DROP USER

    CREATE USER PoInT PASSWORD BaSE;

    CREATE USER "PoInT" PASSWORD "BaSE";

    ALTER USER Scott PASSWORD lion;

    ALTER USER Scott DEFAULT ROLE CEO;

    DROP USER ENGINEERING_MANAGERCASCADE;

  • 7/28/2019 12-SQL73

    20/73

    20

    CREATE/DROP VIEW

    CREATE VIEW customer_order

    AS selectorder_num,order_tbl.customer_num,customer

    _tbl.nameFROM order_tbl,customer_tbl

    WHERE product_num = 10;

    DROP VIEW customer_order;

  • 7/28/2019 12-SQL73

    21/73

    21

    CREATE/DROP TRIGGERCREATE TRIGGER trigger2

    BEFORE UPDATE ON product_tbl

    REFERENCING NEW AS NEWROW

    FOR EACH ROW

    WHEN (NEWROW.qty_on_hand < 0)

    SET NEWROW.qty_on_hand = 0;

    DROP TRIGGER trigger2

  • 7/28/2019 12-SQL73

    22/73

    22

    Select StatementSelect Statement

  • 7/28/2019 12-SQL73

    23/73

    23

    SELECT StatementSELECT [ DISTINCT | ALL ]

    column_expression1, column_expression2, ....

    [ FROM from_clause ][ WHERE where_expression ]

    [ GROUP BY expression1, expression2, .... ]

    [ HAVING having_expression ]

    [ ORDER BY {column | expression} [asc| desc] ]

    distinct keyword eliminates duplicates

  • 7/28/2019 12-SQL73

    24/73

    24

    SELECT StatementSelect * from customer_tbl;

  • 7/28/2019 12-SQL73

    25/73

    25

    FROM ClauseComma delimited list of tables to retrievedata from

    With or without aliases

  • 7/28/2019 12-SQL73

    26/73

    26

    WHERE ClauseDetermines exactly which rows areretrieved

    Qualifications in the where clause

    Comparison operators (=,>,=,

  • 7/28/2019 12-SQL73

    27/73

    27

    WHERE Clause

    (Continued)Not negates any Boolean expressionsand keywords such as like, null, between

    and in

  • 7/28/2019 12-SQL73

    28/73

    28

    Example: WHERE Clauseselect Customer_num, discount_code, zip, name

    from customer_tbl

    where discount_code in ('N','M','L')

    and zip like '33%'

  • 7/28/2019 12-SQL73

    29/73

    29

    GROUP BY ClauseThe group by function organises data intogroups based on the contents of a column(s)

    Usually used with an aggregate function in the selectlist

    The aggregate is calculated for each group

    All null values in the group by column are treated asone group

    Grouping can be done by a column_name orby any expression that does not contain anaggregate function

  • 7/28/2019 12-SQL73

    30/73

    30

    GROUP BY Clause Cont.The group by function usually containsall columns and expressions in the

    select list that are not aggregates

    In conjunction with the where clause,rows are eliminated before they go into

    groupsApplies a condition on a table before thegroups are formed

  • 7/28/2019 12-SQL73

    31/73

    31

    Example: GROUP BY

    Clauseselect customer_num,

    count(customer_num),

    sum(quantity)from order_tbl

    group by customer_num

  • 7/28/2019 12-SQL73

    32/73

    32

    HAVING ClauseSet conditions on groups

    Restricts groups

    Applies a condition to the groups afterthey have been formed

    having is usually used in conjunction

    with an aggregate function

  • 7/28/2019 12-SQL73

    33/73

    33

    Example: HAVING Clauseselect product_num,

    quantity,

    shipping_costfrom order_tbl

    group by product_num,

    quantity,

    shipping_cost

    having shipping_cost >250

  • 7/28/2019 12-SQL73

    34/73

    34

    ORDER BY ClauseThe order by clause sorts the queryresults (in ascending order by default)

    Items named in an order by clause neednot appear in the select list

    When using order by, nulls are listed first

  • 7/28/2019 12-SQL73

    35/73

    35

    ORDER BY Clause

    Exampleselect product_num,

    quantity,

    shipping_costfrom order_tbl

    group by product_num,

    quantity,

    shipping_cost

    having shipping_cost >250

    order by quantity,

    shipping_cost;

  • 7/28/2019 12-SQL73

    36/73

    36

    Join StatementJoin Statement

  • 7/28/2019 12-SQL73

    37/73

    37

    Join StatementRetrieves data from two or more tables

    Combines tables by matching valuesfrom rows in each table

    Joins are done in the where clause

    Columns in join don't have to be in select

  • 7/28/2019 12-SQL73

    38/73

    38

    Join Statement (Continued)If you do not specify how to join rowsfrom different tables, the database

    server assumes you want to join everyrow in each table

    Cartesian Product

    Very costly (cpu time)

    May take a while to return large result set

    Column names that appear in more thenone table should be prefixed by table

    name

  • 7/28/2019 12-SQL73

    39/73

    39

    Example: Join Statementselect c.name,

    o.quantity,

    o.shipping_costfrom order_tbl o,

    customer_tbl c

    where o.customer_num =c.customer_num;

  • 7/28/2019 12-SQL73

    40/73

    40

    Outer JoinsWith a join, if one row of a table isunmatched, row is omitted from result

    table.The outer join operations retain rowsthat do not satisfy the join condition List branches and properties that are in same

    city along with any unmatched branches.

    SELECT b.*, p.*

    FROM branch1 b LEFT JOIN

    property_for_rent1 p ON b.bcity = p.pcity;

  • 7/28/2019 12-SQL73

    41/73

    41

    bno bcity pno pcity

    ---------------------------------------------

    B3 Glasgow PG4 Glasgow

    B4 Bristol NULL NULL

    B2 London PL94 London

    There is a LEFT JOIN and a RIGHT JOINThese can be very vendor specific (check withyour vendor for outer join specifications)

    Oracle uses (+) for outer joins, MS SQL Server

    uses LEFT OUTER JOIN

    Outer Join cont.

  • 7/28/2019 12-SQL73

    42/73

    42

    AliasAlias

  • 7/28/2019 12-SQL73

    43/73

    43

    AliasUse of temporary names for tableswithin a query

    Can be used anywhere in query

    Reduces amount of typing

    ex. select pub_name, title_id

    from titles t, publishers p

    where t.pub_id = p.pub_id

  • 7/28/2019 12-SQL73

    44/73

    44

    Example: Aliasselect type_code,

    city,

    regionfrom office_tbl;

  • 7/28/2019 12-SQL73

    45/73

    45

    Example: Alias cont.select t.description,

    o.city,

    o.region

    from office_tbl o,

    office_type_code_tbl t

    where o.type_code =

    t.type_code;

  • 7/28/2019 12-SQL73

    46/73

    46

    Sub-QuerySub-Query

  • 7/28/2019 12-SQL73

    47/73

    47

    Sub-QueriesA select statement, used as anexpression in part of anotherselect,update, insert ordelete

    The sub-query is resolved first and theresults are substituted into the outerquery's where clause

    Used because it can be quicker to understandthan a join

    Perform otherwise impossible tasks (i.e. usingan aggregate)

  • 7/28/2019 12-SQL73

    48/73

    48

    Example: Sub-Queryselect product_num,

    description,

    purchase_cost

    from product_tbl

    group by product_num,

    description,

    purchase_cost

    having purchase_cost >

    (select avg

    (shipping_cost)

    from order_tbl);

  • 7/28/2019 12-SQL73

    49/73

    49

    EXISTS and NOT EXISTSEXISTS and NOT EXISTS are for useonly with sub-queries.

    They produce a simple true/false resultEXISTS is true if and only if there existsat least one row in result table returnedby sub-query

    It is false if sub-query returns an emptyresult table

    NOT EXISTS is the opposite of EXISTS

  • 7/28/2019 12-SQL73

    50/73

    50

    EXISTS cont.select o.city,

    s.first_name || ' '||s.last_name

    from sales_rep_tbl s,

    office_tbl o

    where s.office_num =o.office_num

    and exists

    (select 1

    from manufacture_tbl m

    where m.city = o.city);

  • 7/28/2019 12-SQL73

    51/73

    51

    Union, IntersectionUnion, Intersection

  • 7/28/2019 12-SQL73

    52/73

    52

    Union, Intersection and

    DifferenceCan use normal set operations of union,intersection, and difference to combine

    results of two or more queries into asingle result table.

    Union of two tables, A and B, is table

    containing all rows in either A or B orboth.

    Intersection is table containing all rowscommon to both A and B.

  • 7/28/2019 12-SQL73

    53/73

    53

    Union cont.

    Difference is table containing all rows inA but not in B.

    Two tables must be union compatible.(SELECT area

    FROM branch

    WHERE area IS NOT NULL) UNION(SELECT area

    FROM property_for_rent

    WHERE area IS NOT NULL);

  • 7/28/2019 12-SQL73

    54/73

    54

    Comparison,Comparison,Character match,Character match,Numerical ExpressionNumerical Expression

  • 7/28/2019 12-SQL73

    55/73

    55

    Comparison Operators

    = equal to

    > greater than

    < less than!= not equal

    not equal

    !> not greater than

    != greater than / equalto

  • 7/28/2019 12-SQL73

    56/73

    56

    Character Matches

    Use to select rows containing field thatmatch specified portions of character

    stringUse with character data only

    Can use wildcards

    % any string of zero or more characters

    Enclose wildcards and character stringsin quotes

  • 7/28/2019 12-SQL73

    57/73

    57

    Numerical Expressions

    Numerical expressions can be used inany numeric column or in any clause

    that allows an expression+ addition

    - subtration

    * multiplication

    / division% modulos

  • 7/28/2019 12-SQL73

    58/73

    58

    AggregateAggregateFunctionsFunctions

  • 7/28/2019 12-SQL73

    59/73

    59

    Aggregate Functions

    count(*) number of selected rows

    count(col_name) number of nul-null values in column

    max(col_name) highest value in column

    min(col_name) lowest value in column

    sum(col_name) total of values in column

    avg(col_name) average of values in column

    Aggregates ignore null values (exceptcount(*))

    sum and avg only work with numericvalues

  • 7/28/2019 12-SQL73

    60/73

    60

    Aggregate Functions Cont.

    If a group by clause is not used, onlyone row is returned

    Aggregates may not be used in a whereclause

    Aggregates can be applied to all rows in

    a table or to a subset of a tableDistinct keyword eliminates duplicatevalues before applying the aggregate

    function

  • 7/28/2019 12-SQL73

    61/73

    61

    NULL ValuesA null value is an unknown value

    null is a special value which means noinformation available

    is null should be used to match columnscontains null values

    = null can also be used, but is notrecommended

    One null value is never equal to anothernullvalue

    null's sort and group together

    Some columns are defined to permit null

    values

  • 7/28/2019 12-SQL73

    62/73

    62

    Insert, Update,Insert, Update,DeleteDelete

  • 7/28/2019 12-SQL73

    63/73

    63

    INSERT

    INSERT INTO table_name [ ( col_name1, col_name2, .... ) ]

    VALUES ( expression1_1, expression1_2, .... ),

    ( expression2_1, expression2_2, .... ), ....

    INSERT INTO table_name [ ( col_name1, col_name2, .... ) ]

    SELECT ...

    INSERT INTO table_name

    SET col_name1 = expression1, col_name2 = expression2, ....

  • 7/28/2019 12-SQL73

    64/73

    64

    INSERT cont.

    The column list is optional.

    If omitted, SQL assumes a list of allcolumns in their original CREATETABLE order.

    Any columns omitted must have been

    declared as NULL when table wascreated, unless DEFAULT was specifiedwhen creating column.

  • 7/28/2019 12-SQL73

    65/73

    65

    INSERT cont.

    Data value list must match column list asfollows:

    Number of items in each list must be the same.

    Must be direct correspondence in position of itemsin two lists.

    Data type of each item in data_value_list must be

    compatible with data type of corresponding column.

  • 7/28/2019 12-SQL73

    66/73

    66

    INSERT Examples

    Not specifying column names:

    INSERT INTO Dept VALUES (1, 'Engineering', ProjectSet());

    Specifying column names:

    INSERT INTO staff (sno, fname, lname, position, salary, bno)

    VALUES ('SG44', 'Anne', 'Jones', 'Assistant', 8100, 'B3');

    Insert using a select statement

    INSERT INTO stores (store_name, total_sales)

    SELECT ...

  • 7/28/2019 12-SQL73

    67/73

    67

    UPDATE

    UPDATE table_name

    SET col_name1 = expression1, col_name2 = expression2, ....

    [ WHERE expression ]

    [ LIMIT limit_amount ]

    SET clause specifies names of one or more columns that are tobe updated.

    Where clause is optional.

    If omitted, named columns are updated for all rows intable.

  • 7/28/2019 12-SQL73

    68/73

    68

    Update Example

    UPDATE emp

    SET sal = sal * 1.1WHERE empno NOT IN (SELECT empno FROM bonus);

    UPDATE staffSET salary = salary*1.05

    WHERE position = 'Manager';

  • 7/28/2019 12-SQL73

    69/73

    69

    DELETE

    DELETE FROM table_name

    [ WHERE expression ]

    [ LIMIT limit_amount ]

    where is optional; if omitted, all rows are deleted from table. Thisdoes not delete table. If the where is specified, only those rowsthat satisfy condition are deleted.

  • 7/28/2019 12-SQL73

    70/73

    70

    DELETE examples

    delete from store where store_num = 221;

    Delete all information from the store table:

    delete from store;

  • 7/28/2019 12-SQL73

    71/73

    71

    SQL Data TypesSQL Data Types

  • 7/28/2019 12-SQL73

    72/73

    72

    SQL Data Types

    Data Type Declarationcharacter CHAR, VARCHAR

    bit BIT, BIT VARYINGnumeric NUMERIC, DECIMAL, INTEGER

    approx. numeric FLOAT, REAL, DOUBLE

    datetime DATE, TIME, TIMESTAMP

  • 7/28/2019 12-SQL73

    73/73

    Passion!Passion!