Beginning SQL

download Beginning SQL

of 46

description

Beginning SQL

Transcript of Beginning SQL

  • 5/27/2018 Beginning SQL

    1/46

    SQLJumpstart

    Mark Holm

    Centerfield Technology

  • 5/27/2018 Beginning SQL

    2/46

    Goals

    Get you started with SQL

    Show how SQL works with an existing

    environment

    Lay the groundwork for learning more

    2

  • 5/27/2018 Beginning SQL

    3/46

    Notes

    V4R3 and higher syntax used in examples

    Examples show only a small subset of what

    can be done!

    3

  • 5/27/2018 Beginning SQL

    4/46

    Agenda

    Explain why SQL is important

    Compare SQL with traditional approaches

    Data definition statements

    Selecting data

    Changing dataUsing SQL day to day

    4

  • 5/27/2018 Beginning SQL

    5/46

    Why SQL?

    Simplifies cross platform development

    SQL generation can be automated

    Allows quick and flexible access to data

    Operates on sets of data -> powerful

    Official industry standard used by pervasive APIs

    & products

    ODBC/JDBC

    Most query tools

    Can perform better than traditional methods!

    5

  • 5/27/2018 Beginning SQL

    6/46

    Why SQL?

    Business Intelligence

    Query tools

    Data manipulation & (some) data cleanup

    Web sites & internet applications

    Net.Data

    JDBC

    ERP applications SSA eBPCS

    JDE One World

    Mapics XA

    6

  • 5/27/2018 Beginning SQL

    7/46

    Tools

    Interactive SQL (STRSQL)

    Run SQL statement (RUNSQLSTM)

    Operations Navigator

    Query tools (ODBC)

    And many others..

    7

  • 5/27/2018 Beginning SQL

    8/46

    Basic statements

    Create Collection = CRTLIB

    Create Table = CRTPF

    Create View = CRTLF (no key)

    Create Index = CRTLF (key)

    Insert, Update, Delete = add, change, andremove records

    Select = select records & columns to read

    8

  • 5/27/2018 Beginning SQL

    9/46

    Data definition (DDL)

    Data definition statements create objects

    Collections (libraries)

    Tables (physical files)

    Views (non-keyed logical files)

    Indexes (keyed logical files)

    9

  • 5/27/2018 Beginning SQL

    10/46

    Create collection

    Create collection = Create library

    Example: CREATE COLLECTION HR

    Objects created:Library named HR

    Journal & journal receiver

    Catalogs (e.g. SYSTABLES)

    10

  • 5/27/2018 Beginning SQL

    11/46

    DSPLIB of a newly created COLLECTION

  • 5/27/2018 Beginning SQL

    12/46

    Create Table

    Create table = Create physical file (CRTPF)

    Objects created, etc.:Physical file

    File automatically journaled to QSQJRN

    Example: Create a table to hold employee

    information

    12

  • 5/27/2018 Beginning SQL

    13/46

    Create table

    CREATE TABLEHR/EMPLOYEE

    (FIRST_NAME FOR COLUMNFNAME CHAR (20 ) NOT NULL,

    LAST_NAME FOR COLUMN LNAME CHAR (30 ) NOT NULL,

    EMPLOYEE_ID FOR COLUMN EMP_ID NUMERIC (6 , 0)NOT NULL WITH DEFAULT0,DEPARTMENT FOR COLUMN DEPT DECIMAL (3 , 0) NOT NULL WITH DEFAULT,

    TITLE CHAR (30 ) NOT NULL WITH DEFAULT,

    HIRE_DATE FOR COLUMN HDATE DATE NOT NULL)

    13

  • 5/27/2018 Beginning SQL

    14/46

    Tables vs. Physicals

    Tables

    Dirty data cantbe

    inserted Marked as a table

    Maximum 1 member

    No maximum size

    Default to reusedeleted rows

    Table is automatically

    journaled (collection)

    Physical files

    Dirty data can be

    insertedNot an SQL object

    No limit on members

    Default is to cap size

    Default to not reusedeleted records

    File is not

    automatically journaled

    14

  • 5/27/2018 Beginning SQL

    15/46

    Prompt for CREATE TABLE in Interactive SQL

  • 5/27/2018 Beginning SQL

    16/46

    Create View

    Create View = Create logical file (CRTLF)

    Objects created:Logical file

    No keyed access path

    Example: View to format an employees first

    & last name and identify employees hiredless than 2 years prior to today

    16

  • 5/27/2018 Beginning SQL

    17/46

    Create View

    CREATE VIEWHR/NEWBIES (EMPLOYEE_NAME, DEPARTMENT, HIRE_DATE)AS

    SELECT concat(concat(strip(last_name),','),strip(first_name)),

    department,

    hire_date

    FROM HR/EMPLOYEE

    WHERE (year(current date)-year(hire_date)) < 2

    17

  • 5/27/2018 Beginning SQL

    18/46

    DSPFD of a newly created VIEW

  • 5/27/2018 Beginning SQL

    19/46

    View uses

    Subset columns to users or applications

    Create new columns for users or

    applications

    Subset the rows returned (hide data)

    Join tables together

    19

  • 5/27/2018 Beginning SQL

    20/46

    Views vs. Logical files

    View

    Looks like logical file

    Never has an access

    path (index)

    Powerful data

    manipulation

    Slower OPEN time

    Views can reference

    views

    One member

    Logical File

    Is a logical file

    Can be keyed or non-

    keyed Basic data

    manipulation

    Faster OPEN time

    Logical files can notreference LFs

    Many members

    20

  • 5/27/2018 Beginning SQL

    21/46

    Create Index

    Create Index = CRTLF (keyed logical)

    Objects created:Logical file

    Physical access path (index)

    Created to improve performance -- not for

    functionExample: Create an index over the

    employee identifier

    21

  • 5/27/2018 Beginning SQL

    22/46

    Create Index

    CREATE UNIQUE INDEXHR/EMPIDIX

    ONHR/EMPLOYEE(EMPLOYEE_ID ASC)

    22

  • 5/27/2018 Beginning SQL

    23/46

    Indexes vs. Keyed logical files

    Index

    Looks like logical file

    Powerful datamanipulation

    Not usable as file

    One member

    Logical file

    Is a logical file

    Basic datamanipulation

    Like a normal file

    Many members

    23

  • 5/27/2018 Beginning SQL

    24/46

    Deleting objects

    Done with a DROP statement

    DROP TABLE

    DROP VIEW

    DROP INDEX

    By default these statements drop dependent

    objects unlike CL commands (e.g. you cantdelete a PF via DLTF if there are dependent

    logical files)

    24

  • 5/27/2018 Beginning SQL

    25/46

    Data Manipulation (DML)

    Insert- add rows to a table

    Update- update column values in a table's

    rows

    Delete- delete rows in a table

    Select - retrieve rows from one or more

    tables

    25

  • 5/27/2018 Beginning SQL

    26/46

    Insert

    Insert = add a new row (record)

    Works just like HLL verbs

    Example: Add a couple of employees to our

    table in the human resources library

    26

  • 5/27/2018 Beginning SQL

    27/46

    Insert

    INSERT INTOHR/EMPLOYEE

    (FIRST_NAME, LAST_NAME, EMPLOYEE_ID,

    DEPARTMENT, TITLE, HIRE_DATE)

    VALUES ('Joe', 'Jones', 4793, 522, Hotshot Programmer', '1998-01-16')

    INSERT INTOHR/EMPLOYEE

    VALUES ('Jane', Smith', 3290, 712, Psychic Business Planner', '1999-12-01')

    27

  • 5/27/2018 Beginning SQL

    28/46

    Update

    Update = change data in existing row

    Works just like HLL verbs

    Example: Give a 20% raise to one our star

    employees

    UPDATEHR/EMPLOYEESETSalary = Salary * 1.2

    WHERE Employee_id = 5228

    28

  • 5/27/2018 Beginning SQL

    29/46

    Delete

    Delete = Remove one or more rows

    Example: Fire the human resources

    department

    DELETEFROMHR/EMPLOYEE

    WHERE Department = 108

    29

  • 5/27/2018 Beginning SQL

    30/46

    Select

    Select statement is the most complex and

    powerful SQL statement

    If you know how to write good selectstatements you are well on your way to

    mastering the language

    30

  • 5/27/2018 Beginning SQL

    31/46

    Select

    SELECT statement overview:

    Select column(s)From table(s) or view(s)

    Where selection criteria

    Group Bygrouping columns

    Having selection criteria for groups

    Order Bysort order for result rows

    31

  • 5/27/2018 Beginning SQL

    32/46

    Select - example 1

    Selects all columns (designated by *)

    Selects data from the HR/EMPLOYEE table

    Select all rows

    SELECT*FROMHR/EMPLOYEE

    32

  • 5/27/2018 Beginning SQL

    33/46

    Select - example 2

    Selects only two columns

    Selects data from the HR/EMPLOYEE table

    Select only rows with EMPID *EQ 556

    SELECTLNAME, FNAME

    FROMHR/EMPLOYEE

    WHEREEMPID = 556

    33

  • 5/27/2018 Beginning SQL

    34/46

    Select - example 3

    Selects two columns and calculates a third

    called DISCPRICESelects data from the INVENTORY table

    Selects parts in a defined range

    SELECTShirtName, SKU,

    PRICE*.8 ASDISCPRICE

    FROM PRODLIB/INVENTORYWHERESYLE = HAWIAN ORCOLOR = PINK

    34

  • 5/27/2018 Beginning SQL

    35/46

    Select - example 4SELECT TERRITORY, SUM(SaleAmt),

    AVG(SaleAmt), COUNT(*)

    FROM PRODLIB/SALES

    WHERE COUNTRY = USAGROUP BYTERRITORY

    HAVING AVG(SaleAmt) > 10000.0

    ORDER BY2 DESC

    Rank sales in largest to smallest order summarized

    by territory. Only look at sales in the United States

    that average more than $10000.35

  • 5/27/2018 Beginning SQL

    36/46

    Useful functions

    Function Description

    DIGITS(expression) Convert a numeric value to a character

    string so it can be taken apart

    DECIMAL(expression, precision, scale) Convert an expression to a packed decimal

    number with a specific scale and precision

    STRIP(string, type, character) Removes leading or trailing charactersfrom a string. Type can be B (both), L

    (leading), or T (trailing). If you use

    STRIP(string) both leading and trailing

    blanks are removed.

    LTRIM(string)

    RTRIM(string)

    Trim leading blanks from string

    Trim trailing blanks from string

    SUBSTR(string, start-position, length) Extracts part of a string beginning at thestart position and going for length

    characters.

    UPPER(string) Converts the string to UPPER CASE.

    36

  • 5/27/2018 Beginning SQL

    37/46

    More useful functions

    Function Description

    MONTH(date or timestamp) Returns the month of the year (1-12)

    CURDATE()

    CURTIME()

    Returns todays date

    Returns the current time

    DAYOFWEEK(date or timestamp)QUARTER(date or timestamp)

    WEEK(date or timestamp)

    Returns a value from 1-7 representing theday

    Returns 1-4 based on the years quarter

    Returns 1-53 based on the week of the year

    MIN(expression1, expression2,)

    MAX(expression1, expression2,)

    Return the minimum numeric value in list

    Return the maximum numeric value in list

    TANH(expression) Return the hyperbolic tangent of

    expression (OK not really that useful!)

    37

  • 5/27/2018 Beginning SQL

    38/46

    Embedded SQL

    Combines the power of SQL with HLLs

    like RPG, COBOL, or C

    All of the benefits of HLLs such asperformance, complex logic, and control

    over data manipulation.with SQLs

    capabilities for set at a time processing anddynamic selection

    38

  • 5/27/2018 Beginning SQL

    39/46

    Embedded SQL

    The following statement is an example of

    what an embedded statement looks like:

    SELECT fname, lname, address

    FROM employee

    WHERE empid = :INPUTID

    INPUTID is a host variable

    39

  • 5/27/2018 Beginning SQL

    40/46

    Embedded SQL

    Embedded SQL programs are pre-compiled

    and then compiled again

    CRTSQLRPGI, CRTSQLCBLI

    Pre-compiler identifies SQL with special

    tags to indicate start and end of SQL

    statement

    40

  • 5/27/2018 Beginning SQL

    41/46

    Source file

    SQL pre-compiler

    Temporary

    Source file

    HLL compiler Module or

    Program

    41

  • 5/27/2018 Beginning SQL

    42/46

    Embedded SQL

    C/Exec SQL

    C+ Update Employee

    C+ Set lname = :NewLN -- assign new last name

    C+ Where empId = :EmployIdC/End-Exec

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

    Exec SQL

    Update Employee

    Set lname = :NewLNWhere empId = :EmployId

    End-Exec

    RPG

    COBOL

    42

  • 5/27/2018 Beginning SQL

    43/46

    Tips

    To start learning SQL use ISQL

    or Operations Navigator

    Create a sample collection and

    tables

    Add, change, and delete data

    Try different select statements

    and functions to get a feel for

    the power of SQL

    Read and try examples listed in

    the book and internet resourcesin this presentation

    Create tables with short and

    long names

    Put related SQL objects in the

    same collection

    If selecting a small amount of

    data, create an index over thecolumns that most uniquely

    identify the data

    Be careful with UPDATE and

    DELETE statements without a

    WHERE clause

    Use the AS clause to give

    calculations understandable

    names

    43

  • 5/27/2018 Beginning SQL

    44/46

    Other resources

    Database Design and Programming for DB2/400 -book by Paul

    Conte

    SQL for Smarties- book by Joe Celko

    SQL Tutorial- www.as400network.com

    AS/400 DB2 web site at http://www.as400.ibm.com/db2/db2main.htm

    Publications at http://publib.boulder.ibm.com/pubs/html/as400/

    Our web site at http://www.centerfieldtechnology.com

    44

  • 5/27/2018 Beginning SQL

    45/46

    Summary

    SQL is becoming increasingly important for

    many reasons

    Basic DDL is very similar to DDS

    Power and flexibility come with the DML

    statements -- in particular SELECT

    There are many resources to help take youto the next level of understanding

  • 5/27/2018 Beginning SQL

    46/46

    I hear and forget.I see and remember.

    I do and I understand.

    Kung Futse

    551 B.C.