beginning sql

46
SQL Jumpstart Mark Holm Mark Holm Centerfield Technology Centerfield Technology

Upload: tess98

Post on 14-Dec-2014

333 views

Category:

Documents


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Beginning SQL

SQLJumpstart

Mark HolmMark Holm

Centerfield TechnologyCenterfield Technology

Page 2: Beginning SQL

Goals

Get you started with SQLGet you started with SQL Show how SQL works with an existing Show how SQL works with an existing

environmentenvironment Lay the groundwork for learning moreLay the groundwork for learning more

2

Page 3: Beginning SQL

Notes

V4R3 and higher syntax used in examplesV4R3 and higher syntax used in examples Examples show only a small subset of what Examples show only a small subset of what

can be done!can be done!

3

Page 4: Beginning SQL

Agenda

Explain why SQL is importantExplain why SQL is important Compare SQL with traditional approachesCompare SQL with traditional approaches Data definition statementsData definition statements Selecting dataSelecting data Changing dataChanging data Using SQL day to dayUsing SQL day to day

4

Page 5: Beginning SQL

Why SQL? Simplifies cross platform developmentSimplifies cross platform development SQL generation can be automatedSQL generation can be automated Allows quick and flexible access to dataAllows quick and flexible access to data Operates on “sets” of data -> powerfulOperates on “sets” of data -> powerful Official industry standard used by pervasive APIs & Official industry standard used by pervasive APIs &

productsproducts– ODBC/JDBCODBC/JDBC

– Most query tools Most query tools

Can perform Can perform betterbetter than traditional methods! than traditional methods!

5

Page 6: Beginning SQL

Why SQL? Business IntelligenceBusiness Intelligence

– Query toolsQuery tools– Data manipulation & (some) data cleanupData manipulation & (some) data cleanup

Web sites & internet applicationsWeb sites & internet applications– Net.DataNet.Data– JDBCJDBC

ERP applicationsERP applications– SSA eBPCSSSA eBPCS– JDE One WorldJDE One World– Mapics XAMapics XA

6

Page 7: Beginning SQL

Tools

Interactive SQL (STRSQL)Interactive SQL (STRSQL) Run SQL statement (RUNSQLSTM)Run SQL statement (RUNSQLSTM) Operations NavigatorOperations Navigator Query tools (ODBC)Query tools (ODBC) And many others…..And many others…..

7

Page 8: Beginning SQL

Basic statements

Create Collection = CRTLIBCreate Collection = CRTLIB Create Table = CRTPFCreate Table = CRTPF Create View = CRTLF (no key)Create View = CRTLF (no key) Create Index = CRTLF (key)Create Index = CRTLF (key) Insert, Update, Delete = add, change, and Insert, Update, Delete = add, change, and

remove recordsremove records Select = select records & columns to readSelect = select records & columns to read

8

Page 9: Beginning SQL

Data definition (DDL)

Data definition statements create objectsData definition statements create objects– Collections (libraries)Collections (libraries)– Tables (physical files)Tables (physical files)– Views (non-keyed logical files)Views (non-keyed logical files)– Indexes (keyed logical files)Indexes (keyed logical files)

9

Page 10: Beginning SQL

Create collection

Create collection = Create libraryCreate collection = Create library Example: Example: CREATE COLLECTION CREATE COLLECTION HRHR Objects created:Objects created:

Library named ‘Library named ‘HRHR’’ Journal & journal receiverJournal & journal receiver Catalogs (e.g. SYSTABLES)Catalogs (e.g. SYSTABLES)

10

Page 11: Beginning SQL

DSPLIB of a newly created COLLECTION

Page 12: Beginning SQL

Create Table

Create table = Create physical file (CRTPF)Create table = Create physical file (CRTPF) Objects created, etc.:Objects created, etc.:

Physical filePhysical file File automatically journaled to QSQJRNFile automatically journaled to QSQJRN

Example: Create a table to hold employee Example: Create a table to hold employee informationinformation

12

Page 13: Beginning SQL

Create table

CREATE TABLE HR/EMPLOYEE

(FIRST_NAME FOR COLUMN FNAME 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 DEFAULT 0,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

Page 14: Beginning SQL

Tables vs. Physicals

TablesTables– Dirty data Dirty data can’tcan’t be be

insertedinserted

– Marked as a ‘table’Marked as a ‘table’

– Maximum 1 memberMaximum 1 member

– No maximum sizeNo maximum size

– Default to reuse Default to reuse deleted rowsdeleted rows

– Table is automatically Table is automatically journaled (collection)journaled (collection)

Physical filesPhysical files– Dirty data Dirty data cancan be be

insertedinserted

– Not an SQL objectNot an SQL object

– No limit on membersNo limit on members

– Default is to cap sizeDefault is to cap size

– Default to not reuse Default to not reuse deleted recordsdeleted records

– File is not automatically File is not automatically journaledjournaled

14

Page 15: Beginning SQL

Prompt for CREATE TABLE in Interactive SQL

Page 16: Beginning SQL

Create View

Create View = Create logical file (CRTLF)Create View = Create logical file (CRTLF) Objects created:Objects created:

““Logical file”Logical file” No keyed access pathNo keyed access path

Example: View to format an employees first Example: View to format an employees first & last name and identify employees hired & last name and identify employees hired less than 2 years prior to todayless than 2 years prior to today

16

Page 17: Beginning SQL

Create View

CREATE VIEW HR/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

Page 18: Beginning SQL

DSPFD of a newly created VIEW

Page 19: Beginning SQL

View uses

Subset columns to users or applicationsSubset columns to users or applications Create new columns for users or Create new columns for users or

applicationsapplications Subset the rows returned (hide data)Subset the rows returned (hide data) Join tables togetherJoin tables together

19

Page 20: Beginning SQL

Views vs. Logical files

ViewView– Looks like logical fileLooks like logical file

– Never has an access Never has an access path (index)path (index)

– Powerful data Powerful data manipulationmanipulation

– Slower OPEN timeSlower OPEN time

– Views can reference Views can reference viewsviews

– One memberOne member

Logical FileLogical File– Is a logical fileIs a logical file

– Can be keyed or non-Can be keyed or non-keyed keyed

– Basic data Basic data manipulationmanipulation

– Faster OPEN timeFaster OPEN time

– Logical files can not Logical files can not reference LF’sreference LF’s

– Many membersMany members

20

Page 21: Beginning SQL

Create Index

Create Index = CRTLF (keyed logical)Create Index = CRTLF (keyed logical) Objects created:Objects created:

““Logical file”Logical file” Physical access path (index)Physical access path (index)

Created to improve performance -- not for Created to improve performance -- not for functionfunction

Example: Create an index over the Example: Create an index over the employee identifieremployee identifier

21

Page 22: Beginning SQL

Create Index

CREATE UNIQUE INDEX HR/EMPIDIX

ON HR/EMPLOYEE (EMPLOYEE_ID ASC)

22

Page 23: Beginning SQL

Indexes vs. Keyed logical files

IndexIndex– Looks like logical fileLooks like logical file

– Powerful data Powerful data manipulationmanipulation

– Not usable as fileNot usable as file

– One memberOne member

Logical fileLogical file– Is a logical fileIs a logical file

– Basic data Basic data manipulationmanipulation

– Like a normal fileLike a normal file

– Many membersMany members

23

Page 24: Beginning SQL

Deleting objects

Done with a DROP statementDone with a DROP statement– DROP TABLEDROP TABLE– DROP VIEWDROP VIEW– DROP INDEXDROP INDEX

By default these statements drop dependent By default these statements drop dependent objects unlike CL commands (e.g. you can’t objects unlike CL commands (e.g. you can’t delete a PF via DLTF if there are dependent delete a PF via DLTF if there are dependent logical files)logical files)

24

Page 25: Beginning SQL

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

Page 26: Beginning SQL

Insert

Insert = add a new row (record)Insert = add a new row (record) Works just like HLL verbsWorks just like HLL verbs Example: Add a couple of employees to our Example: Add a couple of employees to our

table in the human resources librarytable in the human resources library

26

Page 27: Beginning SQL

Insert

INSERT INTO HR/EMPLOYEE(FIRST_NAME, LAST_NAME, EMPLOYEE_ID,

DEPARTMENT, TITLE, HIRE_DATE)

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

INSERT INTO HR/EMPLOYEE

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

27

Page 28: Beginning SQL

Update

Update = change data in existing rowUpdate = change data in existing row Works just like HLL verbsWorks just like HLL verbs Example: Give a 20% raise to one our star Example: Give a 20% raise to one our star

employeesemployees

UPDATE HR/EMPLOYEE

SET Salary = Salary * 1.2

WHERE Employee_id = 5228

28

Page 29: Beginning SQL

Delete

Delete = Remove one or more rowsDelete = Remove one or more rows Example: Fire the human resources Example: Fire the human resources

departmentdepartment

DELETE FROM HR/EMPLOYEE

WHERE Department = 108

29

Page 30: Beginning SQL

Select

Select statement is the most complex and Select statement is the most complex and powerful SQL statementpowerful SQL statement

If you know how to write good select If you know how to write good select statements you are well on your way to statements you are well on your way to mastering the languagemastering the language

30

Page 31: Beginning SQL

Select

SELECT statement overview:SELECT statement overview:

Select column(s) From table(s) or view(s) Where selection criteria Group By grouping columns Having selection criteria for groups Order By sort order for result rows

31

Page 32: Beginning SQL

Select - example 1

– Selects all columns (designated by ‘*’)Selects all columns (designated by ‘*’)– Selects data from the HR/EMPLOYEE tableSelects data from the HR/EMPLOYEE table– Select all rowsSelect all rows

SELECT * FROM HR/EMPLOYEE

32

Page 33: Beginning SQL

Select - example 2

– Selects only two columnsSelects only two columns– Selects data from the HR/EMPLOYEE tableSelects data from the HR/EMPLOYEE table– Select only rows with EMPID *EQ 556Select only rows with EMPID *EQ 556

SELECT LNAME, FNAME FROM HR/EMPLOYEE WHERE EMPID = 556

33

Page 34: Beginning SQL

Select - example 3

– Selects two columns and calculates a third Selects two columns and calculates a third called DISCPRICEcalled DISCPRICE

– Selects data from the INVENTORY tableSelects data from the INVENTORY table– Selects parts in a defined rangeSelects parts in a defined range

SELECT ShirtName, SKU, PRICE*.8 AS DISCPRICE FROM PRODLIB/INVENTORY WHERE SYLE = ‘HAWIAN’ OR COLOR = ‘PINK’

34

Page 35: Beginning SQL

Select - example 4SELECT TERRITORY, SUM(SaleAmt), AVG(SaleAmt), COUNT(*) FROM PRODLIB/SALES WHERE COUNTRY = ‘USA’ GROUP BY TERRITORY HAVING AVG(SaleAmt) > 10000.0 ORDER BY 2 DESC

– Rank sales in largest to smallest order summarized by territory. Rank sales in largest to smallest order summarized by territory. Only look at sales in the United States that average more than Only look at sales in the United States that average more than $10000.$10000.

35

Page 36: Beginning SQL

Useful functionsFunction Description

DIGITS(expression) Convert a numeric value to a characterstring so it can be taken apart

DECIMAL(expression, precision, scale) Convert an expression to a packed decimalnumber 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 useSTRIP(string) both leading and trailingblanks are removed.

LTRIM(string)RTRIM(string)

Trim leading blanks from stringTrim 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

Page 37: Beginning SQL

More useful functionsFunction Description

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

CURDATE()CURTIME()

Returns today’s dateReturns the current time

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

Returns a value from 1-7 representing thedayReturns 1-4 based on the year’s quarterReturns 1-53 based on the week of the year

MIN(expression1, expression2,…)MAX(expression1, expression2,…)

Return the minimum numeric value in listReturn the maximum numeric value in list

TANH(expression) Return the hyperbolic tangent ofexpression (OK not really that useful!)

37

Page 38: Beginning SQL

Embedded SQL

Combines the power of SQL with HLL’s Combines the power of SQL with HLL’s like RPG, COBOL, or Clike RPG, COBOL, or C

All of the benefits of HLL’s such as All of the benefits of HLL’s such as performance, complex logic, and control performance, complex logic, and control over data manipulation….with SQL’s over data manipulation….with SQL’s capabilities for set at a time processing and capabilities for set at a time processing and dynamic selection dynamic selection

38

Page 39: Beginning SQL

Embedded SQL

The following statement is an example of The following statement is an example of what an embedded statement looks like:what an embedded statement looks like:

SELECT fname, lname, addressSELECT fname, lname, address

FROM employee FROM employee

WHERE empid = :INPUTIDWHERE empid = :INPUTID INPUTID is a ‘host variable’INPUTID is a ‘host variable’

39

Page 40: Beginning SQL

Embedded SQL

Embedded SQL programs are pre-compiled Embedded SQL programs are pre-compiled and then compiled againand then compiled again

CRTSQLRPGI, CRTSQLCBLICRTSQLRPGI, CRTSQLCBLI Pre-compiler identifies SQL with special Pre-compiler identifies SQL with special

tags to indicate start and end of SQL tags to indicate start and end of SQL statementstatement

40

Page 41: Beginning SQL

Source file

SQL pre-compiler

Temporary Source file

HLL compiler Module or Program

41

Page 42: Beginning SQL

Embedded SQL

C/Exec SQLC+ Update Employee C+ Set lname = :NewLN -- assign new last name C+ Where empId = :EmployId C/End-Exec-----------------------------------------------------Exec SQL Update Employee Set lname = :NewLN Where empId = :EmployId End-Exec

RPG

COBOL

42

Page 43: Beginning SQL

Tips

To start learning SQL use ISQL To start learning SQL use ISQL or Operations Navigatoror Operations Navigator– Create a sample collection and Create a sample collection and

tablestables

– Add, change, and delete dataAdd, change, and delete data

– Try different select statements Try different select statements and functions to get a feel for and functions to get a feel for the power of SQLthe power of SQL

Read and try examples listed in Read and try examples listed in the book and internet resources the book and internet resources in this presentationin this presentation

Create tables with short and Create tables with short and long nameslong names

Put related SQL objects in the Put related SQL objects in the same collectionsame collection

If selecting a small amount of If selecting a small amount of data, create an index over the data, create an index over the columns that most uniquely columns that most uniquely identify the dataidentify the data

Be careful with UPDATE and Be careful with UPDATE and DELETE statements without a DELETE statements without a WHERE clauseWHERE clause

Use the AS clause to give Use the AS clause to give calculations understandable calculations understandable namesnames

43

Page 44: Beginning SQL

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

Page 45: Beginning SQL

Summary

SQL is becoming increasingly important for SQL is becoming increasingly important for many reasonsmany reasons

Basic DDL is very similar to DDSBasic DDL is very similar to DDS Power and flexibility come with the DML Power and flexibility come with the DML

statements -- in particular SELECTstatements -- in particular SELECT There are many resources to help take you There are many resources to help take you

to the next level of understanding to the next level of understanding

Page 46: Beginning SQL

I hear and forget.I hear and forget.

I see and remember.I see and remember.

I do and I understand.I do and I understand.

Kung FutseKung Futse

551 B.C.551 B.C.