Thirty SQL Tips in Sixty Minutes Ted Holt

  • Slides: 44
Download presentation
Thirty SQL Tips in Sixty Minutes Ted Holt Senior Software Developer Profound Logic Software

Thirty SQL Tips in Sixty Minutes Ted Holt Senior Software Developer Profound Logic Software Starkville, Mississippi Senior Technical Editor Four Hundred Guru www. itjungle. com

1: Sort by Column Numbers You can use column numbers to indicate sort columns

1: Sort by Column Numbers You can use column numbers to indicate sort columns in the ORDER BY clause. This is especially helpful when sorting on calculated columns. select account, ((curyear - prevyear) * 0. 5) from saleshist order by 2, 1 http: //publib. boulder. ibm. com/infocenter/iseries/v 5 r 4/topic/db 2/rbafzmstintsel. htm

2: Non-alphabetic Sorting Technique 1 Suppose you want data about Tennessee to sort ahead

2: Non-alphabetic Sorting Technique 1 Suppose you want data about Tennessee to sort ahead of all other states. Use a CASE construct in the ORDER BY clause. select * from sales order by case when state = ‘TN' then 0 else 1 end, state http: //www. itjungle. com/fhg 100604 -story 02. html

3: Non-alphabetic Sorting Technique 2 The following ORDER BY clause causes data for the

3: Non-alphabetic Sorting Technique 2 The following ORDER BY clause causes data for the Shipping department to sort ahead of data for the Receiving department. select * from trans order by locate(dept, 'ACCOUNTING SHIPPING RECEIVING ') http: //www. itjungle. com/fhg 091306 -story 02. html

4: Two Ways to Ignore Case (1) Use national language support to ignore case

4: Two Ways to Ignore Case (1) Use national language support to ignore case in sorts and comparison. exec sql set option srtseq=*langidshr (2) Use case-conversion functions. select * from Customers order by upper(Name) http: //www. itjungle. com/mgo 111403 -story 01. html

5: Access in Arrival Sequence Use the RRN function to access a file by

5: Access in Arrival Sequence Use the RRN function to access a file by relative record number. select * from gltrans as s where rrn(s) between 301 and 325 http: //www. itjungle. com/fhg 072705 -story 02. html http: //www. itjungle. com/fhg 022206 -story 02. html

The RRN function can be very useful for one-time maintenance tasks. I don’t recommend

The RRN function can be very useful for one-time maintenance tasks. I don’t recommend using it for regular processing.

6: Access Multi-member Files SQL does not support multi-member database files. To access a

6: Access Multi-member Files SQL does not support multi-member database files. To access a member other than the first, create an alias. create alias mylib/pay 2014 for mylib/payhist(year 2014) select * from mylib/pay 2014 http: //www. itjungle. com/guruo/mgo 021302 -story 02. html

7: Create or Replace Use CREATE OR REPLACE to avoid having to drop an

7: Create or Replace Use CREATE OR REPLACE to avoid having to drop an object before recreating it. create or replace view Names as select Name from people http: //www-01. ibm. com/support/knowledgecenter/ssw_ibm_i_72/sqlp/rbafycrtrepl. htm

8: Create or Replace Table If your release of SQL does not support CREATE

8: Create or Replace Table If your release of SQL does not support CREATE OR REPLACE TABLE, you can fake it. begin declare continue handler for sqlexception begin end; drop table customers; end; create table customers. . . http: //www. itjungle. com/fhg 012015 -story 01. html http: //www-01. ibm. com/support/knowledgecenter/ssw_ibm_i_71/sqlp/rbafyreplacetable. htm

9: Clear a Table Finally! SQL can clear a physical file. truncate table daily

9: Clear a Table Finally! SQL can clear a physical file. truncate table daily is equivalent to CLRPFM DAILY http: //www. itjungle. com/fhg 062514 -story 01. html

10: Create Temporary. Tables Use the DECLARE GLOBAL TEMPORARY TABLE command to create scratch

10: Create Temporary. Tables Use the DECLARE GLOBAL TEMPORARY TABLE command to create scratch tables in the QTEMP library. declare global temporary table t 1 as (select state, sum(baldue) as balancedue from qcustcdt group by state) with data http: //publib. boulder. ibm. com/infocenter/iseries/v 5 r 4/topic/d b 2/rbafzmstdgtt. htm

11: Keep Temporary Data The system clears temporary tables on commit unless you tell

11: Keep Temporary Data The system clears temporary tables on commit unless you tell it not to. exec sql declare global temporary table Summary (state char(2), Sum. Amount dec(9, 2)) on commit preserve rows http: //www-01. ibm. com/support/knowledgecenter/ssw_ibm_i_72/db 2/rbafzdgtt. htm

12: Avoid Temporary Tables If possible, use a view or common table expression instead

12: Avoid Temporary Tables If possible, use a view or common table expression instead of a global temporary table. declare global temporary table STotal as (select state, sum(baldue) as Due from qiws/qcustcdt group by state) with data with replace http: //www. itjungle. com/fhg 060215 -story 02. html

The same query with a common table expression. with Stotal as (select state, sum(baldue)

The same query with a common table expression. with Stotal as (select state, sum(baldue) as Due from qiws/qcustcdt group by state) select a. *, b. * from qiws/qcustcdt as a join Stotal as b on a. state = b. state

13: Insert Multiple Rows Insert more than one row at a time using the

13: Insert Multiple Rows Insert more than one row at a time using the VALUES clause of an INSERT statement. Separate rows with commas. INSERT INTO PLANTS VALUES (1, 'Lost Angeles'), (2, 'New Yolk') http: //www. itjungle. com/fhg 010406 -story 02. html

14: Update one Table from Another Use the MERGE statement to update one table

14: Update one Table from Another Use the MERGE statement to update one table with data in another table. merge into items as tgt using (select Item. Number, Price from New. Prices) as src on tgt. Item. Number = src. Item. Number when matched then update set tgt. Price = src. Price http: //www. itjungle. com/fhg 040313 -story 02. html

Item number DH-250 DH-300 TJ-117 WC-321 WI-101 Item number DH-250 DH-300 Description Doo-hickey, left-hand

Item number DH-250 DH-300 TJ-117 WC-321 WI-101 Item number DH-250 DH-300 Description Doo-hickey, left-hand Doo-hickey, right-hand Thimamajig, size 6 Watchmacallit Widget, 4 -inch Cost 2. 00 1. 50 4. 50 1. 00 Price 3. 00 1. 75 3. 00 7. 00 1. 75 Before Price 3. 50 2. 00 merge into items as tgt using (select Item. Number, Price from New. Prices) as src on tgt. Item. Number = src. Item. Number when matched then update set tgt. Price = src. Price Item number DH-250 DH-300 TJ-117 WC-321 WI-101 Description Doo-hickey, left-hand Doo-hickey, right-hand Thimamajig, size 6 Watchmacallit Widget, 4 -inch Cost 2. 00 1. 50 4. 50 1. 00 Price 3. 50 2. 00 3. 00 7. 00 1. 75 After

15: Use MERGE to “Upsert” Update data where it exists, add it where it

15: Use MERGE to “Upsert” Update data where it exists, add it where it doesn’t. merge into items as tgt using (select * from Item. Update) as src on tgt. Item. Number = src. Item. Number when matched then update set tgt. Description = src. Description, tgt. Cost = src. Cost, tgt. Price = src. Price when not matched then insert values (src. Item. Number, src. Description, src. Cost, src. Price) http: //www. itjungle. com/fhg 012715 -story 02. html

Item number DH-250 DH-300 TJ-117 WC-321 WI-101 Description Doo-hickey, left-hand Doo-hickey, right-hand Thimamajig, size

Item number DH-250 DH-300 TJ-117 WC-321 WI-101 Description Doo-hickey, left-hand Doo-hickey, right-hand Thimamajig, size 6 Watchmacallit Widget, 4 -inch Item number Description DH-100 Doo-hickey, universal WI-101 Widget, 4 -inch Cost 2. 00 1. 50 4. 50 1. 00 Price 3. 00 1. 75 3. 00 7. 00 1. 75 Cost 2. 50 1. 50 Price 3. 00 2. 75 Before merge into items as tgt using (select * from Item. Update) as src on tgt. Item. Number = src. Item. Number when matched then update set tgt. Description = src. Description, tgt. Cost = src. Cost, tgt. Price = src. Price when not matched then insert values (src. Item. Number, src. Description, src. Cost, src. Price) Item number DH-100 DH-250 DH-300 TJ-117 WC-321 WI-101 Description Doo-hickey, universal Doo-hickey, left-hand Doo-hickey, right-hand Thimamajig, size 6 Watchmacallit Widget, 4 -inch Cost 2. 50 2. 00 1. 50 4. 50 1. 50 Price 3. 00 1. 75 3. 00 7. 00 2. 75 After

16: Row Value Expressions Simplify row selection by comparing rows of values, rather than

16: Row Value Expressions Simplify row selection by comparing rows of values, rather than single values, to one another. select * From Project Where (PROJNO, ACTNO) = ('AD 3100', '10')

Row value expressions are also great for joins. SELECT FROM left on * cacmst

Row value expressions are also great for joins. SELECT FROM left on * cacmst a outer join cinvp b (a. cmlocn, a. cmcont) = (b. silocn, b. sicont) outer join trudtp c (b. silocn, b. sicont, b. siitem, b. siseqn, b. silino) = (c. tulocn, c. tucont, c. tuitem, c. tuseqn, c. tulino) ORDER BY a. cmlocn, a. cmcont http: //www. itjungle. com/fhg 021015 -story 02. html http: //www. itjungle. com/fhg 100913 -story 02. html http: //www. itjungle. com/fhg 041410 -story 02. html http: //www. itjungle. com/fhg 041206 -story 01. html

17: Null Does Not Equal Null (and null does not equal null) If you

17: Null Does Not Equal Null (and null does not equal null) If you want to compare null to null, use IS [NOT] DISTINCT FROM. SELECT * FROM Some. Table WHERE Some. Field IS NOT DISTINCT FROM Another. Field http: //www. itjungle. com/fhg 091405 -story 01. html

18: Wildcards in RPG The %SCAN BIF does not support wild cards, but SQL

18: Wildcards in RPG The %SCAN BIF does not support wild cards, but SQL does. dcl-s Matched char(1); exec sql set : Matched = case when : in. Source like : in. Pattern then '1' else '0' end; http: //www. itjungle. com/fhg 120314 -story 01. html http: //www. itjungle. com/fhg 011205 -story 02. html

If RPG doesn't have a BIF you need, use an SQL function. exec sql

If RPG doesn't have a BIF you need, use an SQL function. exec sql values hex(: Class) into : Token http: //www. itjungle. com/mgo 080803 -story 02. html http: //www. itjungle. com/fhg 012804 -story 04. html

19: Wildcards on Steroids Regular expressions allow more specific searches than wildcards do. select

19: Wildcards on Steroids Regular expressions allow more specific searches than wildcards do. select * from people as p where regexp_like(p. street, '^1d{2}. *Main') http: //www. itjungle. com/fhg 051915 -story 01. html

20: Remove Extra Spaces in a String Replace two or more blanks with only

20: Remove Extra Spaces in a String Replace two or more blanks with only one. (E. g. , "Joe Smith" becomes "Joe Smith". ) update mydata set name = replace(name, ' ', '<>'), '><', ''), '<>', ' ') http: //mullinsconsulting. com/bp 11. htm http: //www. itjungle. com/fhg 101106 -story 02. html

Assume NAME is “Joe Original string Last REPLACE Middle REPLACE First REPLACE Smith”. (There

Assume NAME is “Joe Original string Last REPLACE Middle REPLACE First REPLACE Smith”. (There are 12 blanks after “Joe”. ) Joe Smith Joe<><><><><><>Smith Joe<>Smith Joe Smith

21: Easily Process Non-date Dates Use the FMTDATE function to convert numeric or alpha

21: Easily Process Non-date Dates Use the FMTDATE function to convert numeric or alpha fields to manageable formats. select fmtdate(Due. Date, ‘cymd’, ’iso-’), . . . from Mfg. Orders http: //www. itjungle. com/fhg 050515 -story 02. html http: //www. itjungle. com/fhg 120209 -story 02. html http: //www. itjungle. com/fhg 081909 -story 02. html

Instead of this: substr( digits(dec(19000000+crdate, 8, 0)), 5, 2 ) || '/' || substr(

Instead of this: substr( digits(dec(19000000+crdate, 8, 0)), 5, 2 ) || '/' || substr( digits(dec(19000000+crdate, 8, 0)), 7, 2 ) || '/' || substr( digits(dec(19000000+crdate, 8, 0)), 1, 4 ) Do this: fmtdate(CRDATE, 'CYMD', 'MDYY/')

22: Unusual Rounding You don't have to round to the nearest power of ten.

22: Unusual Rounding You don't have to round to the nearest power of ten. You can round to other whole numbers, or even to fractions. select dec( round(price * 4, 0)/4, 11, 2) as Nearest_Qtr from Price. Book http: //www. itjungle. com/fhg 092105 -story 02. html

Multiply by the reciprocal of the number to which you are rounding. Divide by

Multiply by the reciprocal of the number to which you are rounding. Divide by the reciprocal. In this example, multiply by four to round to the nearest one-fourth. Then divide by four. Example: Price ======= 1. 00 1. 12 1. 13 1. 25 1. 49 1. 51 Rounded ==== 1. 00 1. 25 1. 50

23: How Many Rows Did I Fetch? Use the SQLER 3 or SQLERR(3) field

23: How Many Rows Did I Fetch? Use the SQLER 3 or SQLERR(3) field to see how many rows were affected by the previous I/O operation (i. e. , fetch, insert, update, delete). exec sql delete from Price. Book where Prc. Flag = 'X'; if SQLER 3 > *zero; http: //www. itjungle. com/fhg 020404 -story 02. html

24: Load Data into IFS Files Use Qshell's db 2 utility to place data

24: Load Data into IFS Files Use Qshell's db 2 utility to place data into an IFS file. db 2 "SELECT char(CUSNUM) || ', ’ || LSTNAM || ', ’ || char(baldue) from qiws. qcustcdt" | sed -n '/, /p' >> custdata. csv http: //www. itjungle. com/fhg 020205 -story 02. html

25: Generate DDL Don’t convert physical files to DDL by hand! ● ● System

25: Generate DDL Don’t convert physical files to DDL by hand! ● ● System i Navigator QSQGNDDL API QSYS 2. GENERATE_SQL stored procedure Third-party utilities http: //www. itjungle. com/mgo 060502 -story 01. html http: //www. itjungle. com/mgo 061202 -story 02. html http: //www. itjungle. com/fhg 111214 -printer 01. html http: //www. epi-software. com/convert_dds_to_sql. html

26: Use an SQL Formatter An SQL formatter can make your code easier to

26: Use an SQL Formatter An SQL formatter can make your code easier to read. ● ● Set case of keywords, column names, functions, variables etc. Align similar parts of a statement. http: //www. dpriver. com/pp/sqlformat. htm (Google “sql formatter” for more. )

An Inspirational Thought from Ashley Phix 28. 35 grams of prevention is worth 0.

An Inspirational Thought from Ashley Phix 28. 35 grams of prevention is worth 0. 4536 kilograms of cure. 6/9/2021

27: Rule of Thumb 1 If you use GROUP BY, you probably want ORDER

27: Rule of Thumb 1 If you use GROUP BY, you probably want ORDER BY, too. SELECT FROM GROUP ORDER state, COUNT(*), SUM(baldue) qiws. qcustcdt by state BY state http: //www. itjungle. com/guruo 112101. html

28: Rule of Thumb 2 Use a left outer join unless you have a

28: Rule of Thumb 2 Use a left outer join unless you have a reason to use some other type. SELECT a. cusnum, a. lstnam, a. init, a. city, b. statename FROM qcustcdt AS a LEFT JOIN states AS b ON a. state = b. abbr

29: Rule of Thumb 3 Use UNION ALL, not UNION, by default. SELECT Customer,

29: Rule of Thumb 3 Use UNION ALL, not UNION, by default. SELECT Customer, Item, Ship. Qty FROM Curr. Year UNION ALL SELECT Customer, Item, Ship. Qty FROM Prev. Year http: //www. itjungle. com/fhg 092607 -story 01. html

30: Rule of Thumb 4 Use correlation names to qualify, even when they’re not

30: Rule of Thumb 4 Use correlation names to qualify, even when they’re not required. select c. cusnum, c. lstnam, c. city, c. state, coalesce(s. name, ' ') from qcustcdt as c left join states as s on c. state = s. abbr

● ● Improves readability. Helps avoid common errors. http: //www. itjungle. com/fhg 102407 -story

● ● Improves readability. Helps avoid common errors. http: //www. itjungle. com/fhg 102407 -story 01. html http: //www. itjungle. com/fhg 031208 -story 02. html http: //www. itjungle. com/fhg 091515 -story 02. html

31: Remember Your Priorities select * from life where people > things

31: Remember Your Priorities select * from life where people > things