The Pocket Guide That Mapped a Fragmented Landscape
In 2007, the second German edition of Jonathan Gennick’s SQL Pocket Guide arrived as a translation matrix for developers juggling Oracle Database 10g Release 2, IBM DB2 Universal Database 8.2, Microsoft SQL Server 2005, MySQL 5.0, and PostgreSQL 8.1. Organized alphabetically by keyword rather than by platform, the book made no claim to exhaustive coverage. Its purpose was narrower: to document the translation points – function names, parameter orders, framing clauses, proprietary extensions – that a developer encounters when moving a query from one engine to another. The central argument, demonstrated through exhaustive cross-vendor comparison, is that SQL portability is largely illusory beyond the most basic DML and query structure. The ANSI/ISO standard provides a nominal common core, but every platform diverges significantly in data-type limits, date/time handling, scalar functions, hierarchical query syntax, transaction semantics, and analytic-window capabilities.
Data Types: Silent Schema Drift
The first hazard appears before a single row is inserted. VARCHAR maximums range from Oracle’s 4,000 bytes (requiring VARCHAR2) to PostgreSQL’s roughly 10.4 megabytes, with MySQL treating TEXT as a VARCHAR synonym. DECIMAL precision and scale ceilings vary wildly: Oracle caps at 38/127, SQL Server at 38/38, PostgreSQL at 1,000/1,000. A bare DECIMAL declaration triggers platform-specific defaults – Oracle creates a floating-point type, DB2 defaults to DECIMAL(5,0), SQL Server to DECIMAL(18,0). The guide’s example is blunt: CREATE TABLE t (c DECIMAL) yields three different physical representations. Explicit precision and scale specification is not pedantry; it is the only guard against silent schema drift.
Date and Time: Practically No Commonalities
If data types are a quiet trap, date/time handling is an open chasm. The guide describes “practically no commonalities” across platforms. Current-timestamp mechanisms differ fundamentally: Oracle separates session time (CURRENT_DATE) from server time (SYSDATE); DB2 uses “special registers” (CURRENT DATE, CURRENT TIMEZONE); SQL Server offers GETDATE() and GETUTCDATE(); MySQL’s NOW(), CURDATE(), CURTIME() return string or numeric results depending on context; PostgreSQL’s CURRENT_TIMESTAMP and LOCALTIMESTAMP freeze at transaction start, while TIMEOFDAY() updates mid-transaction and returns text. Arithmetic syntax diverges just as sharply. DB2 allows labeled intervals: CURRENT DATE + 1 YEARS – 3 MONTHS. SQL Server requires nested function calls: DATEADD(month, -3, DATEADD(year, 1, GETDATE())). MySQL accepts composite interval strings: DATE_ADD(CURDATE(), INTERVAL ‘1-2’ YEAR_MONTH). A developer porting a scheduling module must rewrite every temporal expression.
Conversion Functions: Incompatible Format Models
Formatting and parsing deepen the divide. Oracle’s TO_CHAR/TO_NUMBER employ case-sensitive format elements – MON versus mon controls output casing; FM suppresses padding; FX enforces exact input matching – and a 50-year pivot window (RR/RRRR) for two-digit years. DB2’s DECIMAL conversion from string defaults to scale zero and truncates without rounding; explicit precision, scale, and ROUND are required to preserve fractional digits. PostgreSQL mirrors Oracle’s format elements closely for TO_CHAR, TO_DATE, TO_TIMESTAMP – including Unix epoch conversion via TO_TIMESTAMP(0) yielding 1970-01-01 00:00:00 UTC – but cannot apply TO_CHAR to TIME types and lacks the SP element for spelled-out numbers. The guide’s cross-reference tables become a Rosetta Stone for these translations.
Window Functions: Shared Concept, Divergent Framing
Analytical functions share a conceptual core – the OVER() clause defines a window or partition; empty parentheses apply the function to the entire result set without GROUP BY – but diverge in framing and availability. PARTITION BY creates independent calculation groups; ORDER BY inside OVER() enables ranking and offset functions. Three ranking functions handle ties differently: ROW_NUMBER() assigns sequential numbers, RANK() skips values after ties, DENSE_RANK() does not. Oracle supplies LAG, LEAD, FIRST_VALUE, LAST_VALUE for cross-row access with configurable offsets and defaults. A single query can mix aggregation levels: MIN(northing) OVER (PARTITION BY county_id), AVG(northing) OVER (), and MAX(northing) OVER (PARTITION BY open_to_public) all appear in one result row. Critically, window functions are evaluated after WHERE, GROUP BY, and HAVING but before the final ORDER BY; consequently they may appear only in the SELECT list or the outer ORDER BY clause – not in WHERE or GROUP BY. Filtering on a window result requires a subquery or CTE.
Hierarchical Queries: Proprietary vs. Standard
Tree traversal splits between proprietary and standard syntax. Oracle uses CONNECT BY/START WITH/PRIOR (depth-first default) with cycle detection via CONNECT BY NOCYCLE plus diagnostic functions: CONNECT_BY_ISCYCLE (1 if child is also ancestor), CONNECT_BY_ISLEAF (1 for leaf nodes), CONNECT_BY_ROOT (root column value), LEVEL (depth from 0), and SYS_CONNECT_BY_PATH (concatenated path with delimiter) – the latter noted as the only pre-LISTAGG string aggregation across rows. Standard recursive WITH (CTE) is implemented in SQL Server and DB2 (breadth-first output). MySQL lacked recursive syntax at publication; PostgreSQL support was planned for 8.2. Recursive WITH uses a two-part UNION ALL: anchor query (roots) plus recursive part referencing the CTE name, with a LEVEL column tracking depth. Join order with CONNECT BY matters: the join materializes first, then hierarchical processing, then WHERE filters; joins may inadvertently prune hierarchy nodes. DB2 may falsely warn of infinite loops on sample data.
DML Extensions: Pervasively Proprietary
Even data modification statements resist standardization. Standard DELETE FROM table WHERE predicates is extended in platform-specific ways: MySQL adds ORDER BY (required for self-referential foreign-key constraints due to immediate checking, unlike ISO deferred checking); SQL Server supports a double-FROM join syntax (DELETE FROM gov_unit FROM gov_unit g JOIN county c …); Oracle and DB2 offer RETURNING clauses for deleted values, with Oracle’s BULK COLLECT INTO requiring PL/SQL collections for multi-row deletes; PostgreSQL mandates ON DELETE DO INSTEAD rules for view deletes. TRUNCATE TABLE empties tables faster than DELETE without row-level logging but is non-rollbackable; Oracle’s REUSE STORAGE preserves allocated space, while DB2 8.2 lacks TRUNCATE TABLE entirely. INSERT variations: single-row VALUES universal; multi-row VALUES only in DB2 and MySQL; INSERT into views supported everywhere; INSERT into subqueries in Oracle/DB2; INSERT…SELECT from subqueries universal. MySQL’s row-level constraint checking during INSERT…SELECT forces manual topological sorting – the author calls this “particularly poor.” Oracle’s RETURNING clause captures inserted column values into bind variables (single or multiple rows via arrays); PostgreSQL 8.2 support was planned. Oracle multi-table INSERT: INSERT ALL (unconditional, each source row inserts into all targets) versus INSERT FIRST/ALL with WHEN clauses (conditional routing; FIRST stops at first match, ALL evaluates all conditions).
NULL Handling: Three-Valued Logic Requires Vendor-Specific Guards
Standard comparisons (=, <>) cannot reliably test for NULL; IS NULL/IS NOT NULL are required. The predicate datum = ‘NAD1927’ OR datum <> ‘NAD1927’ excludes NULL rows. COALESCE is the ANSI-standard function for returning the first non-NULL argument (unlimited arguments, returns NULL if all are NULL). Vendors add proprietary extensions: Oracle (NVL, NVL2, DECODE), DB2 (NULLIF), SQL Server (ISNULL, SET ANSI_NULLS OFF – non-standard and deprecated), MySQL (IFNULL, IF), PostgreSQL (NULLIF). A critical caveat: NOT IN (subquery) yields UNKNOWN (never TRUE) if the subquery returns any NULL; the author recommends guarding with WHERE column IS NOT NULL in the subquery or rewriting as NOT EXISTS.
Regular Expressions: From Extensive to Minimal
Regex support varies dramatically. Oracle provides the most extensive implementation: four REGEXP_* functions (10g Release 2), Perl-inspired extensions, a 512-byte pattern limit, and a match_parameter string controlling case sensitivity (i/c), newline matching (n), and multiline anchoring (m); default case sensitivity derives from NLS_SORT. SQL Server offers only a minimal LIKE-based syntax lacking quantifiers, alternation, and backreferences. MySQL uses a REGEXP predicate with POSIX-style metacharacters and word-boundary anchors; case-insensitive for non-binary strings, literal backslashes require doubling (\\). PostgreSQL implements two approaches: the SQL-standard SIMILAR TO predicate (wildcards _ and % like LIKE, plus grouping and alternation) and POSIX-style operators (~ case-sensitive, ~* case-insensitive) with SUBSTRING and REGEXP_REPLACE functions. PostgreSQL’s POSIX regex adds non-capturing groups (?:…), lookahead (?=…), negative lookahead (?!…), word-boundary anchors \m/\M/\y/\Y, and embedded option letters ((?i) case-insensitive, (?n) newline-sensitive, (?s) single-line – default). Backreference parsing: \1-\9 always backreferences; multi-digit constructs are backreferences only if within current subexpression count, otherwise octal escapes; leading zero forces octal.
Auto-Increment: Fundamentally Different Mechanisms
Identity columns reveal no convergence. Oracle uses a SEQUENCE plus BEFORE INSERT trigger (values up to 10^27, MAXVALUE recommended); DB2 uses GENERATED ALWAYS AS IDENTITY with CACHE 20 NO ORDER; SQL Server uses IDENTITY(1,1); MySQL uses AUTO_INCREMENT; PostgreSQL uses SERIAL (4-byte integer). DB2 uniquely requires explicit NOT NULL on primary key and unique constraint columns; other vendors infer it. MySQL silently ignores foreign key constraints unless both tables use the InnoDB storage engine (historically MyISAM was default), even if referenced tables do not exist.
Transaction Control: Divergent Defaults and Syntax
Autocommit defaults vary: SQL Server, MySQL, and PostgreSQL default to autocommit; Oracle operates in implicit transaction mode. MySQL warns only InnoDB (and similar engines) support transactions – non-transactional tables commit immediately regardless. Isolation level syntax diverges: Oracle uses SET TRANSACTION; SQL Server uses SET TRANSACTION ISOLATION LEVEL (session-scoped); MySQL supports GLOBAL|SESSION scope; PostgreSQL allows setting at BEGIN or via SET TRANSACTION/SET SESSION CHARACTERISTICS. Rollback mechanisms differ: SQL Server uses ROLLBACK TRANSACTION [name] (outer transaction name rolls back all nested). Oracle supports ROLLBACK FORCE with local/global IDs for distributed transactions. Oracle, MySQL, and PostgreSQL use SAVEPOINT/ROLLBACK TO savepoint; DB2 requires SAVEPOINT … ON ROLLBACK RETAIN CURSORS/LOCKS and ROLLBACK TO SAVEPOINT. The author claims SET XACT_ABORT ON in SQL Server causes automatic rollback on statement error – a platform-specific behavior.
Set Operations: Semantic and Syntactic Gaps
UNION, EXCEPT/MINUS, INTERSECT eliminate duplicates by default; ALL variants preserve duplicates. MySQL lacks EXCEPT and INTERSECT entirely. Column naming rules differ: first SELECT determines result column names in Oracle/SQL Server/MySQL/PostgreSQL, but DB2 requires consistent aliases across all SELECTs or generates numeric names. ORDER BY applies only once, at the end of a union query. UNION duplicate removal typically requires a sort; UNION ALL avoids this overhead. EXCEPT ALL/INTERSECT ALL implement multiset semantics (each row in second result removes one matching occurrence from first); only DB2 and PostgreSQL support these. Evaluation order: INTERSECT binds tighter than UNION/EXCEPT; parentheses override left-to-right default (except MySQL, which doesn’t allow parentheses for union ordering).
CTEs and UPDATE Extensions: Uneven Support
Moving a correlated subquery into a WITH clause requires “de-correlation”: the correlation predicate becomes a WHERE clause when selecting from the CTE. CTEs can reference prior CTEs in the same WITH clause. UPDATE extensions vary: Oracle/DB2 allow row-value constructor syntax SET (c1, c2) = (subquery); other platforms require one subquery per column. Updating a view or inline view generally requires a 1:1 mapping between view rows and base-table rows. UPDATE … FROM (SQL Server/PostgreSQL) demands deterministic results – each target column must resolve to exactly one value. MySQL requires ORDER BY in UPDATE when modifying self-referential foreign/primary keys. RETURNING (Oracle) or SELECT FROM FINAL TABLE (DB2) capture post-update values without a second round-trip. The author warns that omitting WHERE in multi-column subquery updates sets all rows to NULL where no match exists. View updatability rules vary; PostgreSQL requires ON UPDATE DO INSTEAD rules.
Practical Migration Checklist
The guide’s portable-coding advice distills into a pragmatic checklist: use CASE/COALESCE instead of GREATEST/LEAST; specify explicit LOG base; write custom trim logic for SQL Server/DB2/MySQL; pre-aggregate in a subquery before joining to shrink intermediate results; prefer UNION ALL over UNION to avoid sort overhead; use smaller sort keys (integer id versus varchar name) to reduce temp space and CPU. The sample schemas – waterfall tables for Michigan’s Upper Peninsula using UTM coordinates and a 1,000-row pivot table (renamed in SQL Server where pivot is reserved) – provide concrete, reusable examples for testing equivalents. The cross-reference indexes function as a Rosetta Stone mapping German and English terms to platform-specific pages.