Binary data in SQL, more trivia

Yesterday, I blogged about inlining boolean literals in SQL. This goes on with other data types. Let’s look at BLOBs and BINARY data in general. This is also defined in SQL standards, not in SQL 1992, though:

<binary string literal> ::=
  X <quote> [ <space>... ] 
  [ { <hexit> [ <space>... ] <hexit> [ <space>... ] }... ] <quote>

 
But is that supported as such in all databases? Of course, as usual, the answer goes “NO”. Here’s a little summary to see how binary literals are handled in which database:

SQL Server, Sybase ASE, Sybase SQL Anywhere

-- T-SQL databases treat binary literals as other languages
-- treat hexadecimal numbers
INSERT INTO lob_table VALUES (0x01FF);

DB2

-- DB2 follows the standard, but you may need to use
-- a blob constructor. This is not needed for VARCHAR
-- FOR BIT DATA types
INSERT INTO lob_table VALUES (blob(X'01FF'));

Derby, H2, HSQLDB, Ingres, MySQL, SQLite

-- Most databases follow the standard, especially
-- the Java databases
INSERT INTO lob_table VALUES (X'01FF');

Oracle

-- Oracle Omit's the standard's "X"
INSERT INTO lob_table VALUES (hextoraw('01FF'));

Postgres

-- For some odd reason Postgres, is really off this time
-- using octal representation of bytes in literals.
-- There is also hex encoding but I didn't get that to work
-- The explicit cast is important, though
INSERT INTO lob_table VALUES (E'\\001\\377'::bytea);

SQL and booleans, some trivia

Some trivia about SQL and booleans:

SQL 1992 defines three values for a boolean:

<truth value> ::=
        TRUE
      | FALSE
      | UNKNOWN

True booleans aren’t always supported, though. Here’s the truth table of boolean support:

SQL Dialect Supports booleans
DB2 0 (use 1/0 instead)
Derby true (you can safely use true/false)
H2 true
HSQLDB true
Ingres true
MySQL true
Oracle 0
Postgres true
SQL Server 0
SQLite 0
Sybase ASE 0
Sybase SQL Anywhere 0

Trivia… but nice to know.