// system & session reference

SQL typeof() and pg_typeof()

When a comparison or a sum behaves strangely, the first question is what type the value really has. Four of the five engines can tell you from a query.

Catégorie
System & session
Returns
text
In this category
9 of 13

Syntaxe

typeof(x)
pg_typeof(x)
SQL_VARIANT_PROPERTY(x, 'BaseType')
DUMP(x)

Each block is a separate form. The support table and the examples show which engine takes which.

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Different name or syntax SQL_VARIANT_PROPERTY(x, 'BaseType')
PostgreSQL Different name or syntax pg_typeof(x)
MySQL Not built in no function; CREATE TABLE t AS SELECT x, then DESCRIBE t
SQLite Oui typeof(x) returns the storage class
Oracle Different name or syntax DUMP(x) shows a type code: Typ=2 is NUMBER, Typ=1 VARCHAR2

Exemples

SQLite

SELECT typeof(1) AS a, typeof(1.5) AS b, typeof('1') AS c, typeof(NULL) AS d;  -- integer, real, text, null

PostgreSQL

SELECT pg_typeof(1) AS a, pg_typeof(1.5) AS b, pg_typeof(1::bigint + 1) AS c;  -- integer, numeric, bigint

SQL Server

SELECT SQL_VARIANT_PROPERTY(1.5, 'BaseType') AS base_type, SQL_VARIANT_PROPERTY(1.5, 'Precision') AS prec;  -- numeric, 2

Oracle

SELECT DUMP(1.5) AS d FROM dual;  -- Typ=2 Len=3: 193,2,51

Bon à savoir

  • SQLite's typeof() reports the storage class of the value, not the column's declared type. Inserting 5 into a TEXT column stores the text '5', and inserting 'abc' into an INTEGER column stores text.
  • pg_typeof('a') is unknown: a quoted literal has no type until the context gives it one.
  • SQL_VARIANT_PROPERTY converts its argument to sql_variant, so types that sql_variant cannot hold, such as varchar(max) and xml, raise an operand type clash.

Questions about TYPEOF / pg_typeof

What does typeof() return for a date in SQLite?

text, real or integer, depending on how the value was stored. SQLite has no date type; the date functions read ISO-8601 text, Julian day numbers or Unix seconds.

How do I see a column's declared type instead?

Query information_schema.columns (SQL Server, PostgreSQL, MySQL), PRAGMA table_info('t') on SQLite, or user_tab_columns on Oracle.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.