Consulting. Personal Attention, Expert Assistance



Similar documents
SQL Server Database Coding Standards and Guidelines

Instant SQL Programming

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database 12c: Introduction to SQL Ed 1.1

Oracle SQL. Course Summary. Duration. Objectives

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Oracle Database: SQL and PL/SQL Fundamentals

Course 20461C: Querying Microsoft SQL Server Duration: 35 hours

MOC 20461C: Querying Microsoft SQL Server. Course Overview

Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008

Data Tool Platform SQL Development Tools

Writing Queries Using Microsoft SQL Server 2008 Transact-SQL

Oracle 10g PL/SQL Training

Querying Microsoft SQL Server 2012

Course ID#: W 35 Hrs. Course Content

Writing Queries Using Microsoft SQL Server 2008 Transact-SQL

Querying Microsoft SQL Server 20461C; 5 days

Netezza SQL Class Outline

Querying Microsoft SQL Server (20461) H8N61S

A Comparison of Database Query Languages: SQL, SPARQL, CQL, DMX

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

ICAB4136B Use structured query language to create database structures and manipulate data

Querying Microsoft SQL Server

SQL Databases Course. by Applied Technology Research Center. This course provides training for MySQL, Oracle, SQL Server and PostgreSQL databases.

Search help. More on Office.com: images templates

Oracle Database: SQL and PL/SQL Fundamentals NEW

Create a New Database in Access 2010

MySQL for Beginners Ed 3

Querying Microsoft SQL Server Course M Day(s) 30:00 Hours

DBMS / Business Intelligence, SQL Server

Querying Microsoft SQL Server 2012

ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT

Course 10774A: Querying Microsoft SQL Server 2012

Course 10774A: Querying Microsoft SQL Server 2012 Length: 5 Days Published: May 25, 2012 Language(s): English Audience(s): IT Professionals

Database Programming with PL/SQL: Learning Objectives

Querying Microsoft SQL Server 2012

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

Teradata Utilities Class Outline

1. To start Installation: To install the reporting tool, copy the entire contents of the zip file to a directory of your choice. Run the exe.

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

T-SQL STANDARD ELEMENTS

Introducing Microsoft SQL Server 2012 Getting Started with SQL Server Management Studio

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

1 Structured Query Language: Again. 2 Joining Tables

Oracle Database 10g: Introduction to SQL

MOC QUERYING MICROSOFT SQL SERVER

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

AWS Schema Conversion Tool. User Guide Version 1.0

Exploring Microsoft Office Access Chapter 2: Relational Databases and Multi-Table Queries

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

Introduction to Querying & Reporting with SQL Server

Maintaining Stored Procedures in Database Application

Database Administration with MySQL

Programming with SQL

Discovering SQL. Wiley Publishing, Inc. A HANDS-ON GUIDE FOR BEGINNERS. Alex Kriegel WILEY

Release Bulletin Sybase ETL Small Business Edition 4.2

Oracle Database: Introduction to SQL

SQL Server 2008 Core Skills. Gary Young 2011

Knocker main application User manual

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

Oracle Database 10g Express

Jet Data Manager 2012 User Guide

Web Application Disassembly with ODBC Error Messages By David Litchfield Director of Security

Database Query 1: SQL Basics

Vendor: Crystal Decisions Product: Crystal Reports and Crystal Enterprise

COURSE OUTLINE UCLA EXTENSI ON MGMNT X

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

A Migration Methodology of Transferring Database Structures and Data

Data Migration In Heterogeneous Databases (ETL)

Effective Use of SQL in SAS Programming

Using Temporary Tables to Improve Performance for SQL Data Services

Microsoft Word Track Changes

Toad for Data Analysts, Tips n Tricks

Migrating Non-Oracle Databases and their Applications to Oracle Database 12c O R A C L E W H I T E P A P E R D E C E M B E R

SQL Server Developer Training Program. Topics Covered

Using SQL Server Management Studio

TG Web. Technical FAQ

Oracle Database 12c Enables Quad Graphics to Quickly Migrate from Sybase to Oracle Exadata

Using the Query Analyzer

MySQL 5.0 Stored Procedures

Using AND in a Query: Step 1: Open Query Design

Teradata SQL Assistant Version 13.0 (.Net) Enhancements and Differences. Mike Dempsey

Advanced SQL. Jim Mason. Web solutions for iseries engineer, build, deploy, support, train

Chapter 4 Accessing Data

FHE DEFINITIVE GUIDE. ^phihri^^lv JEFFREY GARBUS. Joe Celko. Alvin Chang. PLAMEN ratchev JONES & BARTLETT LEARN IN G. y ti rvrrtuttnrr i t i r

Product: DQ Order Manager Release Notes

Migrating from Sybase to SQL Server

The release notes provide details of enhancements and features in Cloudera ODBC Driver for Impala , as well as the version history.

An Oracle White Paper June Migrating Applications and Databases with Oracle Database 12c

Setting Up a CLucene and PostgreSQL Federation

Log Analyzer Reference

ODBC Chapter,First Edition

PHP Tutorial From beginner to master

3.GETTING STARTED WITH ORACLE8i

Microsoft Excel Tips & Tricks

Handling Missing Values in the SQL Procedure

Transcription:

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