Consulting Personal Attention, Expert Assistance 1
Writing Better SQL Making your scripts more: Readable, Portable, & Easily Changed 2006 Alpha-G Consulting, LLC All rights reserved. 2
Before Spending your Time: This session does not teach SQL Any SQL you do learn would be incidental I will not be able to stop and explain the SQL This session may help you: Write clearer SQL Understand why that is worthwhile to do Modify existing SQL to work with a different platform (8.x will not run with a Sybase DB) Write new queries to require fewer changes 3
You can't beat SQL, but... It ain't called the SQL Bloodbank for nothin' Hard to read Harder to write Well, maybe that depends upon who wrote it... Won't work when you switch platforms 4
Don't Panic Use an Adequate Tool Use Formatting to your Advantage Use Commenting Effectively Use More Universal Syntax 5
SQL [Dis]Advantage Use something--anything!--else. The single greatest impediment to learning SQL (for Sybase users) is this lousy tool. A tool that helps rather than hinders you is a whole new world. 6
Characteristics of a Good Tool Syntax Highlighting If it doesn't have it, don't use it! Good options for Display of results Effective selection options Export of data Other things that are nice Direct data manipulation Parentheses matching Wizards 7
A Free Option: WinSQL Syntax Highlighting (No parentheses matching--drat! Excellent Display Options Good Selection Flexibility For-pay Options Database Browser Direct manipulation of browsed data Works with any Database with an ODBC Driver Slightly less capable Java version for non-windows www.synametrics.com 8
Another Free Option: jedit Only an Editor You can edit scripts with jedit Use a SQL query tool to actually run the queries Good SQL Syntax Highlighting (Including parentheses matching) Impressive Features and Dozens of Plug-ins Runs on any GUI platform Linux, Mac, Sun, &c. www.jedit.org 9
Formatting to your Advantage Align Things Consider Putting Delimiters at the Beginning Use More Space: Vertical & Horizontal Use Column Name Qualifiers Effectively Group and Arrange Conditions for Clarity 10
Align Things...? Not exactly what we had in mind... 11
Align Things: Better Note the indenting to illustrate the contents of the WHILE loop. 12
Align Things: Better Yet Alignment shows related operations Conditionals are clearer More spacing in expressions Simplified expressions Parentheses added for clarity 13
Alignment: My Preferred Style Lower case keywords are easier to read Slight indent of initializing select makes declaration & initialization parallel More vertical space Commented end of while 14
More On Indenting/Aligning What's wrong with this query? Hint: Does the alignment of the conditions in the where clause give you a clue? 15
Logic Error in where: : Fixed it! How much harder would it be to find that logic error if the conditions were not lined up? Or worse, were on a single line? 16
Isn't this All a Bit Obsessive? One writer's opinion on clarity: For these three abideth forever: clarity, beauty, and power. But the greatest of these is clarity--for clarity never faileth. Dr. John S. Harris, speaking of writing On why it's worth the trouble: It makes the neater job. Cash, in Faulkner's As I lay Dying 17
SQL is hard. Help yourself. Human perceptions are pattern-based Don't fight you own nature. You (or someone else) will, someday, have to: Read, Understand, and Modify your queries. The simplest way to help is good formatting Careful formatting helps you see and fix errors 18
Parentheses & Formatting Are these parentheses balanced? How long does it take to determine that? If they're not, you'll get a helpful error message, right? 19
Parentheses & Formatting How about now? Is it worth the trouble to format for clarity? 20
Qualifying Column Names Use correlation names on all column references You may be clear about it today, but what about a week from now? 21
Consistent Correlation Names Keep correlation names consistent within one script. Do yourself a favor--be consistent within a script. 22
Group & Arrange Conditions Put conditions for one table together. Align operators for columns when appropriate. Order in some kind of locical fashion. 23
Principles of Commenting Do more of it! Comment the END of BEGIN/END blocks Comment to address the question Why? Secret Hints: Formatting is a type of commenting With syntax-highlighting, comments more useful 24
Commenting: Not Enough What's all that mess being assigned to @pattern? At least we have a comment on the end of the while block... 25
Much Better Note use of both single line -- and multi-line /* */ comments. What is each step supposed to do? Why does the WHILE loop function appropriately? 26
Use More Universal Syntax You may be forced to change syntax with 8.x: Oracle DB2 Microsoft SQL Server Significant Changes in SQL Standard Newer syntax generally works in Sybase Older syntax does not work elsewhere DB table changes will force changes in many scripts Begin using newer syntax now 27
More Universal Syntax Joins Learn the up to date syntax and begin using it Moderately Simple Changes Eliminate Incorrect Double Quotes Use Optional Keywords No Equality Tests with Null Use to Concatenate Character Strings Complete group by Column Lists Eliminate Transact-SQL-only Characteristics 28
Use join keyword for Joins Rather than listing the tables in the from clause and the join criteria in the where clause, use join / on Likely to be the biggest change you'll need to make. Ironically, WinSQL doesn't (yet) highlight join and related keywords. 29 } }
A Multi-table Join Note that join appears once for each table being joined. Each join has an on clause that specifies the join conditions for that one table. I use parentheses around each on clause. No on clause? Dot product: all combinations. 30
Join with a where Clause The on clause specifies the conditions for joining the tables: the common keys. The where clause has selection restrictions. The two types of conditions serve slightly different purposes. 31
Join Summary For each table: join with on clause on clause contains key relationships where clause contains selection restrictions Types of joins: inner (default) left outer right outer full outer (almost never useful) 32
Eliminate most Double Quotes Use single quotes/ apostrophes for character values Use double quotes only for column aliases Use AS with column aliases 33
Use Optional Keywords Not necessarily optional on non Sybase/MS SQL platforms delete from insert into 34
No Equality Tests for null = null is not valid in a condition; use: is null / is not null Note that: set column = null Is valid; the meaning of = is different in the two contexts. 35
Use to Concatenate Chars Replace + for character concatenation with MS SQL Server: the new, standard operator may not work; possibly version dependent. 36
Recast joined update & delete Recast joined update or delete to subquery. Although this is a powerful and useful technique, it only works on Sybase or MS SQL Server. Example shows an update statement; the same approach must be used with delete statements. 37
Complete group by Column List Sybase allows selection of columns that are not in the group by column list. No other DB allows this. All non-function columns must be in the group by list. Functions: count, sum, max, & so on. 38
Data Type & Conversion Issues Most Data Types are Available tinyint is unique to Sybase/MS SQL Server but you can simulate it with a 3-digit numeric type bit type is different on Oracle; apparently not available on DB2 Oracle uses number rather than numeric/decimal Type Conversions convert becomes cast( expression AS type_name) Not always quite as flexible as convert Note that Sybase does not recognize cast 39
Other Problem Areas SELECT column1, column2 INTO table_name Use create table followed by insert statement. Cursors Slightly different wording in declaration and use. Local Variable Declaration and Use Variable naming different (no @ for Oracle/DB2) SET rather than SELECT for assigning value Flow of Control Language IF, WHILE, FOR, BREAK, end of blocks Context may be restricted: On DB2, must be in procedure/compound statement 40
Yet More Problem Areas Temporary Tables Not exactly available in DB2 and Oracle Consider creation of a working database to house temporary data EXISTS predicate Not available in Oracle Use subquery either with COUNT(*) or a known key value or range SET ROWCOUNT May be able to use FIRST qualifier in DB2 41
Still More Problem Areas ISNULL function nullif( expression1, expression2 ) LIKE patterns Basic patterns using % are portable Patterns using ranges or single char patterns will require rewriting Oracle has regular expression version of LIKE DB2 has plug-in regex support Functions String functions: similar, richer choices (no patindex) Other functions mostly available 42
Stored Procedures/Triggers Not a well-standardized area of SQL Different syntax in declaring procs & trigs Different usage patterns Different conventions for accessing data in trigs Triggers Before or After the triggering operation "Instead of" triggers for write operations on views SirsiDynix has said: No procs or triggers in 8.x 43
Info Sources Sybase Reference Manuals "~ is a(are) Transact-SQL extension(s)." DB2 Migrating from Sybase document: www3.software.ibm.com/ibmdl/pub/software/dw/dm/db2/0307rada/ sybase_to_db2_v8.pdf Fairly Technical and Terse MS SQL Document is also available Search for: "Porting to DB2 Universal Database" -- use "s General DB2 Info: http://www-128.ibm.com/developerworks/db2/library/techarticle/dm-0509poon2/ 44
Info Sources: Oracle Migrating from MS SQL/Sybase document: download-west.oracle.com/docs/html/b10254_01/ch2.htm Syntax differences well-grouped & fairly clear Particularly useful sections: Data Types Data Manipulation Language Unfortunately not complete Manuals on line: www.oracle.com/pls/db102/homepage 45
Don't Panic!! Use an Adequate Tool Use Formatting to your Advantage Use Commenting Effectively Use More Universal Syntax 46
Thanks for Coming! Best of Success to all CODI SQL Coders! 47
Consulting Personal Attention, Expert Assistance 48