{"id":"sql-data-types/array","corpus":"sql-data-types","engine":null,"language":"en","title":"Array columns","description":"Array columns: first-class in PostgreSQL, VARRAYs in Oracle, child tables or JSON everywhere else.","body":{"slug":"array","name":"Array","h1":"Array columns","family":"semi","lede":"A column that holds a list is genuinely useful for tags and small fixed sets. PostgreSQL makes it a first-class type; Oracle offers collections; SQL Server, MySQL and SQLite make you model it another way.","summary":"PostgreSQL arrays are real columns with indexing and operators; Oracle has VARRAY/nested-table collections; SQL Server, MySQL and SQLite have no array column type, and the honest substitute is JSON or a child table.","variants":[{"engine_slug":"sql-server","type_name":"none (child table or OPENJSON)","storage":"n/a","note":"No array columns. Model as a child table, or store JSON and shred with OPENJSON (2016+) or STRING_SPLIT for flat lists.","has_native_type":false},{"engine_slug":"postgresql","type_name":"ARRAY (e.g. integer[], text[])","storage":"Per element + overhead","note":"One-dimensional or multidimensional, with operators (ANY, @>, &&), unnest(), and GIN indexes for containment. A declared size such as integer[3] is not enforced.","has_native_type":true},{"engine_slug":"mysql","type_name":"none (JSON workaround)","storage":"n/a","note":"No arrays. A JSON column is the accepted stand-in; FIND_IN_SET over a CSV string survives in old code but cannot use indexes.","has_native_type":false},{"engine_slug":"sqlite","type_name":"none (TEXT workaround)","storage":"n/a","note":"No arrays. Common patterns: a TEXT column with a delimiter (unqueryable except by LIKE), JSON over the JSON1 functions, or a child table.","has_native_type":false},{"engine_slug":"oracle","type_name":"VARRAY or nested table","storage":"Declared max for VARRAY","note":"Collection types defined with CREATE TYPE, used as columns; query their contents with TABLE(collection) unnesting. Nested tables can be stored as IOTs.","has_native_type":true}],"gotchas":["PostgreSQL arrays update as a whole: SET tags = tags || 'x' rewrites the value, and row growth is real; arrays of arrays (multidimensional ragged) do not exist, dimensions must be rectangular.","Oracle collections are schema objects: a VARRAY type must exist before the table, and you cannot drop the type while a column uses it. Porting 'just a list' into Oracle means CREATE TYPE ceremony.","SQL Server's STRING_SPLIT arrived in 2016, takes a single-character separator, and only returns element positions with the enable_ordinal argument (2022+). A CSV column also cannot carry a foreign key to the values it lists.","MySQL JSON arrays can be indexed with a multi-valued index (8.0.17+), which serves MEMBER OF, JSON_CONTAINS and JSON_OVERLAPS; without one, every containment check scans the table.","A delimited TEXT list in SQLite accepts '1,x,3' as readily as '1,2,3'. JSON arrays at least parse (json_each() unnests them), and child rows can be constrained."],"see_also":["json","jsonb","composite"],"faqs":[{"question":"Should I store arrays or a child table?","answer":"Rows when you will query, join, or constrain the elements (foreign keys, counts); an array or JSON list when the list is read as a whole attribute, like tags on a note."},{"question":"How do I index a PostgreSQL array?","answer":"CREATE INDEX ... USING GIN on the column; then tags @> ARRAY['x'] and && (overlap) become index scans. Equality on the whole array uses a b-tree instead, which is rarely what you want."},{"question":"What replaces arrays in SQL Server?","answer":"A child table with a foreign key for anything durable, or OPENJSON over an NVARCHAR(MAX) column for document-style payloads. There is no array column type in any released SQL Server."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE TABLE notes (tags TEXT[]);\nINSERT INTO notes VALUES (ARRAY['sql', 'types']);\nSELECT 'sql' = ANY(tags) FROM notes;  -- t: first-class arrays, GIN-indexable"},{"engine_slug":"oracle","sql":"CREATE TYPE tag_list AS VARRAY(10) OF VARCHAR2(30);\nCREATE TABLE notes (tags tag_list);\nINSERT INTO notes VALUES (tag_list('sql', 'types'));\nSELECT tags FROM notes;  -- the collection type must exist before the table"},{"engine_slug":"mysql","sql":"CREATE TABLE notes (tags JSON);\nINSERT INTO notes VALUES (JSON_ARRAY('sql', 'types'));\nSELECT JSON_CONTAINS(tags, '\"sql\"') FROM notes;  -- 1: the accepted stand-in; indexable with a multi-valued index (8.0.17+)"}]},"source_url":"https://sqlly.app/sql-data-types/array","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/bigint","corpus":"sql-data-types","engine":null,"language":"en","title":"BIGINT","description":"The 64-bit integer: 8 bytes, about +/-9.2 quintillion, the safe default for IDs and epoch timestamps - with serialization traps of its own.","body":{"slug":"bigint","name":"BIGINT","h1":"BIGINT","family":"integer","lede":"8 bytes, +/-9.2 quintillion, the safe default for keys and timestamps.","summary":"BIGINT is 8 bytes in SQL Server, PostgreSQL and MySQL; SQLite folds it into INTEGER and Oracle needs NUMBER(19) to match it.","variants":[{"engine_slug":"sql-server","type_name":"BIGINT","storage":"8 bytes","note":"-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.","has_native_type":true},{"engine_slug":"postgresql","type_name":"BIGINT (INT8)","storage":"8 bytes","note":"Same range; the type behind BIGSERIAL.","has_native_type":true},{"engine_slug":"mysql","type_name":"BIGINT","storage":"8 bytes","note":"BIGINT UNSIGNED reaches 18,446,744,073,709,551,615.","has_native_type":true},{"engine_slug":"sqlite","type_name":"INTEGER","storage":"up to 8 bytes","note":"Already 64-bit signed at the top of its variable-width range; INTEGER PRIMARY KEY is the rowid.","has_native_type":true},{"engine_slug":"oracle","type_name":"NUMBER(19)","storage":"1-11 bytes","note":"No native BIGINT; NUMBER(19) covers signed 64-bit (and a little more), NUMBER(20) covers the unsigned range.","has_native_type":true}],"gotchas":["JavaScript and JSON lose precision above 2^53: round-tripping a BIGINT ID through JSON.parse corrupts it, so serialize 64-bit integers as strings.","MySQL's BIGINT UNSIGNED exceeds every other engine's signed 64-bit: values above 9.2e18 fail to import unchanged.","Oracle's NUMBER(19) is decimal, not two's-complement binary: arithmetic stays exact to 38 digits instead of overflowing at 2^63, and the limit only shows up as ORA-01438 when a result is stored back into the column."],"see_also":["integer","serial","numeric-decimal"],"faqs":[{"question":"BIGINT or INT for primary keys?","answer":"BIGINT by default. The INT-to-BIGINT migration on a hot table is painful, and 2.1 billion IDs arrive sooner than planned on event tables."},{"question":"Why is my BIGINT wrong in JavaScript?","answer":"JSON numbers are IEEE doubles, exact only to 2^53. Send 64-bit integers as strings and parse them with BigInt where needed."}],"examples":[{"engine_slug":"sql-server","sql":"CREATE TABLE orders (id BIGINT PRIMARY KEY);\nINSERT INTO orders VALUES (9223372036854775807);\nSELECT id + 1 FROM orders;  -- arithmetic overflow: the signed ceiling is real"},{"engine_slug":"mysql","sql":"CREATE TABLE counters (n BIGINT UNSIGNED);\nINSERT INTO counters VALUES (18446744073709551615);\nSELECT n FROM counters;  -- fine here, above every other signed 64-bit ceiling"},{"engine_slug":"oracle","sql":"CREATE TABLE t (n NUMBER(19));\nINSERT INTO t VALUES (99999999999999999999);  -- ORA-01438: 20 digits do not fit NUMBER(19)"}]},"source_url":"https://sqlly.app/sql-data-types/bigint","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/binary","corpus":"sql-data-types","engine":null,"language":"en","title":"BINARY and VARBINARY","description":"Fixed and variable-length byte arrays across the five engines: BINARY/VARBINARY, BYTEA, and Oracle RAW, with padding behavior and size limits.","body":{"slug":"binary","name":"BINARY and VARBINARY","h1":"BINARY and VARBINARY","family":"binary","lede":"Short byte strings - hashes, UUIDs, tokens - belong in a binary type. The names are close across engines, but padding rules and size ceilings differ in ways that bite.","summary":"Fixed-length BINARY pads with zero bytes; variable-length types (VARBINARY, BYTEA, RAW) do not. Ceilings range from 2,000 bytes (Oracle RAW) to 65,535 (MySQL row limit).","variants":[{"engine_slug":"sql-server","type_name":"BINARY(n) / VARBINARY(n)","storage":"n / n + 2 bytes","note":"BINARY pads to n with 0x00; n maxes at 8000, and VARBINARY(MAX) reaches 2 GB.","has_native_type":true},{"engine_slug":"postgresql","type_name":"BYTEA","storage":"n + 1 or 4 bytes","note":"Variable length with a 1-byte header up to 126 bytes, 4 bytes above; no fixed-length binary type, so no padding.","has_native_type":true},{"engine_slug":"mysql","type_name":"BINARY(n) / VARBINARY(n)","storage":"n / n + 1-2 bytes","note":"BINARY pads with 0x00; both are capped by the 65,535-byte row size, n included in that budget.","has_native_type":true},{"engine_slug":"sqlite","type_name":"BLOB","storage":"n bytes","note":"One type for all sizes; values are written with X'...' hex literals and compare byte by byte.","has_native_type":true},{"engine_slug":"oracle","type_name":"RAW(n)","storage":"n bytes","note":"Inline variable-length bytes, n up to 2000 (32,767 with MAX_STRING_SIZE = EXTENDED); hex input and output by default.","has_native_type":true}],"gotchas":["Fixed-length BINARY pads with 0x00 in SQL Server and MySQL, but comparisons differ: SQL Server ignores trailing zeros (0x01 = 0x0100 is true, even for VARBINARY), while in MySQL a BINARY(3) holding 'a' no longer equals 'a'.","PostgreSQL has no fixed-length binary type. BYTEA never pads, so porting a BINARY(n) column needs a CHECK (octet_length = n) to keep the contract.","MySQL counts binary columns against the 65,535-byte row limit: three VARBINARY(30000) columns fail CREATE TABLE with error 1118. Switch large ones to BLOB, which counts only 9-12 bytes.","Oracle RAW tops out at 2,000 bytes (32767 in extended mode). Anything bigger must be a BLOB, which changes the API to LOB operations.","SQLite's BLOB has one type for every purpose and no length check: a 32-byte hash column accepts a 1 GB value unless a CHECK (length(col) = 32) says otherwise."],"see_also":["blob-bytea","raw-hex","image-legacy"],"faqs":[{"question":"What is the difference between BINARY and VARBINARY?","answer":"BINARY(n) is fixed-length and pads with 0x00 to exactly n bytes; VARBINARY(n) stores only the bytes given plus a length. Use BINARY for fixed-size values like SHA-256 digests."},{"question":"How many bytes can VARBINARY hold?","answer":"SQL Server: 8,000 inline or 2 GB with MAX. MySQL: 65,535 minus the rest of the row. PostgreSQL BYTEA: about 1 GB. Oracle RAW: 2,000 (or 32,767 extended). SQLite BLOB: 1 billion bytes by default."},{"question":"What does PostgreSQL use instead of VARBINARY?","answer":"BYTEA. It is always variable-length, stores n bytes plus a 1- or 4-byte header, and reads and writes hex like '\\x9401' by default."}],"examples":[{"engine_slug":"sql-server","sql":"CREATE TABLE t (b BINARY(4));\nINSERT INTO t VALUES (0x01);\nSELECT b FROM t;  -- 0x01000000: fixed-length pads with zero bytes"},{"engine_slug":"mysql","sql":"CREATE TABLE t (b BINARY(4));\nINSERT INTO t VALUES ('a');\nSELECT HEX(b) FROM t;  -- 61000000: the zero padding is real"},{"engine_slug":"postgresql","sql":"CREATE TABLE t (b BYTEA);\nINSERT INTO t VALUES (decode('AB12', 'hex'));\nSELECT octet_length(b) FROM t;  -- 2: no fixed-length type, nothing pads it"}]},"source_url":"https://sqlly.app/sql-data-types/binary","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/binary-float","corpus":"sql-data-types","engine":null,"language":"en","title":"BINARY_FLOAT and binary-float edge cases","description":"Oracle's native binary floats and how the five engines treat IEEE 754 edge values: NaN, infinity and the results of dividing by zero.","body":{"slug":"binary-float","name":"BINARY_FLOAT / NaN and infinity","h1":"BINARY_FLOAT and binary-float edge cases","family":"approx","lede":"Where IEEE floats get weird: NaN, infinity and divide-by-zero per engine.","summary":"PostgreSQL and Oracle store NaN and infinity as values; MySQL and SQL Server reject them; SQLite keeps infinity but turns NaN into NULL.","variants":[{"engine_slug":"sql-server","type_name":"no separate type - FLOAT(53)","storage":"4-8 bytes","note":"IEEE floats, but no NaN or infinity: dividing by zero raises an error rather than producing a value.","has_native_type":false},{"engine_slug":"postgresql","type_name":"REAL / DOUBLE PRECISION","storage":"4-8 bytes","note":"IEEE throughout: 'NaN'::float8, 'Infinity' and '-Infinity' all store, and NaN sorts above every number.","has_native_type":true},{"engine_slug":"mysql","type_name":"FLOAT / DOUBLE","storage":"4-8 bytes","note":"IEEE format but NaN and infinity are rejected on insert with an error.","has_native_type":true},{"engine_slug":"sqlite","type_name":"REAL","storage":"8 bytes","note":"IEEE double: infinity stores (9e999 evaluates to Inf) but NaN quietly becomes NULL.","has_native_type":true},{"engine_slug":"oracle","type_name":"BINARY_FLOAT / BINARY_DOUBLE","storage":"4-8 bytes","note":"Native IEEE types with BINARY_FLOAT_NAN and BINARY_FLOAT_INFINITY constants and IEEE comparison rules.","has_native_type":true}],"gotchas":["NaN is not one thing: PostgreSQL stores and sorts it (above every number), SQLite maps it to NULL, MySQL and SQL Server reject it, Oracle keeps it with IEEE semantics.","Oracle's NUMBER is decimal and BINARY_DOUBLE is binary: 0.1 is exact in one and not the other, so a NUMBER compared with a BINARY_DOUBLE can fail an equality that looks obviously true.","Divide by zero: SQL Server and PostgreSQL raise errors; MySQL returns NULL with a warning in a SELECT (an error in strict-mode writes); Oracle returns Inf for BINARY_FLOAT/BINARY_DOUBLE and ORA-01476 for NUMBER; SQLite returns NULL.","JSON and most wire formats cannot carry NaN or Infinity: drivers return NULL or error when serializing them."],"see_also":["double-precision","real","numeric-decimal"],"faqs":[{"question":"What is BINARY_FLOAT in Oracle?","answer":"A native 4-byte IEEE 754 float, unlike the NUMBER-based FLOAT. BINARY_DOUBLE is its 8-byte sibling."},{"question":"Can SQL Server store NaN or Infinity?","answer":"No. Both raise errors; IEEE special values need an encoding scheme, such as a sentinel column."},{"question":"Why did my NaN become NULL in SQLite?","answer":"SQLite converts NaN to NULL on insert. Round-tripping such a value through SQLite can silently change its meaning."}],"examples":[{"engine_slug":"oracle","sql":"SELECT BINARY_FLOAT_INFINITY AS inf, BINARY_FLOAT_NAN AS nan FROM dual;  -- both are real stored values here"},{"engine_slug":"postgresql","sql":"SELECT 'NaN'::float8 > 'Infinity'::float8;  -- t: NaN sorts above every number"},{"engine_slug":"sqlite","sql":"SELECT 9e999, typeof(9e999);  -- Inf | real: infinity stores; NaN would arrive as NULL"}]},"source_url":"https://sqlly.app/sql-data-types/binary-float","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/bit","corpus":"sql-data-types","engine":null,"language":"en","title":"BIT","description":"Bit columns and bit fields: SQL Server's byte-sharing BIT, MySQL's BIT(M), PostgreSQL's bit strings, and the substitutes in SQLite and Oracle.","body":{"slug":"bit","name":"BIT","h1":"BIT","family":"exact","lede":"One-byte flags in SQL Server, bit strings elsewhere, integers in the rest.","summary":"SQL Server packs up to 8 BIT columns per byte; PostgreSQL and MySQL have real bit-string types; SQLite and Oracle make do with integers.","variants":[{"engine_slug":"sql-server","type_name":"BIT","storage":"1 byte (up to 8 packed)","note":"Stores 0, 1 or NULL; adjacent BIT columns in the same table share bytes, so 8 flags cost 1 byte total.","has_native_type":true},{"engine_slug":"postgresql","type_name":"BIT(n) / BIT VARYING(n)","storage":"(n+7)/8 bytes + overhead","note":"Fixed- or variable-length bit strings - not a boolean. Use the BOOLEAN type for flags.","has_native_type":true},{"engine_slug":"mysql","type_name":"BIT(M), M = 1-64","storage":"(M+7)/8 bytes","note":"Values are binary literals such as b'101'; many drivers return raw byte arrays.","has_native_type":true},{"engine_slug":"sqlite","type_name":"no BIT - use INTEGER","storage":"up to 8 bytes","note":"Flags are INTEGER 0/1; a bitmask INTEGER works when packing is wanted.","has_native_type":false},{"engine_slug":"oracle","type_name":"no BIT - use BOOLEAN, NUMBER(1) or RAW","storage":"1-2 bytes / variable","note":"Flags: BOOLEAN from 23ai, NUMBER(1) plus a CHECK before that; bit masks: RAW or NUMBER with BITAND().","has_native_type":false}],"gotchas":["MySQL's BIT often arrives in application code as a byte array, so bit_col = 1 checks fail; return CAST(bit_col AS UNSIGNED) or prefer TINYINT(1).","SQL Server packs up to 8 BIT columns into 1 byte, but a lone BIT still costs 1 byte, and a nullable BIT has three states: WHERE flag <> 1 skips the NULL rows.","PostgreSQL's BIT(n) is a bit-string type for masks and fingerprints, not a flag: BIT(1) compares against B'1', not 1 or TRUE. Use BOOLEAN for true/false.","SQLite accepts BIT as a type name but applies NUMERIC affinity: 0 and 1 store as integers, and a stray 'flag' string silently corrupts the column."],"see_also":["tinyint","integer"],"faqs":[{"question":"Is BIT a boolean?","answer":"In SQL Server, practically yes (0/1/NULL). In MySQL and PostgreSQL it is a bit field or bit string; for true/false prefer each engine's boolean or TINYINT(1)."},{"question":"How big is a SQL Server BIT column?","answer":"1 byte when it stands alone; up to 8 BIT columns in the same table share a single byte."}],"examples":[{"engine_slug":"sql-server","sql":"CREATE TABLE flags (a BIT, b BIT, c BIT);\nINSERT INTO flags VALUES (1, 0, NULL);\nSELECT a FROM flags WHERE b = 0;  -- 1: three states, and up to 8 BITs share one byte"},{"engine_slug":"mysql","sql":"CREATE TABLE t (m BIT(3));\nINSERT INTO t VALUES (b'101');\nSELECT CAST(m AS UNSIGNED) FROM t;  -- 5: without the CAST many drivers return raw bytes"},{"engine_slug":"postgresql","sql":"CREATE TABLE t (m BIT(4));\nINSERT INTO t VALUES (B'1010');\nSELECT m FROM t;  -- 1010: a bit string, not a boolean"}]},"source_url":"https://sqlly.app/sql-data-types/bit","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/blob-bytea","corpus":"sql-data-types","engine":null,"language":"en","title":"BLOB (large binary objects)","description":"Large binary objects in each engine: VARBINARY(MAX), BYTEA, the MySQL BLOB family, SQLite BLOB and Oracle BLOB, with real size limits and the strings attached.","body":{"slug":"blob-bytea","name":"BLOB","h1":"BLOB (large binary objects)","family":"binary","lede":"Storing files and other big byte payloads is the BLOB family's job. The documented maximums matter less than the limits you hit first: packet size, row size and TOAST.","summary":"From 1 GB (PostgreSQL BYTEA) to terabytes (Oracle BLOB). MySQL's four BLOB sizes go from 255 bytes to 4 GB but max_allowed_packet caps real transfers; Oracle keeps big values out of line.","variants":[{"engine_slug":"sql-server","type_name":"VARBINARY(MAX)","storage":"up to 2 GB","note":"The replacement for deprecated IMAGE; values over about 8 KB move off-row automatically. Files over a few MB usually belong on object storage.","has_native_type":true},{"engine_slug":"postgresql","type_name":"BYTEA","storage":"up to 1 GB","note":"TOAST moves large values out of line and may compress them; there is also Large Object (lo) storage with a different API.","has_native_type":true},{"engine_slug":"mysql","type_name":"LONGBLOB","storage":"up to 4 GB","note":"TINYBLOB 255 B, BLOB 64 KB, MEDIUMBLOB 16 MB, LONGBLOB 4 GB; max_allowed_packet caps what a single statement can move.","has_native_type":true},{"engine_slug":"sqlite","type_name":"BLOB","storage":"up to 1 billion bytes","note":"SQLITE_MAX_LENGTH defaults to 1,000,000,000 bytes (hard ceiling 2,147,483,647); sqlite3_blob_* streams into an existing value.","has_native_type":true},{"engine_slug":"oracle","type_name":"BLOB","storage":"terabytes","note":"Stored out of line with a LOB locator in the row; maximum is about (4 GB - 1) times the database block size.","has_native_type":true}],"gotchas":["MySQL's 4 GB LONGBLOB is out of reach in practice: max_allowed_packet (64 MB by default in 8.0 and 8.4) caps what one statement can send, so bigger values need a raised limit on both server and client.","Oracle BLOB columns hold a locator, not the bytes. empty_blob() initializes them, dbms_lob reads and writes, and the data lives in separate segments - plain string functions do not work.","PostgreSQL's TOAST compresses and moves values out of line once a row passes about 2 KB; it is transparent, but SELECT * then fetches and decompresses every bytea, so list columns explicitly.","SQLite's incremental blob API (sqlite3_blob_open/write) can overwrite bytes in place but never grow a value: reserve the full size with zeroblob(N) first, then stream into it.","Every engine makes big blobs slow SELECT * down. The usual rule holds: store bytes over a few MB on disk or object storage and keep a path or URL in the row."],"see_also":["binary","raw-hex","image-legacy"],"faqs":[{"question":"What is the difference between BLOB and VARBINARY(MAX)?","answer":"In SQL Server, none: VARBINARY(MAX) is the modern form of what IMAGE used to be, and values move off-row automatically when large. MySQL keeps a separate BLOB family of four sizes."},{"question":"How big can a BLOB be?","answer":"PostgreSQL BYTEA: 1 GB. SQL Server: 2 GB. MySQL LONGBLOB: 4 GB on paper, capped by max_allowed_packet. SQLite: about 1 GB by default. Oracle BLOB: effectively terabytes."},{"question":"Should I store files in the database?","answer":"For small files (a few KB to a few MB) it is fine and gives you transactional consistency. For bigger ones, store bytes on object storage and keep the path plus metadata in the row."}],"examples":[{"engine_slug":"mysql","sql":"CREATE TABLE files (data LONGBLOB);\nINSERT INTO files VALUES (REPEAT('x', 1000000));\nSELECT LENGTH(data) FROM files;  -- 1000000: max_allowed_packet caps real transfers, not the type"},{"engine_slug":"postgresql","sql":"CREATE TABLE files (data BYTEA);\nINSERT INTO files VALUES (repeat('x'::bytea, 1000000));\nSELECT octet_length(data) FROM files;  -- 1000000: TOAST kept it out of line, transparently"},{"engine_slug":"oracle","sql":"CREATE TABLE files (data BLOB);\nINSERT INTO files VALUES (EMPTY_BLOB());\nSELECT DBMS_LOB.GETLENGTH(data) FROM files;  -- 0: the row holds a locator, not bytes"}]},"source_url":"https://sqlly.app/sql-data-types/blob-bytea","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/boolean","corpus":"sql-data-types","engine":null,"language":"en","title":"BOOLEAN","description":"TRUE and FALSE in SQL: PostgreSQL's real BOOLEAN, SQL Server BIT, MySQL's TINYINT(1) alias, SQLite integers, and Oracle's late 23ai arrival.","body":{"slug":"boolean","name":"BOOLEAN","h1":"BOOLEAN","family":"boolean","lede":"Of the five engines, only PostgreSQL has a native SQL BOOLEAN in every version. SQL Server uses BIT, MySQL aliases BOOLEAN to TINYINT(1), SQLite stores integers, and Oracle added BOOLEAN to SQL only in 23ai.","summary":"One engine, PostgreSQL, has a true 1-byte BOOLEAN. SQL Server's BIT stores 0/1/NULL in one shared byte, MySQL's BOOLEAN is TINYINT(1), SQLite uses INTEGER, and Oracle got SQL BOOLEAN in 23ai.","variants":[{"engine_slug":"sql-server","type_name":"BIT","storage":"1 byte per column","note":"Stores 0, 1 or NULL only; up to 8 BIT columns in a table share one byte. There are no TRUE or FALSE keywords.","has_native_type":true},{"engine_slug":"postgresql","type_name":"BOOLEAN","storage":"1 byte","note":"TRUE, FALSE and NULL literals; displays as t and f in text output.","has_native_type":true},{"engine_slug":"mysql","type_name":"TINYINT(1)","storage":"1 byte","note":"BOOLEAN is an alias for TINYINT(1); TRUE and FALSE literals map to 1 and 0.","has_native_type":true},{"engine_slug":"sqlite","type_name":"INTEGER","storage":"1 to 8 bytes","note":"No boolean type: 0 and 1 by convention, with TRUE and FALSE keywords supported since 3.23.0 (2018).","has_native_type":true},{"engine_slug":"oracle","type_name":"BOOLEAN","storage":"1 byte","note":"Added to SQL in Oracle 23ai; before that, BOOLEAN existed only in PL/SQL and columns used NUMBER(1) or CHAR(1).","has_native_type":true}],"gotchas":["SQL Server has no TRUE or FALSE literals and no boolean value type: WHERE is_active alone is a syntax error (write is_active = 1), and SELECT a > b fails; wrap it in CASE or IIF.","PostgreSQL's BOOLEAN prints as t and f in psql and text-mode results, but casts to text as 'true' and 'false'. Code that parses raw output has to handle both.","MySQL's BOOLEAN is TINYINT(1) with no constraint: the column happily stores 2 or 42, and clients report it as a number, so 'is a boolean' is a convention, not a guarantee.","SQLite stores whatever integer you insert; TRUE and FALSE keywords resolve to 1 and 0, but nothing stops -1 or 7 from entering the column without a CHECK.","Before 23ai, Oracle's BOOLEAN existed only in PL/SQL: it could not be a column type, and a function returning BOOLEAN could not be called from a SELECT, hence the NUMBER(1)/CHAR(1) emulation everywhere."],"see_also":["boolean-emulation","bit","tinyint"],"faqs":[{"question":"Does SQL Server have a BOOLEAN type?","answer":"No. SQL Server has BIT, which stores 0, 1 and NULL in one byte (up to 8 BIT columns share a byte), but there is no TRUE/FALSE literal and no boolean expression type."},{"question":"Is MySQL's BOOLEAN a real boolean?","answer":"No. BOOLEAN is an alias for TINYINT(1) and TRUE/FALSE are aliases for 1/0. The column accepts any tinyint value unless you add a CHECK constraint."},{"question":"When did Oracle support BOOLEAN in SQL?","answer":"Oracle Database 23ai (first released as 23c Free in 2023). Before that, BOOLEAN worked only in PL/SQL, and SQL columns emulated it with NUMBER(1) or CHAR(1)."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE TABLE users (active BOOLEAN);\nINSERT INTO users VALUES (TRUE);\nSELECT active FROM users;  -- t: the native SQL BOOLEAN"},{"engine_slug":"mysql","sql":"CREATE TABLE users (active BOOLEAN);\nINSERT INTO users VALUES (2);\nSELECT active FROM users;  -- 2: BOOLEAN is TINYINT(1); nothing rejected the 2"},{"engine_slug":"oracle","sql":"CREATE TABLE users (active BOOLEAN);\nINSERT INTO users VALUES (TRUE);\nSELECT active FROM users WHERE active;  -- TRUE: BOOLEAN reached SQL in 23ai, PL/SQL had it for decades"}]},"source_url":"https://sqlly.app/sql-data-types/boolean","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/boolean-emulation","corpus":"sql-data-types","engine":null,"language":"en","title":"Emulating BOOLEAN with BIT, TINYINT(1) and CHAR(1)","description":"The patterns for faking a boolean where SQL lacks one: BIT in SQL Server, TINYINT(1) in MySQL, INTEGER in SQLite, NUMBER(1) or CHAR(1) in Oracle.","body":{"slug":"boolean-emulation","name":"Boolean emulation","h1":"Emulating BOOLEAN with BIT, TINYINT(1) and CHAR(1)","family":"boolean","lede":"Where BOOLEAN does not exist, schemas invent one: a BIT, a TINYINT(1), a CHAR(1) holding Y or N. Each emulation needs a CHECK constraint to behave like a boolean.","summary":"The portable pattern is an integer 0/1 with a CHECK (col IN (0, 1)) constraint. SQL Server's BIT constrains itself; CHAR(1) Y/N is app-specific and the least portable choice.","variants":[{"engine_slug":"sql-server","type_name":"BIT","storage":"1 byte","note":"BIT already restricts values to 0, 1 and NULL, so no CHECK is needed; comparisons write col = 1, never col = TRUE.","has_native_type":true},{"engine_slug":"postgresql","type_name":"BOOLEAN","storage":"1 byte","note":"Native type - no emulation needed on this engine.","has_native_type":true},{"engine_slug":"mysql","type_name":"TINYINT(1)","storage":"1 byte","note":"Declare BOOLEAN, then add CHECK (col IN (0, 1)) (enforced from 8.0.16) to keep out 2s and 42s.","has_native_type":true},{"engine_slug":"sqlite","type_name":"INTEGER","storage":"1 to 8 bytes","note":"SQLite stores any integer, so CHECK (col IN (0, 1)) is what makes the convention binding; TRUE and FALSE keywords map to 1 and 0.","has_native_type":true},{"engine_slug":"oracle","type_name":"NUMBER(1)","storage":"1-2 bytes","note":"Pre-23ai pattern: NUMBER(1) with 0/1, or CHAR(1) with 'Y'/'N'; pick one convention app-wide and CHECK it. 23ai has a real BOOLEAN.","has_native_type":true}],"gotchas":["CHAR(1) 'Y'/'N' is the least portable emulation: every engine, driver and ORM needs custom mapping, and mixing it with 0/1 columns in one schema is a classic source of bugs.","NULL is a third state. WHERE deleted = 0 excludes NULL rows, so 'not deleted' silently loses records unless the column is NOT NULL or the predicate says deleted = 0 OR deleted IS NULL.","Without a CHECK constraint, MySQL and SQLite accept any integer: 2, -1, 255. The type name BOOLEAN in MySQL enforces nothing.","Comparing against TRUE is fragile on emulators: in MySQL, a flag holding 2 passes WHERE flag and flag IS TRUE but fails flag = TRUE (TRUE is just 1). SQL Server has no TRUE literal, and CHAR(1) Y/N columns match neither.","ORMs differ on mapping: some render BIT/TINYINT as true/false, others as numbers, so the same column reads differently depending on which client asks."],"see_also":["boolean","bit","tinyint"],"faqs":[{"question":"What is the most portable way to emulate BOOLEAN?","answer":"An integer column with values 0 and 1 plus CHECK (col IN (0, 1)), and NOT NULL when the tri-state is not wanted. It maps cleanly in every engine and driver."},{"question":"Should I use CHAR(1) 'Y'/'N' for booleans?","answer":"Only if an existing standard forces it. It is app-specific, needs custom mapping in every client, and mixes badly with 0/1 columns elsewhere in the schema."},{"question":"Why do my MySQL boolean checks return unexpected rows?","answer":"Because the column has no CHECK constraint, so values like 2 get in: WHERE flag matches them, WHERE flag = TRUE does not. Add CHECK (col IN (0, 1)) and make the column NOT NULL."}],"examples":[{"engine_slug":"all","sql":"CREATE TABLE users (deleted INTEGER NOT NULL CHECK (deleted IN (0, 1)));\nINSERT INTO users VALUES (0);\nINSERT INTO users VALUES (2);  -- CHECK violation on every engine: the portable boolean"},{"engine_slug":"sql-server","sql":"CREATE TABLE users (deleted BIT);\nINSERT INTO users VALUES (2);  -- error: BIT already limits itself to 0, 1 and NULL"},{"engine_slug":"mysql","sql":"CREATE TABLE users (deleted BOOLEAN);\nINSERT INTO users VALUES (42);\nSELECT deleted, deleted IS TRUE FROM users;  -- 42 | 1: without a CHECK, 'is true' and 'is 1' disagree"}]},"source_url":"https://sqlly.app/sql-data-types/boolean-emulation","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/char","corpus":"sql-data-types","engine":null,"language":"en","title":"CHAR(n)","description":"Fixed-length character strings: right-padded with spaces, sized in bytes or characters depending on the engine, and rarely the right choice.","body":{"slug":"char","name":"CHAR(n)","h1":"CHAR(n)","family":"text","lede":"Fixed-length, space-padded strings - and what each engine does with the padding.","summary":"CHAR(n) pads to n and every engine cleans up the padding differently; SQLite ignores the whole idea and Oracle counts bytes.","variants":[{"engine_slug":"sql-server","type_name":"CHAR(n)","storage":"n bytes, 1-8000","note":"Blank-padded on storage; = and LIKE both ignore the stored padding, but trailing spaces inside a LIKE pattern count.","has_native_type":true},{"engine_slug":"postgresql","type_name":"CHAR(n) (character(n))","storage":"n chars + small overhead","note":"Padded to n characters; casts and most comparisons strip the padding.","has_native_type":true},{"engine_slug":"mysql","type_name":"CHAR(n)","storage":"n chars x charset bytes","note":"utf8mb4 reserves up to 4 bytes per character; retrieval strips trailing spaces (VARCHAR keeps them).","has_native_type":true},{"engine_slug":"sqlite","type_name":"CHAR(n) (TEXT affinity)","storage":"variable","note":"No padding and no length enforcement: anything non-TEXT is coerced and n is ignored.","has_native_type":true},{"engine_slug":"oracle","type_name":"CHAR(n) / NCHAR(n)","storage":"n bytes or n chars, max 2000","note":"BYTE semantics by default; CHAR semantics via CHAR(n CHAR) or NLS_LENGTH_SEMANTICS.","has_native_type":true}],"gotchas":["CHAR(n) pads values shorter than n, and engines disagree on cleanup: MySQL strips padding on retrieval, PostgreSQL strips it on cast to text, SQL Server and Oracle return it padded and ignore it in = comparisons.","SQLite accepts CHAR(n) as TEXT affinity and never enforces n or pads - a schema port that silently changes semantics.","Oracle sizes CHAR in bytes by default: in AL32UTF8 a CJK character takes 3 bytes, so CHAR(10) rejects a 4-character Japanese value. Declare CHAR(n CHAR) instead.","VARCHAR(n) is almost always the better default today; CHAR earns its keep only for truly fixed codes like country and currency."],"see_also":["varchar","text"],"faqs":[{"question":"Does CHAR save space over VARCHAR?","answer":"Rarely. Variable-length storage costs only a 1-2 byte length prefix, and with multi-byte character sets CHAR is not even fixed-size on disk. The PostgreSQL docs call character(n) the slowest of its three string types."},{"question":"Why do trailing spaces disappear from CHAR columns?","answer":"Because every engine handles the padding differently: MySQL strips it on retrieval, PostgreSQL strips it on cast to text, and SQL Server and Oracle keep it but ignore it in = comparisons."}],"examples":[{"engine_slug":"postgresql","sql":"SELECT length('ab'::char(5));  -- 2: casts strip the padding; SQL Server and Oracle keep it"},{"engine_slug":"mysql","sql":"CREATE TABLE codes (c CHAR(4));\nINSERT INTO codes VALUES ('ab');\nSELECT CONCAT('[', c, ']') FROM codes;  -- [ab]: padding stripped on retrieval"},{"engine_slug":"oracle","sql":"CREATE TABLE t (c CHAR(3 CHAR));\nINSERT INTO t VALUES ('日本');  -- 2 characters, 6 bytes: fits CHAR(3 CHAR), fails CHAR(3)"}]},"source_url":"https://sqlly.app/sql-data-types/char","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/composite","corpus":"sql-data-types","engine":null,"language":"en","title":"Composite, table and object types","description":"Custom row and object types: PostgreSQL composites, SQL Server table types, Oracle OBJECTs, none elsewhere.","body":{"slug":"composite","name":"Composite & object types","h1":"Composite, table and object types","family":"other","lede":"Define your own row shape once, use it as a column type, a function parameter, or a table of rows. PostgreSQL, SQL Server and Oracle each own a flavor; MySQL and SQLite have nothing to translate it into.","summary":"Composite types bundle fields into one named type: PostgreSQL composites and Oracle OBJECTs become column types, SQL Server table types carry rows into procedures, and MySQL/SQLite simply lack them.","variants":[{"engine_slug":"sql-server","type_name":"CREATE TYPE ... AS TABLE","storage":"Per definition","note":"Table types (table-valued parameters) pass rowsets into procedures; also CLR UDTs for scalar custom types. No composite column type.","has_native_type":true},{"engine_slug":"postgresql","type_name":"CREATE TYPE ... AS (...)","storage":"Sum of fields","note":"Composite types: usable as column types, function return rows, and row constructors; every table and view also implicitly creates one.","has_native_type":true},{"engine_slug":"mysql","type_name":"none","storage":"n/a","note":"No composite or object types. Pack into JSON columns or normalize to child tables.","has_native_type":false},{"engine_slug":"sqlite","type_name":"none","storage":"n/a","note":"No composite or object types; JSON in TEXT is the only bundling mechanism.","has_native_type":false},{"engine_slug":"oracle","type_name":"CREATE TYPE ... AS OBJECT","storage":"Per definition","note":"Object types work as column types, as the row type of object tables (which carry an OID per row), in VARRAYs and nested tables, and as PL/SQL argument types.","has_native_type":true}],"gotchas":["PostgreSQL composite columns resist change: ADD and DROP ATTRIBUTE work while a table uses the type, but ALTER ATTRIBUTE ... TYPE fails with 'cannot alter type because column uses it', and many ORMs cannot map a row inside a row.","Oracle stores an object column as hidden scalar columns (one per attribute plus a null indicator), object tables add a 16-byte OID per row, and nested tables need a STORE AS clause. Loaders and drivers that expect plain columns need special handling.","SQL Server table types are read-only in use: table-valued parameters flow in, they cannot be a column, and a type change requires dropping every procedure that references it first.","Every engine with custom types ties the type to the schema lifecycle: you cannot drop a type that a column, function, or procedure uses, so 'just rename the field' becomes a migration.","MySQL and SQLite translations are lossy by definition: a composite becomes either flattened columns (losing the one-value semantics) or a JSON blob (losing per-field typing)."],"see_also":["array","json","enum"],"faqs":[{"question":"What is a table-valued parameter in SQL Server?","answer":"A CREATE TYPE ... AS TABLE definition used to pass a rowset into a stored procedure or batch as one parameter, declared READONLY. It is SQL Server's only structured user type, and it cannot be a column type."},{"question":"Can a PostgreSQL column be of a row type?","answer":"Yes: CREATE TYPE address AS (city text, zip text); then a column address address stores the struct inline, queried as (col).city. Every table already has an implicit row type too, usable in functions."},{"question":"How do I migrate Oracle OBJECT columns to PostgreSQL?","answer":"Flatten to scalar columns, or map to a PostgreSQL composite type (or JSONB for flexible shapes). Object-table OIDs, REF columns and storage clauses do not translate; plan the driver and ORM changes too."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE TYPE address AS (city TEXT, zip TEXT);\nCREATE TABLE users (home address);\nINSERT INTO users VALUES (ROW('Denver', '80202'));\nSELECT (home).city FROM users;  -- Denver: a row type as a column"},{"engine_slug":"sql-server","sql":"CREATE TYPE order_items AS TABLE (id INT, qty INT);  -- flows into procedures as a read-only table-valued parameter; cannot be a column"},{"engine_slug":"oracle","sql":"CREATE TYPE address_t AS OBJECT (city VARCHAR2(30), zip VARCHAR2(10));\nCREATE TABLE users (home address_t);\nINSERT INTO users VALUES (address_t('Denver', '80202'));\nSELECT u.home.city FROM users u;  -- Denver: stored as hidden scalar columns"}]},"source_url":"https://sqlly.app/sql-data-types/composite","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/date","corpus":"sql-data-types","engine":null,"language":"en","title":"DATE","description":"The DATE type across SQL Server, PostgreSQL, MySQL, SQLite and Oracle: storage sizes, supported ranges and the traps that differ between engines.","body":{"slug":"date","name":"DATE","h1":"DATE","family":"datetime","lede":"DATE holds a calendar day with no clock attached. It sounds like the simplest type in SQL, and every engine still manages to disagree about it.","summary":"A calendar date without a time-of-day. SQL Server and MySQL use 3 bytes with narrower ranges, PostgreSQL uses 4 bytes and reaches back to 4713 BC, and Oracle has no pure DATE at all.","variants":[{"engine_slug":"sql-server","type_name":"DATE","storage":"3 bytes","note":"Range 0001-01-01 to 9999-12-31; added in SQL Server 2008, before that DATETIME carried dates.","has_native_type":true},{"engine_slug":"postgresql","type_name":"DATE","storage":"4 bytes","note":"Range 4713 BC to 5874897 AD; accepts 'today', 'tomorrow', 'infinity' and '-infinity' as values.","has_native_type":true},{"engine_slug":"mysql","type_name":"DATE","storage":"3 bytes","note":"Range 1000-01-01 to 9999-12-31; strict mode (the default) rejects invalid dates, which only become '0000-00-00' when strict mode is off.","has_native_type":true},{"engine_slug":"sqlite","type_name":"TEXT","storage":"variable","note":"No native DATE. Store ISO-8601 text like '2026-02-14' and use the date() and strftime() functions.","has_native_type":true},{"engine_slug":"oracle","type_name":"DATE","storage":"7 bytes","note":"Not a pure date: an Oracle DATE always carries a time component, defaulting to 00:00:00.","has_native_type":true}],"gotchas":["Oracle's DATE is not date-only. It always stores century through seconds (7 bytes), so DATE '2026-02-14' is really 2026-02-14 00:00:00, and subtracting two DATEs yields a number of days, not a date.","SQLite has no DATE type. A column declared DATE gets NUMERIC affinity, so '2026-02-14' stays text and 20260214 stays an integer; every date operation goes through date functions or string comparison.","MySQL's DATE range starts at 1000-01-01, and with strict mode off, invalid input silently becomes the zero date '0000-00-00' instead of an error.","SQL Server only gained DATE in 2008. Older code ships dates inside DATETIME, rounding every value to a 3.33-millisecond grid you did not ask for.","PostgreSQL accepts 'infinity' and '-infinity' as DATE values, which sorts above and below every real date - handy for sentinels, surprising in exports."],"see_also":["timestamp","timestamptz","datetime2"],"faqs":[{"question":"How many bytes does DATE use?","answer":"SQL Server and MySQL store a DATE in 3 bytes, PostgreSQL in 4, and Oracle's DATE in 7 because it includes a time. SQLite stores whatever representation you chose, usually text."},{"question":"Does DATE include a time zone?","answer":"No. DATE is a calendar day with no time and no zone. Time-zone handling belongs to TIMESTAMPTZ or DATETIMEOFFSET."},{"question":"Why does my Oracle DATE show a time?","answer":"Because Oracle DATE always stores one. NLS_DATE_FORMAT often hides it, so WHERE d = DATE '2026-02-14' silently misses rows whose time is not midnight; compare a range or use TRUNC(d)."}],"examples":[{"engine_slug":"oracle","sql":"CREATE TABLE due (d DATE);\nINSERT INTO due VALUES (DATE '2026-02-14');\nSELECT TO_CHAR(d, 'YYYY-MM-DD HH24:MI:SS') FROM due;  -- 2026-02-14 00:00:00: a time is always there"},{"engine_slug":"postgresql","sql":"SELECT 'infinity'::date, 'today'::date;  -- sentinel values sort past every real date"},{"engine_slug":"mysql","sql":"CREATE TABLE due (d DATE);\nSET sql_mode = '';\nINSERT INTO due VALUES ('not-a-date');\nSELECT d FROM due;  -- 0000-00-00: only with strict mode off"}]},"source_url":"https://sqlly.app/sql-data-types/date","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/datetime2","corpus":"sql-data-types","engine":null,"language":"en","title":"DATETIME2 and SMALLDATETIME","description":"SQL Server's three datetime types compared - DATETIME2, legacy DATETIME and SMALLDATETIME - and the closest type in PostgreSQL, MySQL, SQLite and Oracle.","body":{"slug":"datetime2","name":"DATETIME2 and SMALLDATETIME","h1":"DATETIME2 and SMALLDATETIME","family":"datetime","lede":"SQL Server ships three datetimes with no zone. DATETIME2 is the modern one, DATETIME is the legacy type that starts in 1753 and rounds to 3.33 ms, and SMALLDATETIME rounds to whole minutes.","summary":"SQL Server's DATETIME2 (6-8 bytes, 100 ns, years 1-9999), legacy DATETIME (8 bytes, 3.33 ms) and SMALLDATETIME (4 bytes, minutes, 1900-2079), with each other engine's nearest equivalent.","variants":[{"engine_slug":"sql-server","type_name":"DATETIME2 / SMALLDATETIME","storage":"6 to 8 / 4 bytes","note":"DATETIME2(p): 6 bytes at p 0-2 up to 8 at p 7. SMALLDATETIME is 4 bytes with minute precision, range 1900-01-01 to 2079-06-06.","has_native_type":true},{"engine_slug":"postgresql","type_name":"TIMESTAMP(p)","storage":"8 bytes","note":"timestamp(0) is the SMALLDATETIME stand-in: whole seconds, still 8 bytes. PostgreSQL has no minute-rounded type.","has_native_type":true},{"engine_slug":"mysql","type_name":"DATETIME","storage":"5 to 8 bytes","note":"DATETIME(0) gives whole seconds in 5 bytes; range 1000-9999 dwarfs SMALLDATETIME's 1900-2079.","has_native_type":true},{"engine_slug":"sqlite","type_name":"TEXT","storage":"variable","note":"No equivalent. ISO-8601 text; truncate to minutes or seconds yourself before storing.","has_native_type":true},{"engine_slug":"oracle","type_name":"TIMESTAMP","storage":"7 to 11 bytes","note":"Oracle DATE (7 bytes) stores whole seconds, the closest match to SMALLDATETIME; TIMESTAMP(p) adds up to 9 fractional digits.","has_native_type":true}],"gotchas":["Legacy DATETIME rounds to .000, .003 or .007 (a 1/300-second grid), so a value like 12:00:00.005 silently becomes .007 and equality lookups miss. DATETIME2 does not round this way.","DATETIME starts at 1753-01-01, the first full year after Britain and its colonies switched to the Gregorian calendar; DATETIME2 covers 0001-01-01 to 9999-12-31. Historical data needs DATETIME2.","SMALLDATETIME rounds to the nearest minute (29.998 seconds or less round down) and stops at 2079-06-06, which 30-year mortgage and lease end dates already pass.","MySQL's DATETIME and SQL Server's DATETIME share a name but nothing else: MySQL's is zone-free wall-clock time with a 5-byte base; SQL Server's is the 8-byte 3.33 ms legacy type.","DATETIME2 costs the same 8 bytes as legacy DATETIME at full precision (less below p 5), so there is no storage reason left to pick DATETIME for new tables."],"see_also":["timestamp","timestamptz","date"],"faqs":[{"question":"Should I use DATETIME2 or DATETIME in SQL Server?","answer":"DATETIME2. It has a wider range (year 1 to 9999), 100-nanosecond precision, and the same or smaller storage. Keep DATETIME only for compatibility with old code that depends on the 3.33 ms rounding."},{"question":"What is SMALLDATETIME good for?","answer":"Minute-granularity schedules where 4 bytes matter. It rounds to the nearest minute and cannot store dates past 2079-06-06, which is closer than it sounds."},{"question":"How many bytes is DATETIME2?","answer":"6 bytes at precision 0-2, 7 bytes at 3-4, and 8 bytes at 5-7. Legacy DATETIME is always 8 bytes, and SMALLDATETIME is 4."}],"examples":[{"engine_slug":"sql-server","sql":"CREATE TABLE t (a DATETIME, b DATETIME2(3));\nINSERT INTO t VALUES ('2026-02-14 12:00:00.005', '2026-02-14 12:00:00.005');\nSELECT a, b FROM t;  -- .007 vs .005: legacy DATETIME rounds to a 1/300 s grid"},{"engine_slug":"postgresql","sql":"CREATE TABLE t (x TIMESTAMP(0));\nINSERT INTO t VALUES ('2026-02-14 12:30:45.7');\nSELECT x FROM t;  -- 12:30:46: the SMALLDATETIME-style round, still 8 bytes"}]},"source_url":"https://sqlly.app/sql-data-types/datetime2","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/double-precision","corpus":"sql-data-types","engine":null,"language":"en","title":"DOUBLE PRECISION (FLOAT8)","description":"Double-precision IEEE 754 floats: 8 bytes, about 15 significant digits - the default float in SQLite and in most application drivers.","body":{"slug":"double-precision","name":"DOUBLE PRECISION / FLOAT8","h1":"DOUBLE PRECISION (FLOAT8)","family":"approx","lede":"An 8-byte IEEE double in SQL Server, PostgreSQL, MySQL and SQLite; in Oracle DOUBLE PRECISION means decimal FLOAT(126) and BINARY_DOUBLE is the real thing.","summary":"An 8-byte IEEE double in SQL Server, PostgreSQL, MySQL and SQLite; in Oracle the keyword means FLOAT(126), a decimal NUMBER, and the IEEE double is BINARY_DOUBLE.","variants":[{"engine_slug":"sql-server","type_name":"FLOAT (FLOAT(53))","storage":"8 bytes","note":"DOUBLE PRECISION is accepted and stored as FLOAT(53); FLOAT(n) is 4 bytes for n 1-24 and 8 bytes for 25-53.","has_native_type":true},{"engine_slug":"postgresql","type_name":"DOUBLE PRECISION (FLOAT8)","storage":"8 bytes","note":"15 decimal digits; FLOAT(p) with 25 <= p <= 53 selects it.","has_native_type":true},{"engine_slug":"mysql","type_name":"DOUBLE","storage":"8 bytes","note":"DOUBLE PRECISION is a synonym; REAL maps to DOUBLE unless REAL_AS_FLOAT mode is set.","has_native_type":true},{"engine_slug":"sqlite","type_name":"REAL","storage":"8 bytes","note":"The only float: an 8-byte IEEE double, whatever the declaration said.","has_native_type":true},{"engine_slug":"oracle","type_name":"BINARY_DOUBLE","storage":"8 bytes","note":"Native IEEE double with NaN and infinity; FLOAT(126) is instead the NUMBER-based decimal float.","has_native_type":true}],"gotchas":["In SQLite the declared name is irrelevant: REAL, FLOAT and DOUBLE all produce the same 8-byte double under REAL affinity.","In Oracle, a column declared DOUBLE PRECISION becomes FLOAT(126), a decimal NUMBER, not an IEEE double. Ask for BINARY_DOUBLE when you want 8-byte IEEE behavior, NaN and Inf.","MySQL's REAL follows DOUBLE unless the REAL_AS_FLOAT SQL mode says otherwise, a recurring porting surprise.","SQL Server's FLOAT(1-24) silently shrinks to a 4-byte float; FLOAT with no argument means 53, not 24."],"see_also":["real","binary-float","numeric-decimal"],"faqs":[{"question":"REAL or DOUBLE?","answer":"DOUBLE for general work: four extra bytes buy 15 digits instead of 7. Choose REAL/FLOAT only for large measured arrays where size matters."},{"question":"Is DOUBLE PRECISION exact?","answer":"No. It is approximate binary floating point: 0.1 has no exact binary form. Use NUMERIC/DECIMAL where exactness is required."}],"examples":[{"engine_slug":"postgresql","sql":"SELECT 0.1::double precision * 3 = 0.3::double precision;  -- f: binary floats drift"},{"engine_slug":"sql-server","sql":"CREATE TABLE t (v FLOAT(53));\nINSERT INTO t VALUES (0.1);\nSELECT v FROM t;  -- 0.1: FLOAT with no argument means 53, not 24"},{"engine_slug":"oracle","sql":"SELECT CAST(0.1 AS BINARY_DOUBLE) FROM dual;  -- the IEEE double; DOUBLE PRECISION resolves to FLOAT(126), a decimal NUMBER"}]},"source_url":"https://sqlly.app/sql-data-types/double-precision","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/enum","corpus":"sql-data-types","engine":null,"language":"en","title":"ENUM and enumerated types","description":"Enumerated types: MySQL's table-bound ENUM, PostgreSQL's CREATE TYPE, CHECK constraints elsewhere.","body":{"slug":"enum","name":"ENUM","h1":"ENUM and enumerated types","family":"other","lede":"PostgreSQL puts the value list in a schema type, MySQL puts it on the column, Oracle 23ai has enum domains, and SQL Server and SQLite make you use a CHECK constraint or lookup table.","summary":"A real enum type (PostgreSQL) is ordered and schema-wide; MySQL ENUM is declared per column and sorts by position; the rest fake it with CHECK constraints, which edit differently.","variants":[{"engine_slug":"sql-server","type_name":"none (CHECK or lookup table)","storage":"n/a","note":"No enum type. A CHECK (status IN ('new','paid')) or a lookup table with a foreign key; lookup tables are the standard answer when values carry data.","has_native_type":false},{"engine_slug":"postgresql","type_name":"ENUM (CREATE TYPE)","storage":"4 bytes","note":"CREATE TYPE mood AS ENUM ('sad','ok','happy'): stored as an int index, ordered by declaration, labels are case-sensitive and shared schema-wide.","has_native_type":true},{"engine_slug":"mysql","type_name":"ENUM('a','b','c')","storage":"1-2 bytes","note":"Declared on the column inside CREATE TABLE; stored as a 1- or 2-byte index into the value list, sorted by that index, not alphabetically.","has_native_type":true},{"engine_slug":"sqlite","type_name":"none (TEXT + CHECK)","storage":"TEXT size","note":"No enum. TEXT with CHECK (col IN (...)) is the idiom; nothing but the constraint ties the value list down.","has_native_type":false},{"engine_slug":"oracle","type_name":"enum domain (23ai) or CHECK","storage":"n/a","note":"23ai adds CREATE DOMAIN ... AS ENUM; earlier releases use CHECK constraints or lookup tables.","has_native_type":true}],"gotchas":["MySQL ENUM sorts by declaration order, not alphabetically: ORDER BY on an ENUM column returns the values in the order they were listed in CREATE TABLE, which is either a feature or a bug depending on who wrote the query.","MySQL also stores the empty string '' for invalid values when strict mode is off, silently: the row inserts with a value that is not in your list.","PostgreSQL enums grow awkwardly: ALTER TYPE ... ADD VALUE appends (or goes BEFORE/AFTER an existing label), RENAME VALUE works since 10, but removing or reordering means creating a new type and rewriting the column.","CHECK-constraint enums (SQL Server, SQLite, Oracle) edit with ALTER TABLE, but the value list is duplicated everywhere the column appears across the schema.","PostgreSQL enum labels are case-sensitive and typed: mood_col = 'happy' works because the literal is coerced, but mood_col = some_text_column fails with 'operator does not exist: mood = text' until you cast."],"see_also":["hstore","composite","integer"],"faqs":[{"question":"MySQL ENUM or a lookup table?","answer":"Lookup table when values may change, carry extra data, or are referenced across tables; ENUM only for a short list that never changes, where you accept an ALTER TABLE to add a value."},{"question":"How do I add a value to a PostgreSQL enum?","answer":"ALTER TYPE mytype ADD VALUE 'new' (optionally BEFORE or AFTER an existing label). Before PostgreSQL 12 it could not run inside a transaction block; since 12 it can, but the new value is unusable until that transaction commits. There is no DROP VALUE."},{"question":"Why does my enum column sort weirdly?","answer":"MySQL ENUMs and PostgreSQL enums both sort by their position in the declared list, not alphabetically. CHECK-constraint text columns sort alphabetically, because they are just text."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');\nCREATE TABLE users (m mood);\nINSERT INTO users VALUES ('happy');\nSELECT m FROM users ORDER BY m;  -- declaration order, not alphabetical"},{"engine_slug":"mysql","sql":"CREATE TABLE shirts (size ENUM('s', 'm', 'l'));\nINSERT INTO shirts VALUES ('m');\nSELECT size + 0 FROM shirts;  -- 2: stored as a 1-byte index into the list"},{"engine_slug":"sqlite","sql":"CREATE TABLE shirts (size TEXT CHECK (size IN ('s', 'm', 'l')));\nINSERT INTO shirts VALUES ('xl');  -- CHECK violation: the constraint is the only enum here"}]},"source_url":"https://sqlly.app/sql-data-types/enum","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/float","corpus":"sql-data-types","engine":null,"language":"en","title":"FLOAT(p)","description":"FLOAT(p) means IEEE single or double in most engines, but in Oracle it is decimal NUMBER. Precision ranges, storage sizes, and where the 24/25 boundary falls.","body":{"slug":"float","name":"FLOAT(p)","h1":"FLOAT(p)","family":"approx","lede":"FLOAT(p) looks like one type with a precision knob. In SQL Server, PostgreSQL and MySQL it picks a 4- or 8-byte IEEE float; in Oracle the same keyword declares a decimal NUMBER.","summary":"SQL standard FLOAT(p): p up to 24 selects a 4-byte IEEE float, 25 to 53 an 8-byte double - except Oracle, where FLOAT(p) is decimal NUMBER and BINARY_FLOAT is the real float.","variants":[{"engine_slug":"sql-server","type_name":"FLOAT(p)","storage":"4 or 8 bytes","note":"p 1-24 is 4 bytes, p 25-53 is 8 bytes. REAL is a synonym for FLOAT(24); the default FLOAT is FLOAT(53).","has_native_type":true},{"engine_slug":"postgresql","type_name":"float(p)","storage":"4 or 8 bytes","note":"p 1-24 selects real (4 bytes), p 25-53 selects double precision (8 bytes); the precision is advisory, not exact digits.","has_native_type":true},{"engine_slug":"mysql","type_name":"FLOAT(p)","storage":"4 or 8 bytes","note":"p 0-24 maps to FLOAT, 25-53 to DOUBLE. FLOAT(p) is fine; the two-argument FLOAT(M,D) form is the deprecated one.","has_native_type":true},{"engine_slug":"sqlite","type_name":"REAL","storage":"8 bytes","note":"One IEEE 754 double for every floating-point column; the declared precision is ignored entirely.","has_native_type":true},{"engine_slug":"oracle","type_name":"FLOAT(p)","storage":"1-20 bytes (decimal)","note":"Not IEEE: FLOAT(p) is a NUMBER subtype whose precision p (1-126) counts binary digits, about 0.3 x p decimal digits. The 4-byte IEEE float is BINARY_FLOAT.","has_native_type":true}],"gotchas":["Oracle's FLOAT(p) is the trap: it is a decimal NUMBER subtype, not IEEE 754, so FLOAT(24) gives about 7 decimal digits of NUMBER, not a 4-byte float. Code that expects IEEE rounding and NaN needs BINARY_FLOAT or BINARY_DOUBLE.","The 24/25 boundary decides storage: p up to 24 gives a 4-byte single, 25 and up an 8-byte double, in SQL Server, PostgreSQL and MySQL alike.","MySQL deprecates FLOAT(M,D) and DOUBLE(M,D) (the two-argument display forms) since 8.0.17; single-argument FLOAT(p) is standard SQL and still fine.","SQLite ignores declared precision: FLOAT(10) and DOUBLE PRECISION both become the same 8-byte REAL.","Approximate types never store exact decimals: 0.1 drifts, equality comparisons fail, and money in FLOAT is a bug waiting to be filed."],"see_also":["double-precision","real","binary-float","numeric-decimal"],"faqs":[{"question":"Is FLOAT(p) exact?","answer":"Not in SQL Server, PostgreSQL, MySQL or SQLite: there it is binary floating point, 0.1 has no exact form, and sums drift. Oracle is the odd one out, since its FLOAT(p) is a decimal NUMBER. Use NUMERIC for exact decimals."},{"question":"What is Oracle's equivalent of an IEEE float?","answer":"BINARY_FLOAT (4 bytes) and BINARY_DOUBLE (8 bytes). Oracle's FLOAT(p) is a decimal NUMBER subtype with binary precision p, so it rounds like NUMBER, not like IEEE."},{"question":"How many bytes is FLOAT(p)?","answer":"4 bytes when p is 24 or below, 8 bytes when p is 25 to 53, in SQL Server, PostgreSQL and MySQL. SQLite always uses 8 bytes; Oracle's FLOAT is variable-length decimal."}],"examples":[{"engine_slug":"sql-server","sql":"CREATE TABLE t (a FLOAT(24), b FLOAT(53));\nINSERT INTO t VALUES (1.5, 1.5);\nSELECT DATALENGTH(a), DATALENGTH(b) FROM t;  -- 4 | 8: the 24/25 boundary picks the size"},{"engine_slug":"oracle","sql":"CREATE TABLE t (v FLOAT(24));\nINSERT INTO t VALUES (0.1);\nSELECT v FROM t;  -- decimal NUMBER rounding, not IEEE: the IEEE single is BINARY_FLOAT"},{"engine_slug":"sqlite","sql":"CREATE TABLE t (v FLOAT(10));\nINSERT INTO t VALUES (1.5);\nSELECT typeof(v) FROM t;  -- real: the precision knob is ignored"}]},"source_url":"https://sqlly.app/sql-data-types/float","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/hstore","corpus":"sql-data-types","engine":null,"language":"en","title":"Hstore: key-value storage","description":"PostgreSQL's hstore extension: flat text key-value pairs, and the JSON alternatives elsewhere.","body":{"slug":"hstore","name":"Hstore","h1":"Hstore: key-value storage","family":"semi","lede":"hstore is PostgreSQL's original key-value column: a flat map of text to text, indexable with GIN. JSONB does most of its job now, and the other engines never had a name for it at all.","summary":"hstore is a PostgreSQL extension for flat string-to-string maps, GIN-indexable and cheap. jsonb supersedes it for nested data; every other engine reaches for JSON or a child table.","variants":[{"engine_slug":"sql-server","type_name":"none (JSON workaround)","storage":"n/a","note":"No key-value type. NVARCHAR(MAX) JSON with OPENJSON, or an EAV child table for attribute-heavy designs.","has_native_type":false},{"engine_slug":"postgresql","type_name":"HSTORE","storage":"Text pairs, variable","note":"Extension (CREATE EXTENSION hstore): flat text-to-text map written 'a=>1, b=>2', with operators ->, ?, ?|, ?& and @>; GIN indexes serve key and containment lookups.","has_native_type":true},{"engine_slug":"mysql","type_name":"none (JSON workaround)","storage":"n/a","note":"No equivalent. JSON columns cover key-value access; SET columns exist but hold enumerated values, not arbitrary keys.","has_native_type":false},{"engine_slug":"sqlite","type_name":"none (TEXT workaround)","storage":"n/a","note":"No equivalent. JSON (JSON1 functions) or a key-value child table is the pattern.","has_native_type":false},{"engine_slug":"oracle","type_name":"none (JSON workaround)","storage":"n/a","note":"No hstore; use native JSON columns (21c+) or a name/value child table. Oracle's object types can fake maps but are not queryable the same way.","has_native_type":false}],"gotchas":["hstore values are text, full stop: storing numbers and booleans works, but every read compares and sorts strings, and there are no nested structures. jsonb keeps types and nests.","hstore keeps one value per key, and when the input repeats a key the docs do not promise which value survives. Old code that builds values with the text => text operator breaks: that operator was removed; use hstore('k', 'v').","GIN index choice matters for both: the default jsonb_ops class indexes every key and value, while jsonb_path_ops is smaller but only serves @>. Measure index size before indexing a wide attribute column.","The other four engines have no hstore, so any schema using it needs a documented JSON or EAV translation for migrations, not a type mapping.","For flat user-defined attributes, hstore's text-only model is a fine fit, and existing hstore columns convert to jsonb with a plain cast (col::jsonb) when nesting or types become necessary."],"see_also":["json","jsonb","enum"],"faqs":[{"question":"Is hstore deprecated in favor of jsonb?","answer":"Not deprecated, just niche. It still ships with PostgreSQL and works well for flat text-to-text maps; for anything nested or typed, jsonb wins. New schemas usually default to jsonb."},{"question":"Why do I get 'type hstore does not exist'?","answer":"hstore ships with PostgreSQL as a contrib extension, so each database needs CREATE EXTENSION hstore before the type exists. Most managed services allow it; locked-down installs may not."},{"question":"How do I query 'has this key' in hstore?","answer":"Use the ? operator (attr ? 'color') or @> for containment (attr @> 'color=>red'), both GIN-indexable. To build a value in code, call hstore('color', 'red')."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE EXTENSION IF NOT EXISTS hstore;\nCREATE TABLE attrs (a hstore);\nINSERT INTO attrs VALUES ('color=>red');\nSELECT a -> 'color' FROM attrs;  -- red: extension first, flat text pairs only"}]},"source_url":"https://sqlly.app/sql-data-types/hstore","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/identity","corpus":"sql-data-types","engine":null,"language":"en","title":"Auto increment and identity columns","description":"AUTO_INCREMENT, IDENTITY(1,1) and GENERATED AS IDENTITY: per-engine syntax, gaps and limits.","body":{"slug":"identity","name":"Auto increment & identity","h1":"Auto increment and identity columns","family":"identifier","lede":"The cheapest primary key is a counter the engine hands out on insert. Every engine has one; every engine spells it differently, and the fine print (gaps, explicit values, one-per-table rules) differs more than the syntax suggests.","summary":"All five engines can auto-number a column. The standard spelling is GENERATED ... AS IDENTITY; MySQL keeps AUTO_INCREMENT, SQLite uses INTEGER PRIMARY KEY, and gaps are normal everywhere.","variants":[{"engine_slug":"sql-server","type_name":"IDENTITY(1,1)","storage":"On the host column (4 or 8 bytes as INT/BIGINT)","note":"Declared per column; insert explicit values only after SET IDENTITY_INSERT table ON, session-scoped and table-bound.","has_native_type":true},{"engine_slug":"postgresql","type_name":"GENERATED AS IDENTITY","storage":"On the host column","note":"Since PostgreSQL 10; owns its backing sequence. GENERATED ALWAYS rejects explicit values unless the INSERT says OVERRIDING SYSTEM VALUE; BY DEFAULT accepts them. SERIAL is the older shorthand.","has_native_type":true},{"engine_slug":"mysql","type_name":"AUTO_INCREMENT","storage":"On the host column","note":"At most one per table, and it must be the first column of some index. Integer columns in practice; FLOAT/DOUBLE support is deprecated.","has_native_type":true},{"engine_slug":"sqlite","type_name":"INTEGER PRIMARY KEY","storage":"1-8 bytes (varint rowid)","note":"Any INTEGER PRIMARY KEY is an alias for the rowid and auto-assigns; the AUTOINCREMENT keyword is stricter (never reuses ids) and slower, rarely needed.","has_native_type":true},{"engine_slug":"oracle","type_name":"GENERATED AS IDENTITY","storage":"On the host column","note":"Since 12c, one identity column per table; before that, a SEQUENCE plus a BEFORE INSERT trigger was the house pattern, and plenty of those still exist.","has_native_type":true}],"gotchas":["Gaps are not a bug: a rolled-back insert burns the number in SQL Server, PostgreSQL, MySQL and Oracle (SQLite reuses it). TRUNCATE resets the counter in SQL Server and MySQL, but PostgreSQL keeps counting unless you write TRUNCATE ... RESTART IDENTITY.","SQL Server, MySQL and Oracle allow one auto-numbered column per table (Oracle raises ORA-30669 for a second); PostgreSQL accepts several identity columns in one table.","SQLite's AUTOINCREMENT keyword is not needed to get auto-numbering: a plain INTEGER PRIMARY KEY already does it. AUTOINCREMENT only forbids id reuse after deletes, at the cost of a sqlite_sequence lookup per insert.","Inserting explicit values behaves differently: SQL Server needs IDENTITY_INSERT toggled on, PostgreSQL identity columns refuse it by default, MySQL accepts it freely and bumps the counter.","An INT identity stops at 2,147,483,647 values, not rows: gaps from rollbacks, deletes and SQL Server's identity cache all spend numbers. High-churn tables (sessions, logs) should start at BIGINT."],"see_also":["uuid","sequence","integer","rowid"],"faqs":[{"question":"Why do my identity values skip numbers?","answer":"Rollbacks and failed inserts still consume values; SQL Server also caches ranges and throws away unused ones on restart. If a gap is unacceptable (order numbers, invoices), generate them in a transaction, not with a counter."},{"question":"Is SERIAL deprecated in PostgreSQL?","answer":"Not deprecated, but superseded. Identity columns are standard SQL, need no separate GRANT on the backing sequence, and in the ALWAYS form reject accidental explicit values."},{"question":"How do I copy rows into a table with an IDENTITY column?","answer":"Either toggle SET IDENTITY_INSERT on (SQL Server), use OVERRIDING SYSTEM VALUE (PostgreSQL), or just omit the key column and let new numbers be generated; the last option is usually what you want anyway."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE TABLE posts (id INT GENERATED ALWAYS AS IDENTITY);\nINSERT INTO posts OVERRIDING SYSTEM VALUE VALUES (500);\nINSERT INTO posts DEFAULT VALUES;\nSELECT id FROM posts;  -- 500, then 1: the sequence never saw the explicit 500"},{"engine_slug":"sql-server","sql":"CREATE TABLE posts (id INT IDENTITY(1,1));\nSET IDENTITY_INSERT posts ON;\nINSERT INTO posts (id) VALUES (500);\nSET IDENTITY_INSERT posts OFF;\nSELECT id FROM posts;"},{"engine_slug":"sqlite","sql":"CREATE TABLE posts (id INTEGER PRIMARY KEY);\nINSERT INTO posts DEFAULT VALUES;\nSELECT id FROM posts;  -- 1: the rowid counts; AUTOINCREMENT only forbids reuse"}]},"source_url":"https://sqlly.app/sql-data-types/identity","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/image-legacy","corpus":"sql-data-types","engine":null,"language":"en","title":"IMAGE and other deprecated binary types","description":"SQL Server's IMAGE and Oracle's LONG RAW are deprecated. What they were, why they block modern features, and how to migrate to VARBINARY(MAX) and BLOB.","body":{"slug":"image-legacy","name":"IMAGE (deprecated)","h1":"IMAGE and other deprecated binary types","family":"binary","lede":"Two engines shipped binary types they later regretted. SQL Server's IMAGE and Oracle's LONG RAW still work, still appear in old schemas, and both block features you probably want.","summary":"IMAGE (SQL Server, 2 GB) and LONG RAW (Oracle, 2 GB) are deprecated legacy blob types with real restrictions; the migration targets are VARBINARY(MAX) and BLOB.","variants":[{"engine_slug":"sql-server","type_name":"IMAGE","storage":"up to 2 GB","note":"Deprecated since 2005; the replacement is VARBINARY(MAX). IMAGE cannot be compared, sorted, grouped or used as a local variable.","has_native_type":true},{"engine_slug":"postgresql","type_name":"BYTEA","storage":"up to 1 GB","note":"No deprecated type to retire; BYTEA has always been the answer for binary data.","has_native_type":true},{"engine_slug":"mysql","type_name":"LONGBLOB","storage":"up to 4 GB","note":"No deprecated image type; LONGBLOB is the storage equivalent for legacy IMAGE columns.","has_native_type":true},{"engine_slug":"sqlite","type_name":"BLOB","storage":"up to 1 billion bytes","note":"One BLOB type from the start; nothing to migrate.","has_native_type":true},{"engine_slug":"oracle","type_name":"LONG RAW","storage":"up to 2 GB","note":"Deprecated: one LONG or LONG RAW column per table, no SQL functions on it, and no CREATE TABLE AS SELECT. Migrate to BLOB.","has_native_type":true}],"gotchas":["SQL Server's IMAGE fails in = comparisons, ORDER BY, GROUP BY and DISTINCT, cannot be a local variable, and needs READTEXT/WRITETEXT/UPDATETEXT for partial access. It has been deprecated since 2005.","Oracle LONG RAW allows only one per table, cannot be used in expressions or most functions, and the migration to BLOB is not a plain CAST - it needs ALTER TABLE MODIFY or a copy through a LOB operation.","The deprecated trio TEXT, NTEXT and IMAGE often appear together in old SQL Server schemas; all three migrate to VARCHAR(MAX), NVARCHAR(MAX) and VARBINARY(MAX) respectively.","ALTER TABLE t ALTER COLUMN c VARBINARY(MAX) converts in place, but old client code that calls READTEXT or WRITETEXT on the column breaks, so search the codebase before migrating."],"see_also":["blob-bytea","binary","raw-hex"],"faqs":[{"question":"What replaces IMAGE in SQL Server?","answer":"VARBINARY(MAX). It stores the same data, supports all functions and modern drivers, moves large values off-row automatically, and has no deprecated behavior."},{"question":"How do I migrate Oracle LONG RAW to BLOB?","answer":"Not with a plain CAST. Use ALTER TABLE ... MODIFY (col BLOB) or copy the data through TO_LOB in an INSERT ... SELECT, then drop the old column."},{"question":"Can I still create IMAGE columns?","answer":"In SQL Server yes, and tools still accept them, but new code should not: they are deprecated, restricted, and the eventual removal will break them."}],"examples":[{"engine_slug":"sql-server","sql":"CREATE TABLE old (pic IMAGE);\nINSERT INTO old VALUES (0x89504E47);\nSELECT pic FROM old WHERE pic = 0x89504E47;  -- error 306: IMAGE cannot be compared; VARBINARY(MAX) can"},{"engine_slug":"oracle","sql":"CREATE TABLE old (pic LONG RAW);\nINSERT INTO old VALUES ('89504E47');\nSELECT COUNT(*) FROM old;  -- one LONG RAW per table, no functions on it: the migration target is BLOB"}]},"source_url":"https://sqlly.app/sql-data-types/image-legacy","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/inet","corpus":"sql-data-types","engine":null,"language":"en","title":"IP address types (INET/CIDR)","description":"Storing IPs: PostgreSQL INET/CIDR natively, VARBINARY and text workarounds in MySQL, SQLite and Oracle.","body":{"slug":"inet","name":"IP address","h1":"IP address types (INET/CIDR)","family":"other","lede":"An IP column sorted as text sorts wrong: '10.0.0.9' after '10.0.0.10'. PostgreSQL fixes this with INET; the other engines fix it with binary packing functions you have to remember to use.","summary":"PostgreSQL's INET and CIDR are typed, sortable and netmask-aware. MySQL packs addresses into VARBINARY with INET6_ATON; SQL Server, SQLite and Oracle store text or bytes with no IP smarts at all.","variants":[{"engine_slug":"sql-server","type_name":"none (VARBINARY(16) or VARCHAR(45))","storage":"4-16 or up to 45 bytes","note":"No IP type and no conversion function. Pack the address to bytes in the application (.NET IPAddress.GetAddressBytes()) or store text and accept wrong sorting.","has_native_type":false},{"engine_slug":"postgresql","type_name":"INET / CIDR","storage":"7 or 19 bytes (inet)","note":"INET holds a host with optional netmask, CIDR a network; both sort correctly, support contains operators (>>), and family() distinguishes IPv4/6.","has_native_type":true},{"engine_slug":"mysql","type_name":"none (VARBINARY(16))","storage":"4 or 16 bytes","note":"Pack with INET6_ATON() into VARBINARY(16) (handles IPv4 and IPv6), unpack with INET6_NTOA(); the older INT + INET_ATON() is IPv4-only.","has_native_type":false},{"engine_slug":"sqlite","type_name":"none (TEXT)","storage":"up to 45 bytes","note":"No IP type or functions. Store canonical text; sort with a custom collation or in application code if order matters.","has_native_type":false},{"engine_slug":"oracle","type_name":"none (VARCHAR2)","storage":"up to 45 bytes","note":"No IP type. VARCHAR2 text storage; correct ordering needs a stored binary companion column or a sort key function.","has_native_type":false}],"gotchas":["Text-sorted IPs are misordered: '10.0.0.10' sorts before '10.0.0.9', and IPv6 text with :: compression does not sort by address at all. Any ORDER BY ip over a text column is quietly wrong.","MySQL's INET_ATON()/INT path only fits IPv4; mixing IPv6 in requires the VARBINARY(16) + INET6_ATON() pattern, and old columns using INT cannot hold v6 at all.","PostgreSQL CIDR rejects host bits that are set ('192.168.1.5/24'), while INET keeps them; picking the wrong one is a data-entry validation decision, not a storage one.","The engines without a type give no validation: '999.999.1.2' inserts without complaint into VARCHAR, TEXT and NVARCHAR columns everywhere.","IPv4-mapped IPv6 (::ffff:10.0.0.1) and 10.0.0.1 are one host in two notations, and no engine unifies them: PostgreSQL's '::ffff:10.0.0.1'::inet = '10.0.0.1'::inet is false. Normalize in the application."],"see_also":["point","uuid"],"faqs":[{"question":"What is the difference between INET and CIDR in PostgreSQL?","answer":"INET stores one host (or network) address and accepts a netmask, keeping host bits: 10.1.2.3/8 is valid. CIDR stores a network and rejects out-of-place host bits: 10.0.0.0/8 only. Both sort and index correctly."},{"question":"How should I store IPs in MySQL?","answer":"VARBINARY(16) with INET6_ATON() on write and INET6_NTOA() on read: it handles IPv4 and IPv6 in one column and sorts correctly because it is binary, not text."},{"question":"Can I just store IPs as VARCHAR?","answer":"You can, and many schemas do. You lose validation, correct ordering and subnet comparisons. If any of those matter, pack to binary (or use INET in PostgreSQL) instead."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE TABLE logins (ip INET);\nINSERT INTO logins VALUES ('10.0.0.9'), ('10.0.0.10');\nSELECT ip FROM logins ORDER BY ip;  -- 10.0.0.9 first: numeric order, not text order"},{"engine_slug":"mysql","sql":"CREATE TABLE logins (ip VARBINARY(16));\nINSERT INTO logins VALUES (INET6_ATON('10.0.0.9'));\nSELECT INET6_NTOA(ip) FROM logins;  -- 10.0.0.9: packed bytes sort correctly, an INT column cannot hold IPv6"},{"engine_slug":"sqlite","sql":"CREATE TABLE logins (ip TEXT);\nINSERT INTO logins VALUES ('10.0.0.9');\nSELECT ip FROM logins;  -- text: no validation, '999.999.1.2' goes in happily"}]},"source_url":"https://sqlly.app/sql-data-types/inet","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/integer","corpus":"sql-data-types","engine":null,"language":"en","title":"INTEGER (INT)","description":"The default whole-number type everywhere: 4 bytes and about +/-2.1 billion, with Oracle and SQLite quietly differing from the ANSI story.","body":{"slug":"integer","name":"INTEGER / INT","h1":"INTEGER (INT)","family":"integer","lede":"4 bytes, +/-2.1 billion, the type everyone reaches for first.","summary":"INT and INTEGER name a 4-byte type in three engines; Oracle's is a 38-digit NUMBER, and in SQLite only the exact spelling INTEGER PRIMARY KEY aliases the rowid.","variants":[{"engine_slug":"sql-server","type_name":"INT","storage":"4 bytes","note":"-2,147,483,648 to 2,147,483,647. INTEGER is an accepted spelling.","has_native_type":true},{"engine_slug":"postgresql","type_name":"INTEGER (INT, INT4)","storage":"4 bytes","note":"Three spellings, one 4-byte signed type.","has_native_type":true},{"engine_slug":"mysql","type_name":"INT","storage":"4 bytes","note":"INT(11)-style display width is deprecated since 8.0.17; INT UNSIGNED reaches 4,294,967,295.","has_native_type":true},{"engine_slug":"sqlite","type_name":"INTEGER","storage":"up to 8 bytes","note":"One integer type covering 1-8 byte values; INTEGER PRIMARY KEY aliases the rowid.","has_native_type":true},{"engine_slug":"oracle","type_name":"INTEGER (= NUMBER(38))","storage":"1-20 bytes","note":"ANSI INTEGER maps to NUMBER(38), not a 4-byte type; use NUMBER(10) for int-sized columns.","has_native_type":true}],"gotchas":["Oracle's INTEGER is NUMBER(38) in disguise: 38 digits, variable-length decimal storage, and fractional input rounded rather than rejected (1.5 becomes 2). NUMBER(10) caps it near INT's size.","In SQLite, INT PRIMARY KEY and INTEGER PRIMARY KEY are not the same: only the exact spelling INTEGER makes the key an alias for the rowid. INT PRIMARY KEY creates a separate column plus a unique index.","MySQL's INT(11) is display width, not size: the column is always 4 bytes, and the syntax is deprecated as of MySQL 8.0.17.","The 2.1 billion ceiling arrives faster than expected on event and audit tables: pick BIGINT before the painful migration."],"see_also":["bigint","smallint","serial","tinyint"],"faqs":[{"question":"Is INT the same as INTEGER?","answer":"Almost. SQL Server, PostgreSQL and MySQL treat them as one 4-byte type, and Oracle maps both to NUMBER(38). SQLite gives both INTEGER affinity, but only INTEGER PRIMARY KEY becomes the rowid alias."},{"question":"Why does Oracle's INTEGER accept huge values?","answer":"Because it resolves to NUMBER(38). Oracle treats the ANSI integer names as precision-unlimited numbers; constrain with NUMBER(10,0) to get INT semantics."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE TABLE events (id INTEGER);\nINSERT INTO events VALUES (2147483648);  -- error: integer out of range, BIGINT territory"},{"engine_slug":"oracle","sql":"CREATE TABLE t (n INTEGER);\nINSERT INTO t VALUES (1.5);\nSELECT n FROM t;  -- 2: NUMBER(38) rounds instead of rejecting"},{"engine_slug":"sqlite","sql":"CREATE TABLE t (id INTEGER PRIMARY KEY);\nINSERT INTO t DEFAULT VALUES;\nSELECT id FROM t;  -- 1: only the exact spelling INTEGER aliases the rowid"}]},"source_url":"https://sqlly.app/sql-data-types/integer","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/integer-money","corpus":"sql-data-types","engine":null,"language":"en","title":"Storing money as INTEGER","description":"The engine-proof money pattern: store integer minor units (cents), compute exactly, format to currency only at the edges of the system.","body":{"slug":"integer-money","name":"INTEGER money (cents)","h1":"Storing money as INTEGER","family":"exact","lede":"Store cents, not dollars - the one money recipe that works everywhere.","summary":"BIGINT (or NUMBER(20)) cents are exact in all five engines including SQLite, at the cost of handling currency minor units yourself.","variants":[{"engine_slug":"sql-server","type_name":"BIGINT","storage":"8 bytes","note":"Cents fit easily: BIGINT spans about +/-92 quadrillion dollars in cents.","has_native_type":true},{"engine_slug":"postgresql","type_name":"BIGINT","storage":"8 bytes","note":"Same recipe; pair with a view or generated column for dollar formatting.","has_native_type":true},{"engine_slug":"mysql","type_name":"BIGINT","storage":"8 bytes","note":"SUM() over BIGINT returns DECIMAL, so totals stay exact even past the 64-bit range.","has_native_type":true},{"engine_slug":"sqlite","type_name":"INTEGER","storage":"up to 8 bytes","note":"SQLite's native integer is the natural home for cents - there is no decimal type to prefer.","has_native_type":true},{"engine_slug":"oracle","type_name":"NUMBER(20)","storage":"1-11 bytes","note":"A 20-digit integer NUMBER dwarfs any realistic cent total.","has_native_type":true}],"gotchas":["Never store money in FLOAT or DOUBLE: 0.1 + 0.2 drifts. INTEGER cents and DECIMAL are the only safe homes.","Minor units differ per currency: JPY has no cents and BHD has three decimals, so a hardcoded division by 100 breaks both.","Sums of cents can overflow the application's integers (exact only to 2^53 in JavaScript) even when they fit in BIGINT. SQL Server's SUM over BIGINT returns BIGINT and raises an overflow error past 2^63; PostgreSQL and MySQL return NUMERIC/DECIMAL.","Round at the boundaries only: store exact cents and apply tax or proration rounding once per line, in one documented policy."],"see_also":["money","numeric-decimal","bigint"],"faqs":[{"question":"Why INTEGER over DECIMAL?","answer":"It behaves identically in all five engines including SQLite, sums exactly, and forces a single rounding policy into application code."},{"question":"What about currencies without cents?","answer":"Define the minor unit per currency - 1 for JPY, 1000 for BHD - and store that unit. The column is unit-agnostic; the formatter is not."}],"examples":[{"engine_slug":"sqlite","sql":"CREATE TABLE invoices (total_cents INTEGER);\nINSERT INTO invoices VALUES (1099);\nSELECT total_cents, total_cents / 100 FROM invoices;  -- 1099 | 10: compute in cents, format at the edges"},{"engine_slug":"oracle","sql":"CREATE TABLE invoices (total_cents NUMBER(20));\nINSERT INTO invoices VALUES (1099);\nSELECT total_cents / 100 AS dollars FROM invoices;  -- 10.99, exact to the last cent"}]},"source_url":"https://sqlly.app/sql-data-types/integer-money","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/interval","corpus":"sql-data-types","engine":null,"language":"en","title":"Interval types (spans of time)","description":"Time spans as data: PostgreSQL and Oracle INTERVAL types, and the numeric-second workarounds elsewhere.","body":{"slug":"interval","name":"Interval","h1":"Interval types (spans of time)","family":"other","lede":"'How long' is data: PostgreSQL and Oracle give durations a real type, while SQL Server, MySQL and SQLite store a number and remember which unit it counts.","summary":"Only PostgreSQL and Oracle have interval column types (with different field structures); elsewhere a duration is an integer of undocumented unit plus DATEADD-style arithmetic at the edges.","variants":[{"engine_slug":"sql-server","type_name":"none (numeric or datetime math)","storage":"4-8 bytes","note":"No interval type. Durations live as INT/BIGINT seconds or DECIMAL hours, or as the difference of two DATETIME2s via DATEDIFF; DATEADD applies them back.","has_native_type":false},{"engine_slug":"postgresql","type_name":"INTERVAL","storage":"16 bytes","note":"One type covering years to microseconds, internally months/days/seconds fields; '1 month' is stored as a month, not a fixed number of days.","has_native_type":true},{"engine_slug":"mysql","type_name":"none (INTERVAL keyword only)","storage":"n/a","note":"INTERVAL 1 DAY exists only inside expressions (DATE_ADD, DATE_SUB); there is no interval column type. Store numeric seconds or two DATETIME columns.","has_native_type":false},{"engine_slug":"sqlite","type_name":"none (numeric)","storage":"TEXT/REAL/INT","note":"No interval type; date math goes through modifiers ('+3 days') and julianday() differences. Store seconds (INT), days (REAL), or ISO 8601 duration text like 'P1DT2H' and interpret it yourself.","has_native_type":false},{"engine_slug":"oracle","type_name":"INTERVAL YEAR TO MONTH / DAY TO SECOND","storage":"5 / 11 bytes","note":"Two ANSI interval types with separate jobs: calendar spans (years/months) and exact spans (days/seconds). They cannot be added to each other directly.","has_native_type":true}],"gotchas":["PostgreSQL intervals are three fields, not a number of seconds: '1 month' + date arithmetic is calendar-aware (Jan 31 + 1 month lands Feb 28/29), so interval comparisons and sums can surprise ('1 month 30 days' vs '2 months').","Oracle splits intervals in two on purpose: months are not fixed lengths, so INTERVAL YEAR TO MONTH covers calendar spans and INTERVAL DAY TO SECOND exact ones; casting between them needs a date as the bridge.","MySQL's INTERVAL keyword only works inside date arithmetic: a column declared INTERVAL is a syntax error. Durations end up as integers, so put the unit in the column name (duration_ms).","SQL Server DATEDIFF counts boundaries crossed, not elapsed time: DATEDIFF(year, '2025-12-31', '2026-01-01') returns 1 for a one-day span, and DATEDIFF(hour, '10:59', '11:00') returns 1 for one minute.","SQLite's '+1 month' modifier overflows instead of clamping: date('2026-01-31', '+1 month') returns 2026-03-03. ISO 8601 durations (P1Y2M) stored as text need application-side parsing to compare or sum."],"see_also":["point","composite"],"faqs":[{"question":"What is the difference between PostgreSQL's INTERVAL and Oracle's two types?","answer":"PostgreSQL's INTERVAL mixes months, days and seconds in one value (calendar-aware month arithmetic). Oracle forces you to choose INTERVAL YEAR TO MONTH for calendar spans or INTERVAL DAY TO SECOND for exact durations, and the two do not mix directly."},{"question":"How do I store durations in MySQL or SQL Server?","answer":"Pick a unit and document it: INT seconds (or BIGINT milliseconds) is the portable answer. SQL Server can also persist start/end DATETIME2 pairs and compute with DATEDIFF; MySQL uses TIMESTAMPDIFF over two DATETIMEs."},{"question":"What happens when I add one month to January 31?","answer":"It depends on the engine. PostgreSQL, SQL Server DATEADD, MySQL DATE_ADD and Oracle ADD_MONTHS clamp to Feb 28 (or 29). Oracle's DATE + INTERVAL '1' MONTH raises ORA-01839, and SQLite's '+1 month' rolls over to March 3. Test month ends."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE TABLE plans (d INTERVAL);\nINSERT INTO plans VALUES ('1 month');\nSELECT DATE '2026-01-31' + d FROM plans;  -- 2026-02-28: months stay calendar-aware"},{"engine_slug":"oracle","sql":"CREATE TABLE plans (d INTERVAL DAY TO SECOND);\nINSERT INTO plans VALUES (INTERVAL '36' HOUR);\nSELECT d FROM plans;  -- +01 12:00:00: the other half is INTERVAL YEAR TO MONTH"},{"engine_slug":"sql-server","sql":"CREATE TABLE plans (duration_s INT);\nINSERT INTO plans VALUES (86400);\nSELECT DATEADD(SECOND, duration_s, '2026-02-14 00:00:00') FROM plans;  -- no interval type: a number plus DATEADD"}]},"source_url":"https://sqlly.app/sql-data-types/interval","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/interval-day-second","corpus":"sql-data-types","engine":null,"language":"en","title":"INTERVAL DAY TO SECOND","description":"Day-to-second intervals - elapsed time with hours, minutes and fractional seconds - across Oracle, PostgreSQL, MySQL, SQL Server and SQLite.","body":{"slug":"interval-day-second","name":"INTERVAL DAY TO SECOND","h1":"INTERVAL DAY TO SECOND","family":"datetime","lede":"A day-to-second interval measures elapsed time: 2 days, 4 hours, 30 minutes. It is what you want for durations, and every engine except Oracle and PostgreSQL makes you fake it.","summary":"Elapsed time down to fractional seconds. Oracle's INTERVAL DAY TO SECOND takes 11 bytes, PostgreSQL reuses its 16-byte INTERVAL, and the rest store seconds as integers or lean on TIME.","variants":[{"engine_slug":"sql-server","type_name":"TIME","storage":"3 to 5 bytes","note":"TIME(7) works as a duration only up to 23:59:59.9999999; larger spans need DATEDIFF or an integer of seconds.","has_native_type":true},{"engine_slug":"postgresql","type_name":"INTERVAL","storage":"16 bytes","note":"interval '2 days 04:30:00'; microsecond precision with separate days and microseconds fields.","has_native_type":true},{"engine_slug":"mysql","type_name":"TIME","storage":"3 bytes plus fractional","note":"TIME's -838:59:59 to 838:59:59 range makes it a signed duration; beyond 838 hours, store seconds in BIGINT.","has_native_type":true},{"engine_slug":"sqlite","type_name":"INTEGER","storage":"1 to 8 bytes","note":"Store elapsed seconds or milliseconds and format on display; no interval arithmetic beyond date modifiers.","has_native_type":true},{"engine_slug":"oracle","type_name":"INTERVAL DAY TO SECOND","storage":"11 bytes","note":"INTERVAL '2 04:30:00' DAY TO SECOND; day precision defaults to 2 digits, up to 9, with up to 9 fractional-second digits.","has_native_type":true}],"gotchas":["SQL Server's TIME is a clock time capped at 24 hours. Using it for durations works only inside one day, and negative durations are impossible - use DATEDIFF results instead.","MySQL's TIME goes the other way: it is effectively a signed interval of up to 838 hours, so a 'time of day' column can legally hold -12:30:00.","Oracle's default day precision is 2 digits, so a 100-day interval overflows until you declare INTERVAL '100 0:00:00' DAY(3) TO SECOND.","PostgreSQL's single INTERVAL mixes both families: interval '1 day' and interval '24 hours' compare equal, but adding them across a DST change in a timestamptz gives different results.","ISO SQL forbids mixing the two interval families in one value; if you need both, that is two columns, not one."],"see_also":["interval-year-month","time","timestamp"],"faqs":[{"question":"How do I store a duration in SQL Server?","answer":"Below 24 hours, TIME(7) works. Otherwise store the total in seconds (BIGINT) or use DATEDIFF between start and end columns - SQL Server has no INTERVAL type."},{"question":"How many bytes is INTERVAL DAY TO SECOND?","answer":"11 bytes in Oracle and 16 bytes for PostgreSQL's combined INTERVAL. Integer-second emulation costs 4 to 8 bytes elsewhere."},{"question":"What is the difference between MySQL TIME and an interval?","answer":"MySQL TIME behaves like a signed interval (up to 838 hours) rather than a clock time, which is unusual: in SQL Server and PostgreSQL, TIME is strictly time-of-day."}],"examples":[{"engine_slug":"oracle","sql":"CREATE TABLE runs (d INTERVAL DAY TO SECOND);\nINSERT INTO runs VALUES (INTERVAL '2 04:30:00' DAY TO SECOND);\nSELECT d FROM runs;  -- +02 04:30:00"},{"engine_slug":"postgresql","sql":"SELECT INTERVAL '2 days 04:30:00';  -- same intent, one general INTERVAL type"},{"engine_slug":"mysql","sql":"CREATE TABLE runs (d TIME);\nINSERT INTO runs VALUES ('26:00:00');\nSELECT d FROM runs;  -- 26:00:00: TIME doubles as a duration"}]},"source_url":"https://sqlly.app/sql-data-types/interval-day-second","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/interval-year-month","corpus":"sql-data-types","engine":null,"language":"en","title":"INTERVAL YEAR TO MONTH","description":"Year-to-month intervals across the five engines: Oracle's INTERVAL YEAR TO MONTH, PostgreSQL's single INTERVAL, and the integer-month emulation everywhere else.","body":{"slug":"interval-year-month","name":"INTERVAL YEAR TO MONTH","h1":"INTERVAL YEAR TO MONTH","family":"datetime","lede":"A year-to-month interval counts calendar months: 3 years, 6 months. It is the only interval that respects calendar length - a month is a month, not 30 days - and only Oracle gives it a real column type.","summary":"Whole months as a duration. Oracle stores it natively (INTERVAL YEAR TO MONTH, 5 bytes), PostgreSQL folds it into its 16-byte INTERVAL, and the other three engines store an integer month count.","variants":[{"engine_slug":"sql-server","type_name":"int (month count)","storage":"4 bytes","note":"No INTERVAL type. Store total months in an INT and rebuild dates with DATEADD(MONTH, months, d).","has_native_type":true},{"engine_slug":"postgresql","type_name":"INTERVAL","storage":"16 bytes","note":"One INTERVAL covers both interval families, with separate months, days and microseconds fields.","has_native_type":true},{"engine_slug":"mysql","type_name":"int (month count)","storage":"4 bytes","note":"INTERVAL exists only as expression syntax (SELECT INTERVAL '1' MONTH + d), not as a column type.","has_native_type":true},{"engine_slug":"sqlite","type_name":"INTEGER","storage":"1 to 8 bytes","note":"No interval support. Store the month count and add it with date(d, '+N months').","has_native_type":true},{"engine_slug":"oracle","type_name":"INTERVAL YEAR TO MONTH","storage":"5 bytes","note":"INTERVAL '3-6' YEAR TO MONTH; year precision defaults to 2 digits and goes up to 9.","has_native_type":true}],"gotchas":["Oracle splits intervals into YEAR TO MONTH and DAY TO SECOND because you cannot convert between them: 1 month is not 30 days. Choosing the wrong family loses calendar arithmetic.","PostgreSQL has a single INTERVAL for both families, kept as separate months, days and microseconds. Adding them to dates differs (Jan 31 + 1 month is Feb 28), yet comparison treats a month as 30 days: interval '1 month' = interval '30 days' is true.","Neither MySQL nor SQL Server has an interval column type. MySQL has INTERVAL only as expression syntax (DATE_ADD(d, INTERVAL 3 MONTH)); SQL Server has no INTERVAL at all, only DATEADD.","Oracle's default year precision is 2, so INTERVAL '100-0' YEAR TO MONTH fails until you write INTERVAL '100-0' YEAR(3) TO MONTH."],"see_also":["interval-day-second","date","timestamp"],"faqs":[{"question":"Why are there two interval types?","answer":"Because months and days do not convert cleanly: month lengths vary with the calendar. ISO SQL defines YEAR-MONTH intervals and DAY-SECOND intervals as separate families that cannot be mixed in one value."},{"question":"How do I store a subscription length in SQL Server?","answer":"Store the number of months in an INT and compute the end date with DATEADD(MONTH, @months, @start). That keeps month-end behavior consistent instead of guessing 30 days."},{"question":"How many bytes is INTERVAL YEAR TO MONTH?","answer":"5 bytes in Oracle. PostgreSQL's combined INTERVAL is 16 bytes; integer-month emulation is 4 bytes everywhere else."}],"examples":[{"engine_slug":"oracle","sql":"CREATE TABLE plans (d INTERVAL YEAR TO MONTH);\nINSERT INTO plans VALUES (INTERVAL '3-6' YEAR TO MONTH);\nSELECT d FROM plans;  -- +03-06"},{"engine_slug":"postgresql","sql":"SELECT INTERVAL '3 years 6 months';  -- the one general INTERVAL type; Oracle needs the YEAR TO MONTH spelling"},{"engine_slug":"sql-server","sql":"CREATE TABLE plans (months INT);\nINSERT INTO plans VALUES (42);\nSELECT DATEADD(MONTH, months, '2026-02-14') FROM plans;  -- 2028-08-14: the no-interval workaround"}]},"source_url":"https://sqlly.app/sql-data-types/interval-year-month","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/json","corpus":"sql-data-types","engine":null,"language":"en","title":"The JSON column type","description":"JSON columns: binary JSON in MySQL, Oracle 21c+ and SQL Server 2025, text with functions in older SQL Server and SQLite, and both kinds in PostgreSQL.","body":{"slug":"json","name":"JSON","h1":"The JSON column type","family":"semi","lede":"Half the engines give JSON a real type that validates and parses on write; the other half store text and call functions on read. Same data, very different write-time guarantees and index options.","summary":"PostgreSQL's json and jsonb, MySQL JSON and Oracle 21c+ JSON validate on write; SQL Server before 2025 and SQLite store text and validate only if you add a CHECK.","variants":[{"engine_slug":"sql-server","type_name":"NVARCHAR(MAX) with ISJSON","storage":"Up to 2 GB","note":"SQL Server 2025 and Azure SQL add a native json type; before that, store text, validate with ISJSON, extract with JSON_VALUE/JSON_QUERY, and index via computed columns.","has_native_type":true},{"engine_slug":"postgresql","type_name":"JSON","storage":"Textual, variable","note":"The text-preserving variant: validated on write, stored exactly as sent (whitespace and duplicate keys included), and re-parsed on every read. jsonb is the faster default.","has_native_type":true},{"engine_slug":"mysql","type_name":"JSON","storage":"Binary, variable","note":"Real JSON type since 5.7.8: validated and converted to binary on write, duplicate keys collapsed (last one wins in 8.0), partial in-place updates via JSON_SET and JSON_REPLACE.","has_native_type":true},{"engine_slug":"sqlite","type_name":"TEXT with JSON1 functions","storage":"TEXT limits","note":"No JSON type. TEXT storage, with json_valid(), json_extract() and friends (built in since 3.38, extension before); nothing stops invalid JSON in the column.","has_native_type":true},{"engine_slug":"oracle","type_name":"JSON type or VARCHAR2/CLOB","storage":"Variable, up to 32 MB (JSON type)","note":"21c+ has a native JSON type stored as OSON binary. From 12.1.0.2 to 19c, use VARCHAR2/CLOB/BLOB with an IS JSON check constraint for validation.","has_native_type":true}],"gotchas":["SQL Server had no JSON column type until SQL Server 2025. On 2016-2022 it is NVARCHAR(MAX) plus functions, and without a CHECK (ISJSON(col) = 1) a malformed document is only caught when a query parses it.","PostgreSQL's json type is not the 'better' one: it re-parses on every access and keeps duplicate keys. jsonb exists precisely because json is a niche choice (exact text, key order).","MySQL JSON columns cannot be indexed directly: index a generated column, a functional index on CAST(col->>'$.id' AS UNSIGNED) (8.0.13+), or a multi-valued index for arrays (8.0.17+).","SQLite's JSON functions became built-in only in 3.38 (2022); on older bundled builds (PHP, old Python) they may be missing entirely, and nothing validates the column's contents either way.","Oracle before 21c needs the IS JSON check constraint or the column is just text; without it, malformed rows insert fine and JSON_VALUE quietly returns NULL for them (its default is NULL ON ERROR)."],"see_also":["jsonb","xml","hstore"],"faqs":[{"question":"json or jsonb in PostgreSQL?","answer":"jsonb, almost always: it parses once on write, deduplicates keys, supports GIN indexes and containment queries. Choose json only when byte-exact text or key order must be preserved."},{"question":"How do I validate JSON in SQL Server or SQLite?","answer":"SQL Server: add a CHECK (ISJSON(col) = 1) constraint. SQLite: CHECK (json_valid(col) = 1). Without it, both engines store any string in the column."},{"question":"Can I index inside a JSON column?","answer":"PostgreSQL jsonb: yes, GIN indexes support containment natively. MySQL: index a generated column extracted from the JSON. SQL Server: computed column + index. SQLite: index an expression like json_extract(col, '$.id')."}],"examples":[{"engine_slug":"mysql","sql":"CREATE TABLE docs (j JSON);\nINSERT INTO docs VALUES ('{\"a\": 1, \"a\": 2}');\nSELECT j FROM docs;  -- {\"a\": 2}: validated, binary-packed, last duplicate key wins"},{"engine_slug":"sql-server","sql":"CREATE TABLE docs (j NVARCHAR(MAX) CHECK (ISJSON(j) = 1));\nINSERT INTO docs VALUES ('{\"a\": 1}');\nSELECT JSON_VALUE(j, '$.a') FROM docs;  -- 1: text plus functions before SQL Server 2025"},{"engine_slug":"sqlite","sql":"CREATE TABLE docs (j TEXT CHECK (json_valid(j)));\nINSERT INTO docs VALUES ('{\"a\": 1}');\nSELECT json_extract(j, '$.a') FROM docs;  -- 1: no JSON type, validation only if you write the CHECK"}]},"source_url":"https://sqlly.app/sql-data-types/json","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/jsonb","corpus":"sql-data-types","engine":null,"language":"en","title":"JSONB and binary JSON storage","description":"Binary JSON: PostgreSQL JSONB, MySQL's JSON, SQLite 3.45 JSONB format, and the engines without one.","body":{"slug":"jsonb","name":"JSONB","h1":"JSONB and binary JSON storage","family":"semi","lede":"JSONB means parse once on write, query fast on read. PostgreSQL coined the name, MySQL's JSON already works that way, SQLite added a JSONB blob format in 3.45, and SQL Server got a binary json type in 2025.","summary":"Binary JSON trades write cost and exact text for faster reads and indexability. PostgreSQL JSONB is the reference; MySQL JSON and Oracle's OSON JSON are the same idea under other names.","variants":[{"engine_slug":"sql-server","type_name":"json (2025) or NVARCHAR(MAX)","storage":"Variable","note":"SQL Server 2025 adds a native json type (binary, like JSONB). On 2022 and earlier, NVARCHAR(MAX) plus functions is the only option.","has_native_type":true},{"engine_slug":"postgresql","type_name":"JSONB","storage":"Binary, variable","note":"Decomposed tree on disk, duplicate keys collapsed (last wins), insignificant whitespace dropped; GIN-indexable for @> containment. The default choice for JSON columns.","has_native_type":true},{"engine_slug":"mysql","type_name":"JSON (already binary)","storage":"Binary, variable","note":"MySQL's JSON type stores parsed binary from day one, so it plays jsonb's role; there is no separate jsonb name.","has_native_type":true},{"engine_slug":"sqlite","type_name":"BLOB (JSONB format)","storage":"BLOB limits","note":"3.45 added JSONB: jsonb() converts text to a binary BLOB that the json_* functions read without re-parsing. There is no JSONB column type; the BLOB is just a value.","has_native_type":true},{"engine_slug":"oracle","type_name":"JSON type (OSON)","storage":"Binary, variable","note":"Native JSON since 21c stores as OSON, an Oracle binary JSON encoding; 23ai adds JSON Schema validation and JSON-relational duality views.","has_native_type":true}],"gotchas":["PostgreSQL JSONB does not preserve key order, whitespace or duplicate keys: round-tripping a document through jsonb silently rewrites it. If a diff or signature depends on the text, store the text too.","SQLite's JSONB is not a column type: it is a BLOB value that only SQLite understands. Storing it on disk is allowed, but the docs tell applications not to read or build the format outside SQLite.","SQL Server 2025's json type is new enough that most code targets NVARCHAR(MAX); ORMs and drivers that assume the old model need the type mapping checked before you adopt it.","MySQL sorts out duplicate keys at write time too: since 8.0.3 the last duplicate wins, as in jsonb, while 5.7 kept the first. Data migrated from 5.7 can read differently.","GIN indexes on PostgreSQL JSONB make writes slower and bigger; indexing every key by default is a common way to turn a fast column into the table's write bottleneck."],"see_also":["json","hstore","xml"],"faqs":[{"question":"Is jsonb always better than json in PostgreSQL?","answer":"For querying, yes. json wins only if you must return byte-identical documents (key order, duplicate keys) or log the exact payload received. Both validate on write."},{"question":"Does MySQL have a jsonb type?","answer":"No, and it does not need one: MySQL's JSON type has stored parsed binary JSON since 5.7, which is what jsonb does. The names differ, the behavior matches."},{"question":"What is SQLite's JSONB then?","answer":"A binary format introduced in 3.45: jsonb(text) produces it, the json_* and jsonb_* functions consume it without re-parsing, and it can be stored in a BLOB column. Applications are told not to read or write the format themselves."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE TABLE docs (j JSONB);\nINSERT INTO docs VALUES ('{\"a\": 1, \"a\": 2}');\nSELECT j FROM docs;  -- {\"a\": 2}: parsed once on write, GIN-indexable"},{"engine_slug":"sqlite","sql":"CREATE TABLE docs (j BLOB);\nINSERT INTO docs VALUES (jsonb('{\"a\": 1}'));\nSELECT json_extract(j, '$.a') FROM docs;  -- 1: the 3.45 binary format is a BLOB value, not a column type"},{"engine_slug":"oracle","sql":"CREATE TABLE docs (j JSON);\nINSERT INTO docs VALUES ('{\"a\": 1}');\nSELECT j.a FROM docs;  -- 1: 21c+ stores OSON binary under the JSON type"}]},"source_url":"https://sqlly.app/sql-data-types/jsonb","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/money","corpus":"sql-data-types","engine":null,"language":"en","title":"MONEY","description":"Dedicated money types in SQL Server and PostgreSQL, and why MySQL, SQLite and Oracle all reach for DECIMAL or NUMBER instead.","body":{"slug":"money","name":"MONEY","h1":"MONEY","family":"exact","lede":"Only SQL Server and PostgreSQL ship a native MONEY type; MySQL, SQLite and Oracle reach for DECIMAL(19,4), INTEGER cents or NUMBER(19,4) instead.","summary":"SQL Server MONEY (8 bytes, scale 4) and PostgreSQL's locale-aware MONEY; the other three engines use DECIMAL(19,4) or NUMBER(19,4).","variants":[{"engine_slug":"sql-server","type_name":"MONEY / SMALLMONEY","storage":"8 / 4 bytes","note":"Fixed scale 4; MONEY spans about +/-922 trillion, SMALLMONEY about +/-214,748.3647.","has_native_type":true},{"engine_slug":"postgresql","type_name":"MONEY","storage":"8 bytes","note":"No precision modifier: the number of decimals and the currency symbol both come from the lc_monetary setting.","has_native_type":true},{"engine_slug":"mysql","type_name":"no MONEY - use DECIMAL(19,4)","storage":"9 bytes","note":"The idiomatic money column is DECIMAL with scale 4 (or 2).","has_native_type":false},{"engine_slug":"sqlite","type_name":"no MONEY - use INTEGER cents","storage":"variable","note":"Common recipes: INTEGER minor units, or NUMERIC plus application rounding.","has_native_type":false},{"engine_slug":"oracle","type_name":"no MONEY - use NUMBER(19,4)","storage":"1-11 bytes","note":"NUMBER(19,4) is the standard stand-in.","has_native_type":false}],"gotchas":["SQL Server's MONEY keeps 4 decimals through every intermediate step: CAST(1 AS MONEY) / CAST(3 AS MONEY) * 3 returns 0.9999. DECIMAL(p,s) widens intermediate scale, so it is the safer default for financial math.","PostgreSQL's MONEY is locale-aware: a dump taken with one lc_monetary and restored under another can misread the values. Most teams use NUMERIC instead.","Three of the five engines have no MONEY at all, so a portable schema means DECIMAL(19,4) / NUMBER(19,4) from the start.","MONEY columns accept more decimals than they keep: SQL Server silently rounds to 4 places on insert."],"see_also":["numeric-decimal","integer-money"],"faqs":[{"question":"Should I use MONEY or DECIMAL for money?","answer":"Prefer DECIMAL/NUMERIC. MONEY's fixed scale and, in PostgreSQL, locale-dependent output make it a reliable source of surprises."},{"question":"What is SQL Server SMALLMONEY?","answer":"A 4-byte money type with scale 4 and a range of -214,748.3648 to 214,748.3647."}],"examples":[{"engine_slug":"sql-server","sql":"CREATE TABLE prices (p MONEY);\nINSERT INTO prices VALUES (1);\nSELECT CAST(p AS MONEY) / CAST(3 AS MONEY) * 3 FROM prices;  -- 0.9999: scale 4 follows every step"},{"engine_slug":"postgresql","sql":"SHOW lc_monetary;\nSELECT '12.30'::money;  -- $12.30 or 12,30, depending on the locale"},{"engine_slug":"mysql","sql":"CREATE TABLE prices (p DECIMAL(19,4));\nINSERT INTO prices VALUES (12.3);\nSELECT p FROM prices;  -- 12.3000: the stand-in money column keeps 4 places"}]},"source_url":"https://sqlly.app/sql-data-types/money","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/numeric-decimal","corpus":"sql-data-types","engine":null,"language":"en","title":"NUMERIC and DECIMAL","description":"Exact fixed-point decimals for money and measurements: NUMERIC(p,s) and DECIMAL(p,s), their size limits, and where SQLite falls short.","body":{"slug":"numeric-decimal","name":"NUMERIC / DECIMAL","h1":"NUMERIC and DECIMAL","family":"exact","lede":"NUMERIC and DECIMAL are exact synonyms in SQL Server, PostgreSQL, MySQL and Oracle; SQLite's NUMERIC affinity quietly stores floats, so 0.1 drifts.","summary":"SQL Server, PostgreSQL, MySQL and Oracle all have true exact decimals; SQLite's NUMERIC affinity silently degrades to floats.","variants":[{"engine_slug":"sql-server","type_name":"DECIMAL(p,s) / NUMERIC","storage":"5-17 bytes","note":"Exact synonyms; precision 1-38. Storage is 5 bytes up to p=9, 9 to p=19, 13 to p=28, 17 to p=38.","has_native_type":true},{"engine_slug":"postgresql","type_name":"NUMERIC(p,s) / DECIMAL(p,s)","storage":"2 bytes per 4 digits + 3-8 bytes","note":"Declared precision up to 1,000; unconstrained NUMERIC holds up to 131,072 digits before and 16,383 after the point.","has_native_type":true},{"engine_slug":"mysql","type_name":"DECIMAL(p,s)","storage":"variable, ~4 bytes per 9 digits","note":"NUMERIC is a synonym; precision up to 65, scale up to 30.","has_native_type":true},{"engine_slug":"sqlite","type_name":"NUMERIC (affinity)","storage":"variable (INTEGER or REAL)","note":"No true decimal: NUMERIC affinity stores values as INTEGER or IEEE REAL, so 0.1 drifts.","has_native_type":true},{"engine_slug":"oracle","type_name":"NUMBER(p,s)","storage":"variable, 1-20 bytes","note":"NUMBER covers integers and decimals alike; precision 1-38.","has_native_type":true}],"gotchas":["SQLite has no exact decimal: a NUMERIC column keeps 0.1 as an 8-byte float. Store cents as INTEGER or use a decimal extension.","NUMERIC and DECIMAL are exact synonyms in SQL Server, PostgreSQL and MySQL alike; the type underneath differs per engine, the guarantee does not.","Extra fractional digits are rounded, not rejected, in all four exact engines: 1.005 into DECIMAL(4,2) or NUMBER(4,2) stores 1.01. Only too many integer digits raise an error.","MySQL clamps out-of-range DECIMAL values to the endpoint with a warning unless strict mode (the default since 5.7) is on."],"see_also":["money","integer-money","double-precision","real"],"faqs":[{"question":"Are NUMERIC and DECIMAL different?","answer":"No, in every engine covered here they are synonyms for the same exact type. The standard distinguishes their required precision; no implementation does."},{"question":"How do I store money exactly in SQLite?","answer":"Store integer cents in an INTEGER column, or load a decimal extension. NUMERIC affinity will not protect you from binary float drift."},{"question":"What does NUMERIC(p,s) mean?","answer":"p is the total number of significant digits, s how many sit right of the decimal point. NUMERIC(6,2) holds up to 9,999.99."}],"examples":[{"engine_slug":"sql-server","sql":"CREATE TABLE rates (r DECIMAL(4,2));\nINSERT INTO rates VALUES (1.005);\nSELECT r FROM rates;  -- 1.01: extra digits round, they are not rejected"},{"engine_slug":"postgresql","sql":"SELECT 0.1::numeric + 0.2::numeric = 0.3::numeric AS exact;  -- t: exact decimal arithmetic"},{"engine_slug":"sqlite","sql":"CREATE TABLE t (p NUMERIC);\nINSERT INTO t VALUES (0.1);\nSELECT typeof(p) FROM t;  -- real: NUMERIC affinity quietly became a float"}]},"source_url":"https://sqlly.app/sql-data-types/numeric-decimal","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/oid","corpus":"sql-data-types","engine":null,"language":"en","title":"OIDs and other internal system identifiers","description":"PostgreSQL's OID, SQLite's oid alias, Oracle XID and how engines identify their own objects.","body":{"slug":"oid","name":"OID & system ids","h1":"OIDs and other internal system identifiers","family":"identifier","lede":"Engines need internal ids for their own objects and transactions: PostgreSQL's OID is the famous one, Oracle's XID names a transaction, and the others keep such bookkeeping out of your SQL.","summary":"PostgreSQL's OID is a 32-bit object id from the old days: still everywhere in system catalogs, gone from ordinary user tables. SQLite's oid is just an alias for rowid; Oracle's XID tracks transactions.","variants":[{"engine_slug":"sql-server","type_name":"object_id (int)","storage":"4 bytes (int)","note":"No column-level OIDs; objects carry an int object_id in sys.objects (OBJECT_ID('dbo.t') looks it up), and transactions a bigint transaction_id in sys.dm_tran_active_transactions.","has_native_type":true},{"engine_slug":"postgresql","type_name":"OID","storage":"4 bytes","note":"Unsigned 32-bit id for every system object: tables, types, functions. WITH OIDS stopped being the default for user tables in 8.1 and was removed in 12.","has_native_type":true},{"engine_slug":"mysql","type_name":"none","storage":"n/a","note":"Objects are identified by name; InnoDB's internal TABLE_ID shows up in information_schema.INNODB_TABLES, but there is no system id type to use in SQL.","has_native_type":false},{"engine_slug":"sqlite","type_name":"oid (rowid alias)","storage":"1-8 bytes","note":"'oid' is only a historical alias for the rowid; SQLite has no object-id concept. Name a column oid and the alias disappears for that table.","has_native_type":true},{"engine_slug":"oracle","type_name":"OBJECT_ID / XID","storage":"NUMBER / RAW(8)","note":"Objects have a NUMBER OBJECT_ID in USER_OBJECTS; transactions carry an 8-byte XID (undo segment, slot, sequence) visible in V$TRANSACTION.","has_native_type":true}],"gotchas":["PostgreSQL OIDs are unsigned 32-bit and can wrap around, values below 16384 are reserved for built-in objects, and a dump and restore assigns new ones. Never store an OID as a lasting reference to a table.","WITH OIDS was removed in PostgreSQL 12: a dump from an older server that creates tables WITH OIDS fails to load, and queries that read the hidden oid column need an explicit key instead.","SQLite's oid alias breaks if you declare a column literally named oid: the alias is shadowed and old queries reading 'oid' as the rowid start returning your data instead.","Oracle's XID identifies a transaction, not a row. ORA_ROWSCN is a row's commit SCN, but without ROWDEPENDENCIES on the table it is tracked per block, so every row in a block reports the latest change.","SQL Server's object_id() returns an int that is only unique per database, not per server; joining catalogs across databases on object_id alone is a bug."],"see_also":["rowid","uuid","identity"],"faqs":[{"question":"What is an OID in PostgreSQL, in one sentence?","answer":"An unsigned 32-bit id the system assigns to every object it creates: tables, types, functions. You meet it in catalogs (pg_class.oid, regtype casts), not in your own tables, which stopped having one in PostgreSQL 12."},{"question":"How do I find a table's OID?","answer":"SELECT 'mytable'::regclass::oid, or look up pg_class WHERE relname = 'mytable'. The regclass cast is the tidy way and handles schema qualification."},{"question":"My old query says SELECT oid FROM mytable and now fails. Why?","answer":"On pre-12 PostgreSQL the table was created WITH OIDS and had a hidden oid column; PostgreSQL 12 and later cannot create one. Replace it with an explicit primary key."}],"examples":[{"engine_slug":"postgresql","sql":"SELECT 'pg_class'::regclass::oid;  -- a 4-byte system id; user tables stopped having an oid column in 12"},{"engine_slug":"sqlite","sql":"CREATE TABLE t (v TEXT);\nINSERT INTO t VALUES ('a');\nSELECT oid FROM t;  -- 1: just an alias for the rowid, nothing to do with object ids"},{"engine_slug":"oracle","sql":"SELECT OBJECT_ID FROM USER_OBJECTS WHERE OBJECT_NAME = 'DUAL';  -- a NUMBER object id, unique per database"}]},"source_url":"https://sqlly.app/sql-data-types/oid","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/point","corpus":"sql-data-types","engine":null,"language":"en","title":"Point and basic spatial types","description":"Storing points: PostgreSQL's bare POINT, MySQL/SQL Server spatial types, Oracle SDO_GEOMETRY.","body":{"slug":"point","name":"Point & spatial","h1":"Point and basic spatial types","family":"other","lede":"A coordinate pair seems simple, and every engine stores one differently: PostgreSQL's built-in POINT is plain 2-D geometry, while MySQL, SQL Server, Oracle and SpatiaLite spatial types carry an SRID.","summary":"For a lone (x, y), PostgreSQL has a lightweight POINT type and the others reach for full spatial types; for anything with a map, all five want their spatial machinery and a declared SRID.","variants":[{"engine_slug":"sql-server","type_name":"geometry / geography Point","storage":"22 bytes approx","note":"Two spatial types: geometry (planar) and geography (ellipsoidal), built from WKT with STPointFromText or Point(); methods like STDistance differ between them.","has_native_type":true},{"engine_slug":"postgresql","type_name":"POINT","storage":"16 bytes","note":"A plain geometric (x, y) pair of float8 with operators such as <-> (distance) and <@ (contained in a box) but no SRID; real GIS wants PostGIS geometry/geography.","has_native_type":true},{"engine_slug":"mysql","type_name":"POINT","storage":"25 bytes","note":"4-byte SRID plus 21-byte WKB. Spatial types date back to 4.1; MySQL 8.0 added the column SRID attribute, geographic SRID math, and rejects SRID mismatches.","has_native_type":true},{"engine_slug":"sqlite","type_name":"none (SpatiaLite)","storage":"n/a","note":"No spatial types built in; the SpatiaLite extension adds geometry columns, R-tree indexes and the ST_ functions, but plain SQLite stores coordinates as two REAL columns.","has_native_type":false},{"engine_slug":"oracle","type_name":"SDO_GEOMETRY","storage":"~100+ bytes","note":"Oracle Spatial's object type: coordinates plus SDO_SRID, SDO_POINT and index metadata in USER_SDO_GEOM_METADATA; far heavier than a point needs.","has_native_type":true}],"gotchas":["PostgreSQL POINT has no SRID and no geography semantics: point(-73.98, 40.75) <-> point(-0.12, 51.5) returns a distance in degrees. Meters need PostGIS geography or hand-written great-circle SQL.","SQL Server's geometry and geography types are not interchangeable: geography distances are meters on the ellipsoid, geometry are planar units, and casting between them is a projection, not a cast.","MySQL 8 enforces SRIDs strictly: mixing SRID 4326 and 0 values in one function call is an error, while 5.7 computed everything as flat Cartesian, so the same query can error or return meters after an upgrade.","Oracle SDO_GEOMETRY drags metadata with it: you must register dimensions in USER_SDO_GEOM_METADATA before spatial indexes work, a step no other engine requires.","SQLite has no spatial functions unless SpatiaLite is loaded, which many deployments cannot do; the built-in R*Tree module can still index bounding boxes over two REAL columns."],"see_also":["inet","composite","interval"],"faqs":[{"question":"PostgreSQL POINT or PostGIS geometry?","answer":"POINT for abstract 2-D coordinates (screen positions, floor plans) where units are yours to define; PostGIS geometry/geography the moment SRIDs, areas, buffers, or real-world maps appear."},{"question":"How do I store latitude and longitude in MySQL?","answer":"A POINT column with SRID 4326 and a SPATIAL index, or two DECIMAL(9,6) columns if you only filter and sort numerically. Avoid 4-byte FLOAT: near 180 degrees it keeps only about 5 decimals, roughly a meter."},{"question":"Why is Oracle SDO_GEOMETRY so much bigger than a point?","answer":"It is an object type carrying SRID, element info and coordinate arrays for shapes beyond points, plus registration metadata. A lone point in SDO_POINT_TYPE still pays the wrapper's overhead."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE TABLE pins (p POINT);\nINSERT INTO pins VALUES ('(40.75, -73.98)');\nSELECT p <-> '(0, 0)' FROM pins;  -- degrees, not meters: no SRID on a bare POINT"},{"engine_slug":"mysql","sql":"CREATE TABLE pins (p POINT SRID 4326);\nINSERT INTO pins VALUES (ST_GeomFromText('POINT(40.75 -73.98)', 4326));\nSELECT ST_X(p) FROM pins;  -- 40.75: the SRID is checked on write since 8.0"},{"engine_slug":"sql-server","sql":"CREATE TABLE pins (p geometry);\nINSERT INTO pins VALUES (geometry::STGeomFromText('POINT(1 2)', 0));\nSELECT p.STX FROM pins;  -- 1: planar geometry; geography does the ellipsoidal math"}]},"source_url":"https://sqlly.app/sql-data-types/point","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/raw-hex","corpus":"sql-data-types","engine":null,"language":"en","title":"RAW and hex literals","description":"How each engine writes and converts raw bytes: 0x literals, X'...' strings, BYTEA hex format, and Oracle's HEXTORAW and RAWTOHEX.","body":{"slug":"raw-hex","name":"RAW and hex literals","h1":"RAW and hex literals","family":"binary","lede":"Every engine can express bytes as hex text, but each picked its own literal syntax and its own conversion functions. Moving a script between engines is a translation exercise.","summary":"SQL Server and MySQL use 0x hex literals, SQLite uses X'...', PostgreSQL outputs bytea as \\x hex, and Oracle's RAW type converts with HEXTORAW and RAWTOHEX.","variants":[{"engine_slug":"sql-server","type_name":"VARBINARY(n)","storage":"n + 2 bytes","note":"Hex literals like 0xAB12; CONVERT(varchar(max), value, 1) renders hex text with 0x, style 2 without it.","has_native_type":true},{"engine_slug":"postgresql","type_name":"BYTEA","storage":"n + 1 or 4 bytes","note":"Input and output in hex ('\\xAB12') by default since 9.0; decode('ab12', 'hex') and encode(value, 'hex') convert.","has_native_type":true},{"engine_slug":"mysql","type_name":"BINARY(n)","storage":"n bytes","note":"0x hex literals; HEX() returns uppercase hex text and UNHEX() parses it back to bytes.","has_native_type":true},{"engine_slug":"sqlite","type_name":"BLOB","storage":"n bytes","note":"X'AB12' blob literals; hex() renders a blob as uppercase hex text and unhex() (3.41+) parses it back. CAST('AB12' AS BLOB) returns the 4 text bytes, not 2.","has_native_type":true},{"engine_slug":"oracle","type_name":"RAW(n)","storage":"n bytes","note":"HEXTORAW('AB12') builds bytes, RAWTOHEX converts back; RAW input and output are hex by default.","has_native_type":true}],"gotchas":["PostgreSQL changed bytea output from escape format to hex ('\\x' prefix) in 9.0; old drivers and parsers that expect escape format break against modern servers.","SQLite's X'...' literal requires an even number of hex digits and is only valid as a blob literal - X'ABC' is a syntax error, not three bytes.","MySQL's HEX() doubles the length and returns uppercase text; UNHEX() pads odd-length input with a leading zero (UNHEX('ABC') is 0x0ABC) and returns NULL for non-hex characters.","SQL Server's CONVERT(varchar, b, 2) truncates at 30 characters because bare varchar means varchar(30): a 32-byte hash comes back as 15 bytes of hex. Write varchar(max) or an explicit length.","Oracle converts implicitly between RAW and hex strings: inserting 'AB12' into a RAW column stores 2 bytes, and selecting RAW into a VARCHAR2 yields hex text. The other engines need an explicit function."],"see_also":["binary","blob-bytea","image-legacy"],"faqs":[{"question":"How do I write binary data as a literal?","answer":"SQL Server and MySQL: 0xAB12. SQLite: X'AB12'. PostgreSQL: '\\xAB12'::bytea or decode('ab12','hex'). Oracle: HEXTORAW('AB12')."},{"question":"How do I convert a BLOB to hex text?","answer":"PostgreSQL: encode(b, 'hex'). MySQL: HEX(b). SQLite: hex(b). SQL Server: CONVERT(varchar(max), b, 2). Oracle: RAWTOHEX(b) for RAW, or RAWTOHEX(DBMS_LOB.SUBSTR(b, 2000, 1)) for a BLOB chunk."},{"question":"Why does my bytea output start with \\x?","answer":"PostgreSQL 9.0 switched bytea's default output to hex format with a \\x prefix. The setting bytea_output controls it, and escape format is still available for old clients."}],"examples":[{"engine_slug":"oracle","sql":"SELECT HEXTORAW('AB12'), RAWTOHEX(HEXTORAW('AB12')) FROM dual;  -- converts both ways; inserting 'AB12' into RAW stores 2 bytes"},{"engine_slug":"sqlite","sql":"SELECT hex(X'AB12');  -- AB12: X literals want an even digit count, X'ABC' is a syntax error"},{"engine_slug":"sql-server","sql":"DECLARE @b VARBINARY(MAX) = 0xAB12;\nSELECT CONVERT(varchar(max), @b, 2);  -- AB12: style 2 without the 0x prefix"}]},"source_url":"https://sqlly.app/sql-data-types/raw-hex","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/real","corpus":"sql-data-types","engine":null,"language":"en","title":"REAL (FLOAT4)","description":"Single-precision IEEE 754 floats: 4 bytes, about 7 significant digits. Oracle calls it BINARY_FLOAT, and SQLite stores an 8-byte double instead.","body":{"slug":"real","name":"REAL / FLOAT4","h1":"REAL (FLOAT4)","family":"approx","lede":"REAL is a 4-byte IEEE single in SQL Server, PostgreSQL and MySQL, but SQLite quietly stores a full 8-byte double and Oracle's REAL is a NUMBER-based FLOAT(63).","summary":"REAL is IEEE single precision in SQL Server, PostgreSQL and MySQL; SQLite only has doubles and Oracle's REAL is a NUMBER in disguise.","variants":[{"engine_slug":"sql-server","type_name":"REAL","storage":"4 bytes","note":"IEEE 754 single precision, about 7 digits; FLOAT(24) names the same type.","has_native_type":true},{"engine_slug":"postgresql","type_name":"REAL (FLOAT4)","storage":"4 bytes","note":"6 decimal digits of precision; FLOAT(p) with p <= 24 also picks REAL.","has_native_type":true},{"engine_slug":"mysql","type_name":"FLOAT","storage":"4 bytes","note":"Single precision; FLOAT(p) with p <= 24 is FLOAT, 25-53 becomes DOUBLE.","has_native_type":true},{"engine_slug":"sqlite","type_name":"REAL (8-byte double)","storage":"8 bytes","note":"No single precision exists: every REAL is a full 8-byte double.","has_native_type":true},{"engine_slug":"oracle","type_name":"BINARY_FLOAT","storage":"4 bytes","note":"Oracle's REAL keyword maps to FLOAT(63), a NUMBER-based decimal float; BINARY_FLOAT is the true 4-byte IEEE type.","has_native_type":true}],"gotchas":["SQLite stores every REAL as an 8-byte double: a column declared REAL costs 8 bytes per value even when the source was a 4-byte float.","Oracle's REAL is not IEEE: it is FLOAT(63), decimal floating point on NUMBER. Ask for BINARY_FLOAT when you want 4-byte IEEE behavior.","7 digits runs out fast: 16,777,217 (2^24 + 1) is the first integer a REAL cannot store, so IDs and money do not belong here.","MySQL's FLOAT(M,D) decimal syntax is deprecated as of 8.0.17: use plain FLOAT and format in the application."],"see_also":["double-precision","binary-float","numeric-decimal"],"faqs":[{"question":"How many digits does REAL hold?","answer":"About 6-7 significant decimal digits. Anything past that is rounded on write."},{"question":"Why is my REAL column 8 bytes in SQLite?","answer":"SQLite has exactly one float representation, the 8-byte IEEE double, regardless of the declared type."}],"examples":[{"engine_slug":"postgresql","sql":"SELECT 16777217::real;  -- 1.67772e+07: 2^24 + 1 is the first integer REAL rounds"},{"engine_slug":"sqlite","sql":"CREATE TABLE t (v REAL);\nINSERT INTO t VALUES (1.5);\nSELECT typeof(v) FROM t;  -- real: an 8-byte double, whatever single precision you meant"},{"engine_slug":"oracle","sql":"SELECT CAST(1.5 AS BINARY_FLOAT) FROM dual;  -- the true 4-byte IEEE single; the REAL keyword means FLOAT(63), a decimal NUMBER"}]},"source_url":"https://sqlly.app/sql-data-types/real","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/rowid","corpus":"sql-data-types","engine":null,"language":"en","title":"Rowids and hidden row identifiers","description":"Hidden per-row addresses: Oracle ROWID, SQLite rowid, PostgreSQL ctid, and SQL Server's lack of one.","body":{"slug":"rowid","name":"Rowid","h1":"Rowids and hidden row identifiers","family":"identifier","lede":"Under every heap and table there is a physical handle for a row: an address you can select, sometimes select by, and never build an API on, because rows move and ids get reused.","summary":"Oracle exposes ROWID, SQLite exposes rowid, PostgreSQL offers ctid, MySQL hides its clustered key, and SQL Server has no equivalent pseudo-column worth using.","variants":[{"engine_slug":"sql-server","type_name":"none","storage":"n/a","note":"No rowid pseudo-column. Heaps have an internal RID (visible only through %%physloc%% or sys.dm_db_database_page_allocations), but it is undocumented in use and unstable.","has_native_type":false},{"engine_slug":"postgresql","type_name":"ctid (system column)","storage":"6 bytes","note":"Physical location as (page, item); selectable like any column. Moves on every VACUUM FULL or UPDATE that relocates the tuple; never persist it.","has_native_type":true},{"engine_slug":"mysql","type_name":"none (hidden PK)","storage":"6 bytes","note":"InnoDB is index-organized: the clustered key (your PK, or a hidden 6-byte GEN_CLUST_INDEX row id) is the address, but SQL cannot reference it.","has_native_type":false},{"engine_slug":"sqlite","type_name":"ROWID","storage":"1-8 bytes (varint)","note":"Every ordinary table has a rowid; new rows get max(rowid)+1, so deleted ids can come back unless AUTOINCREMENT is set. 'oid' and '_rowid_' are aliases, unless a real column shadows them.","has_native_type":true},{"engine_slug":"oracle","type_name":"ROWID / UROWID","storage":"10 bytes (typical)","note":"Encodes file, block and slot; the fastest way to address one row and the fastest way to break a stored pointer, since MOVE and shrink rewrites it. UROWID covers index-organized tables.","has_native_type":true}],"gotchas":["Rowids are addresses, not identities: they change on table rewrites (Oracle ALTER TABLE MOVE, PostgreSQL VACUUM FULL, SQLite VACUUM on a table without an INTEGER PRIMARY KEY), and ids of deleted rows can be handed out again.","SQLite gives you three interchangeable names for the same value: rowid, oid and _rowid_. A user column named 'oid' silently shadows the alias, which surprises anyone porting old code that assumed oid was the rowid.","PostgreSQL ctid is the classic deduplication tool (DELETE FROM t a USING t b WHERE a.key = b.key AND a.ctid > b.ctid), but every UPDATE writes a new tuple with a new ctid, so a captured ctid goes stale immediately.","SQL Server's closest thing, the heap RID, exists only when the table has no clustered index; add one and the RID is gone. Code that leaned on it breaks on the first index change.","SQLite tables declared WITHOUT ROWID have no rowid at all and must declare a PRIMARY KEY; SELECT rowid on them is an error."],"see_also":["oid","identity","uuid"],"faqs":[{"question":"Can I use ROWID as a primary key?","answer":"No. It is an address that changes on rewrites and gets reused after deletes. Oracle explicitly warns against persisting ROWID; anything you need stable should be its own column."},{"question":"What is ctid used for in PostgreSQL, then?","answer":"Short-lived physical tricks: deduplication, and since PostgreSQL 14, batching big updates or deletes by page range (WHERE ctid >= '(1000,0)' AND ctid < '(2000,0)' uses a TID range scan). It is a maintenance handle, not application data."},{"question":"Why does SQLite have both rowid and oid?","answer":"History: SQLite accepted 'oid' as a friendly alias early on. It means the same thing as rowid unless you declare your own column called oid, which shadows it. Avoid naming columns oid."}],"examples":[{"engine_slug":"sqlite","sql":"CREATE TABLE t (v TEXT);\nINSERT INTO t VALUES ('a');\nSELECT rowid, oid, _rowid_ FROM t;  -- 1 | 1 | 1: three names, one value"},{"engine_slug":"postgresql","sql":"CREATE TABLE t (v TEXT);\nINSERT INTO t VALUES ('a');\nSELECT ctid FROM t;  -- (0,1): page and slot; it changes on every update that moves the row"},{"engine_slug":"oracle","sql":"SELECT ROWID FROM dual;  -- file, block and slot: an address, not an identity"}]},"source_url":"https://sqlly.app/sql-data-types/rowid","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/sequence","corpus":"sql-data-types","engine":null,"language":"en","title":"CREATE SEQUENCE: standalone number generators","description":"Standalone sequences: native in PostgreSQL, Oracle and SQL Server, absent in MySQL and SQLite.","body":{"slug":"sequence","name":"Sequence","h1":"CREATE SEQUENCE: standalone number generators","family":"identifier","lede":"A sequence is a number generator that belongs to the schema, not to one column: several tables can draw from it, and application code can too. It is the standard answer to 'I need IDs without a row' and it is missing from two of the five engines.","summary":"Sequences are objects you CREATE and pull from with NEXTVAL/NEXT VALUE FOR. PostgreSQL, Oracle and SQL Server have them; MySQL and SQLite substitute per-table counters.","variants":[{"engine_slug":"sql-server","type_name":"CREATE SEQUENCE","storage":"8 bytes (BIGINT by default)","note":"Since 2012; value fetched with NEXT VALUE FOR seq. Can be shared by tables and used as a DEFAULT, but is not tied to a column's lifecycle.","has_native_type":true},{"engine_slug":"postgresql","type_name":"CREATE SEQUENCE","storage":"8 bytes","note":"First-class object: nextval('seq'), currval, setval; OWNED BY a column ties its lifecycle to a table. Every identity column backs onto one.","has_native_type":true},{"engine_slug":"mysql","type_name":"none (AUTO_INCREMENT)","storage":"n/a","note":"No standalone sequence object (MariaDB has one, MySQL does not). Workarounds: a counter table bumped with LAST_INSERT_ID(expr), or per-table AUTO_INCREMENT.","has_native_type":false},{"engine_slug":"sqlite","type_name":"none (rowid)","storage":"n/a","note":"No sequences. INTEGER PRIMARY KEY assigns rowids; the hidden sqlite_sequence table only tracks AUTOINCREMENT counters.","has_native_type":false},{"engine_slug":"oracle","type_name":"CREATE SEQUENCE","storage":"NUMBER (variable)","note":"The classic: seq.NEXTVAL / seq.CURRVAL, CACHE and NOCACHE options; pre-12c this plus a trigger was the standard identity column emulation.","has_native_type":true}],"gotchas":["There is no portable way to read the next value: PostgreSQL uses nextval('seq'), SQL Server NEXT VALUE FOR seq, Oracle seq.NEXTVAL. Migrations rewrite all three.","MySQL's common emulation, UPDATE counters SET id = LAST_INSERT_ID(id + 1) followed by SELECT LAST_INSERT_ID(), serializes on that row: every caller waits for the previous transaction to commit.","Sequences never roll back. Oracle's CACHE option precomputes a batch and discards it on instance restart, so gaps can be much larger than one.","A SQL Server sequence can be a table's DEFAULT, but nothing stops two tables sharing it; identities are per column, sequences are free-floating, and that is the design decision to make consciously.","In PostgreSQL, nextval() and setval() are never rolled back: setval('s', 500) inside a rolled-back transaction still leaves the sequence at 500. ALTER SEQUENCE ... RESTART, by contrast, does roll back."],"see_also":["identity","uuid"],"faqs":[{"question":"When do I need a sequence instead of an identity column?","answer":"When IDs are shared across tables, generated before the insert (child rows that reference a parent key you do not have yet), or handed to application code directly. A per-table counter does not do any of that."},{"question":"How do I get sequence-like behavior in MySQL or SQLite?","answer":"Neither has a sequence object. MySQL's counter-table trick works but is a hotspot; SQLite only has rowids. If cross-table ids matter, generate them in the application (snowflake ids, ULIDs, UUIDv7) instead."},{"question":"Do sequences create gaps?","answer":"Always, eventually: values are handed out and never returned, cached batches are dropped on crash, and transactions that roll back keep the number. Plan keys for uniqueness, not for contiguity."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE SEQUENCE order_no;\nSELECT nextval('order_no'), currval('order_no');  -- 1 | 1: belongs to the schema, not a column"},{"engine_slug":"sql-server","sql":"CREATE SEQUENCE order_no;\nSELECT NEXT VALUE FOR order_no;  -- 1: the SQL Server spelling, since 2012"},{"engine_slug":"mysql","sql":"CREATE TABLE counters (name VARCHAR(20) PRIMARY KEY, id BIGINT);\nUPDATE counters SET id = LAST_INSERT_ID(id + 1) WHERE name = 'order';\nSELECT LAST_INSERT_ID();  -- the emulation: one counter row, one hotspot"}]},"source_url":"https://sqlly.app/sql-data-types/sequence","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/serial","corpus":"sql-data-types","engine":null,"language":"en","title":"SERIAL and auto-incrementing integers","description":"Auto-incrementing integer keys: PostgreSQL's SERIAL, SQL Server IDENTITY, MySQL AUTO_INCREMENT, SQLite's rowid and Oracle identity columns.","body":{"slug":"serial","name":"SERIAL / auto-increment","h1":"SERIAL and auto-incrementing integers","family":"integer","lede":"SERIAL, IDENTITY, AUTO_INCREMENT, an INTEGER PRIMARY KEY alias, GENERATED AS IDENTITY: five engines, five spellings of the auto-growing key, none portable verbatim.","summary":"Same intent, incompatible syntax: SERIAL, IDENTITY, AUTO_INCREMENT, rowid aliasing and GENERATED AS IDENTITY, plus per-engine gaps and quirks.","variants":[{"engine_slug":"sql-server","type_name":"INT IDENTITY(1,1)","storage":"4 bytes","note":"IDENTITY is a column property, not a type; BIGINT IDENTITY for larger ranges.","has_native_type":true},{"engine_slug":"postgresql","type_name":"SERIAL / BIGSERIAL","storage":"4 / 8 bytes","note":"Shorthand for an INTEGER (or BIGINT) with a sequence-backed default; GENERATED AS IDENTITY is the modern spelling.","has_native_type":true},{"engine_slug":"mysql","type_name":"INT AUTO_INCREMENT","storage":"4 bytes","note":"A column attribute that must be indexed; at most one AUTO_INCREMENT column per table.","has_native_type":true},{"engine_slug":"sqlite","type_name":"INTEGER PRIMARY KEY AUTOINCREMENT","storage":"up to 8 bytes","note":"Any INTEGER PRIMARY KEY auto-assigns rowids; AUTOINCREMENT additionally forbids reusing deleted ids.","has_native_type":true},{"engine_slug":"oracle","type_name":"INT GENERATED ALWAYS AS IDENTITY","storage":"1-20 bytes","note":"Identity columns since 12c; older code pairs sequences with triggers or a default of seq.NEXTVAL.","has_native_type":true}],"gotchas":["SERIAL is not standard SQL: the same intent appears as IDENTITY (SQL Server, Oracle), AUTO_INCREMENT (MySQL) and implicit rowids (SQLite), so DDL never ports verbatim.","SQL Server, PostgreSQL, MySQL and Oracle burn values on rolled-back or failed inserts. SQLite is the exception: a rolled-back insert does not consume a rowid. Never build logic on gap-free keys.","MySQL allows at most one AUTO_INCREMENT column per table, and it must be indexed (error 1075 otherwise).","SQLite's AUTOINCREMENT keyword is usually unnecessary: a plain INTEGER PRIMARY KEY already auto-assigns, and AUTOINCREMENT adds a sqlite_sequence table and overhead.","Inserting explicit IDs desynchronizes counters differently: PostgreSQL's serial accepts them and leaves the sequence behind (the next default collides), MySQL moves its counter past them, SQL Server needs SET IDENTITY_INSERT first."],"see_also":["integer","bigint"],"faqs":[{"question":"Is SERIAL a data type?","answer":"In PostgreSQL it is shorthand for INTEGER plus a sequence-owned default; BIGSERIAL does the same for BIGINT. GENERATED ALWAYS AS IDENTITY is the standards-based replacement."},{"question":"Do auto-increment counters have gaps?","answer":"Yes. In SQL Server, PostgreSQL, MySQL and Oracle, rolled-back or failed inserts consume values permanently. SQLite hands out max(rowid)+1, so rollbacks leave no gap, but deletes do. Treat the counter as a unique source, not a row count."},{"question":"How do I auto-increment in SQLite?","answer":"Declare the column INTEGER PRIMARY KEY. SQLite aliases it to the rowid and assigns increasing values automatically; AUTOINCREMENT only adds reuse protection."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE TABLE posts (id SERIAL PRIMARY KEY, title TEXT);\nINSERT INTO posts (title) VALUES ('hi');\nSELECT id FROM posts;  -- 1: the sequence owned the default"},{"engine_slug":"sql-server","sql":"CREATE TABLE posts (id INT IDENTITY(1,1), title VARCHAR(100));\nINSERT INTO posts (title) VALUES ('hi');\nSELECT id FROM posts;  -- 1: IDENTITY is a column property, not a type"},{"engine_slug":"sqlite","sql":"CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT);\nINSERT INTO posts (title) VALUES ('hi');\nSELECT id FROM posts;  -- 1: the rowid did the counting"}]},"source_url":"https://sqlly.app/sql-data-types/serial","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/smallint","corpus":"sql-data-types","engine":null,"language":"en","title":"SMALLINT","description":"The 2-byte integer, -32,768 to 32,767: native in SQL Server, PostgreSQL and MySQL, faked with NUMBER(5) in Oracle and ignored by SQLite.","body":{"slug":"smallint","name":"SMALLINT","h1":"SMALLINT","family":"integer","lede":"SMALLINT halves INT's storage for columns with a known small range.","summary":"2 bytes and -32,768 to 32,767 in three engines; MySQL adds an UNSIGNED variant; Oracle and SQLite fold it into their general numeric types.","variants":[{"engine_slug":"sql-server","type_name":"SMALLINT","storage":"2 bytes","note":"Signed -32,768 to 32,767. There is no unsigned variant.","has_native_type":true},{"engine_slug":"postgresql","type_name":"SMALLINT (INT2)","storage":"2 bytes","note":"Same range; INT2 is the internal spelling.","has_native_type":true},{"engine_slug":"mysql","type_name":"SMALLINT","storage":"2 bytes","note":"Signed by default; SMALLINT UNSIGNED reaches 65,535.","has_native_type":true},{"engine_slug":"sqlite","type_name":"SMALLINT (INTEGER affinity)","storage":"variable, 1-8 bytes","note":"Accepted as a type name but behaves exactly like INTEGER.","has_native_type":true},{"engine_slug":"oracle","type_name":"NUMBER(5)","storage":"1-4 bytes","note":"Oracle accepts SMALLINT but maps it to NUMBER(38); NUMBER(5) allows -99,999 to 99,999, wider than a real SMALLINT.","has_native_type":true}],"gotchas":["MySQL's SMALLINT UNSIGNED (0-65,535) has no counterpart in SQL Server or PostgreSQL: porting it needs a CHECK constraint on the signed type.","SQLite ignores the size hint entirely: SMALLINT maps to INTEGER affinity and still stores up to 8-byte values.","Oracle's SMALLINT keyword is just NUMBER(38). NUMBER(5) is the usual stand-in, but it allows up to 99,999 and rounds fractional input (2.5 becomes 3) instead of rejecting it."],"see_also":["tinyint","integer","bigint"],"faqs":[{"question":"When should I use SMALLINT instead of INT?","answer":"When the range provably stays small and the table is large: 2 bytes instead of 4 per row and per index entry. Alignment padding often eats the saving in PostgreSQL, so choose it for the range, not the bytes."},{"question":"Does SQLite store SMALLINT in 2 bytes?","answer":"Not by declaration. SQLite uses INTEGER affinity and picks 1-8 bytes per value from its magnitude, so small values are compact anyway."}],"examples":[{"engine_slug":"mysql","sql":"CREATE TABLE years (yr SMALLINT UNSIGNED);\nINSERT INTO years VALUES (65535);\nINSERT INTO years VALUES (65536);  -- error: unsigned smallint stops at 65,535"},{"engine_slug":"sqlite","sql":"CREATE TABLE t (v SMALLINT);\nINSERT INTO t VALUES (-32769);\nSELECT v;  -- still -32769: affinity ignores the smallint idea"}]},"source_url":"https://sqlly.app/sql-data-types/smallint","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/text","corpus":"sql-data-types","engine":null,"language":"en","title":"TEXT and CLOB","description":"Large text storage: PostgreSQL's unlimited TEXT, MySQL's TEXT family, SQL Server's deprecated TEXT, SQLite's everyday TEXT and Oracle's CLOB.","body":{"slug":"text","name":"TEXT / CLOB","h1":"TEXT and CLOB","family":"text","lede":"The large-text options, from SQLite's everyday TEXT to Oracle's 128 TB CLOB.","summary":"PostgreSQL and SQLite treat TEXT as the plain string type; MySQL tiers it; SQL Server retired TEXT for VARCHAR(MAX); Oracle says CLOB.","variants":[{"engine_slug":"sql-server","type_name":"no TEXT - use VARCHAR(MAX)","storage":"up to 2 GB","note":"TEXT and NTEXT are deprecated since 2005 and slated for removal; new columns use VARCHAR(MAX) or NVARCHAR(MAX).","has_native_type":false},{"engine_slug":"postgresql","type_name":"TEXT","storage":"up to 1 GB","note":"TEXT and VARCHAR share one implementation; VARCHAR(n) only adds a length check, and CHAR(n) adds padding.","has_native_type":true},{"engine_slug":"mysql","type_name":"TEXT / LONGTEXT","storage":"64 KB / 4 GB","note":"TINYTEXT 255 bytes, TEXT 64 KB, MEDIUMTEXT 16 MB, LONGTEXT 4 GB; plain TEXT takes no DEFAULT (expression defaults from 8.0.13).","has_native_type":true},{"engine_slug":"sqlite","type_name":"TEXT","storage":"up to 1 billion bytes","note":"Stored in the database encoding (UTF-8 or UTF-16); SQLITE_MAX_LENGTH caps a value at 1,000,000,000 bytes by default.","has_native_type":true},{"engine_slug":"oracle","type_name":"CLOB / NCLOB","storage":"up to 128 TB","note":"LOB storage sits out-of-line; VARCHAR2 caps at 4000 bytes (32,767 with extended data types).","has_native_type":true}],"gotchas":["SQL Server's TEXT is a dead end: excluded from most string functions and dependent on READTEXT/UPDATETEXT; VARCHAR(MAX) replaced it in 2005.","MySQL's TEXT columns take no literal DEFAULT (only an expression default, from 8.0.13), and before 8.0.13 any query whose temporary table held a TEXT column went straight to disk.","PostgreSQL's TEXT has no length limit: enforce one with VARCHAR(n) or a CHECK constraint when the schema should.","Oracle's CLOBs live out-of-line: small LOBs cost extra I/O versus VARCHAR2, and comparisons need DBMS_LOB or explicit casts.","In SQLite, CHAR(n), VARCHAR(n) and TEXT all get TEXT affinity and none enforces a length; a CHECK (length(col) <= n) is the only way to cap one."],"see_also":["varchar","char"],"faqs":[{"question":"Is TEXT deprecated?","answer":"In SQL Server yes, in favor of VARCHAR(MAX). In MySQL and PostgreSQL TEXT is fully supported for large strings."},{"question":"TEXT or VARCHAR for emails?","answer":"A limited VARCHAR, such as VARCHAR(320): it documents the limit and, in MySQL, can be fully indexed, while a TEXT column needs a prefix length to be indexed at all."},{"question":"How big is a MySQL TEXT column?","answer":"Up to 65,535 bytes. MEDIUMTEXT reaches 16 MB and LONGTEXT 4 GB; the limit is in bytes, not characters."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE TABLE notes (body TEXT);\nINSERT INTO notes VALUES (repeat('x', 100000));\nSELECT length(body) FROM notes;  -- 100000: TEXT has no length limit"},{"engine_slug":"mysql","sql":"CREATE TABLE notes (body TEXT, tag VARCHAR(10) DEFAULT 'new');\nINSERT INTO notes (body) VALUES ('x');\nSELECT tag FROM notes;  -- 'new': VARCHAR takes a literal DEFAULT, TEXT cannot (expression defaults only, 8.0.13+)"},{"engine_slug":"sql-server","sql":"CREATE TABLE notes (body VARCHAR(MAX));\nINSERT INTO notes VALUES (REPLICATE('x', 10000));\nSELECT DATALENGTH(body) FROM notes;  -- 10000: the VARCHAR(MAX) replacement for TEXT"}]},"source_url":"https://sqlly.app/sql-data-types/text","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/time","corpus":"sql-data-types","engine":null,"language":"en","title":"TIME","description":"TIME across the five engines: fractional-second precision, storage sizes, and why MySQL's TIME can hold 838 hours while Oracle has no TIME type at all.","body":{"slug":"time","name":"TIME","h1":"TIME","family":"datetime","lede":"TIME stores a clock time: hours, minutes, seconds and an optional fractional part. Two engines treat it as a pure time-of-day, MySQL lets it go negative, and two do not have it.","summary":"A time-of-day with optional fractional seconds. SQL Server and PostgreSQL cap it at 24 hours; MySQL's TIME is a signed duration up to 838 hours; Oracle and SQLite have no TIME-only type.","variants":[{"engine_slug":"sql-server","type_name":"TIME","storage":"3 to 5 bytes","note":"TIME(p) with p 0-7; the default TIME(7) has 100-nanosecond precision and needs 5 bytes.","has_native_type":true},{"engine_slug":"postgresql","type_name":"TIME","storage":"8 bytes","note":"Microsecond precision; TIME(p) stays 8 bytes up to p = 6. TIME WITH TIME ZONE is 12 bytes and best avoided.","has_native_type":true},{"engine_slug":"mysql","type_name":"TIME","storage":"3 bytes plus fractional","note":"Range -838:59:59 to 838:59:59, so MySQL's TIME doubles as a duration, not just a clock time.","has_native_type":true},{"engine_slug":"sqlite","type_name":"TEXT","storage":"variable","note":"No native TIME. Store 'HH:MM:SS' text or seconds as INTEGER and use the time() function.","has_native_type":true},{"engine_slug":"oracle","type_name":"DATE","storage":"7 bytes","note":"No TIME-only type. The time of day lives inside DATE or TIMESTAMP; a 12:30 value needs a dummy date.","has_native_type":true}],"gotchas":["MySQL's TIME accepts negative values and hours above 23 (up to 838), because it is really an interval type. Code that assumes a clock time breaks the moment a computed duration lands in the column.","Oracle has no TIME type. To store 12:30:00 you pick a dummy date, and comparisons then include that date whether you meant it or not.","Fractional precision differs everywhere: SQL Server TIME(7) is 100 nanoseconds, PostgreSQL and MySQL cap at 6 digits (microseconds), and SQLite gives you whatever your text says.","PostgreSQL's TIME WITH TIME ZONE (timetz) is 12 bytes and stores a fixed offset that cannot follow DST; the docs say it exists only for SQL standard compliance. Use timestamptz instead."],"see_also":["timestamp","interval-day-second","date"],"faqs":[{"question":"How many bytes does TIME use?","answer":"SQL Server TIME(p) uses 3 to 5 bytes depending on precision, PostgreSQL TIME is 8 bytes, and MySQL TIME is 3 bytes plus 0 to 3 fractional bytes."},{"question":"Can TIME store durations like 26 hours?","answer":"In MySQL yes: TIME reaches -838:59:59 to 838:59:59 and is the usual duration type. In SQL Server and PostgreSQL a 26-hour value overflows; use an INTERVAL or an integer of seconds."},{"question":"Does TIME store a time zone?","answer":"No, except PostgreSQL's timetz, which stores a fixed offset that does not follow DST and is not recommended. Track zones with TIMESTAMPTZ instead."}],"examples":[{"engine_slug":"mysql","sql":"CREATE TABLE runs (t TIME);\nINSERT INTO runs VALUES ('26:30:00'), ('-04:00:00');\nSELECT t FROM runs;  -- 26:30:00 | -04:00:00: durations, not times of day"},{"engine_slug":"sql-server","sql":"CREATE TABLE shifts (start TIME(0));\nINSERT INTO shifts VALUES ('08:30:00');\nSELECT start FROM shifts;  -- a clock time, capped at 24 hours"},{"engine_slug":"oracle","sql":"CREATE TABLE noon (t DATE);\nINSERT INTO noon VALUES (TRUNC(SYSDATE) + 12/24);\nSELECT t FROM noon;  -- a 12:00 value needs a dummy date to live in"}]},"source_url":"https://sqlly.app/sql-data-types/time","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/timestamp","corpus":"sql-data-types","engine":null,"language":"en","title":"TIMESTAMP (without time zone)","description":"Timestamps without a time zone across the five engines, including why SQL Server's 'timestamp' keyword means something completely different.","body":{"slug":"timestamp","name":"TIMESTAMP (without time zone)","h1":"TIMESTAMP (without time zone)","family":"datetime","lede":"This is the workhorse datetime: a calendar date plus a clock time, with no time zone attached. Each engine names it differently, and SQL Server hijacks the word entirely.","summary":"Date plus time, zone-free. PostgreSQL calls it TIMESTAMP (8 bytes, microseconds), MySQL DATETIME (5 to 8 bytes, no conversion), SQL Server DATETIME2, Oracle TIMESTAMP, SQLite stores text.","variants":[{"engine_slug":"sql-server","type_name":"DATETIME2","storage":"6 to 8 bytes","note":"DATETIME2(p) has 100-nanosecond precision; 6 bytes at p 0-2, 7 at p 3-4, 8 at p 5-7. In SQL Server the word 'timestamp' means rowversion, not a datetime.","has_native_type":true},{"engine_slug":"postgresql","type_name":"TIMESTAMP","storage":"8 bytes","note":"Timestamp without time zone; microsecond precision, range 4713 BC to 294276 AD.","has_native_type":true},{"engine_slug":"mysql","type_name":"DATETIME","storage":"5 to 8 bytes","note":"DATETIME(fsp) is 5 bytes plus 0-3 fractional bytes; range 1000-01-01 to 9999-12-31 with no time-zone conversion.","has_native_type":true},{"engine_slug":"sqlite","type_name":"TEXT","storage":"variable","note":"No native type. ISO-8601 text like '2026-02-14 09:30:00' sorts correctly and feeds the datetime() functions.","has_native_type":true},{"engine_slug":"oracle","type_name":"TIMESTAMP","storage":"7 to 11 bytes","note":"TIMESTAMP(p) adds up to 9 fractional-second digits on top of the 7-byte DATE layout.","has_native_type":true}],"gotchas":["In SQL Server, TIMESTAMP is a deprecated synonym for rowversion: an 8-byte binary counter that changes on every row update. Writing CREATE TABLE (t timestamp) does not create a datetime column.","PostgreSQL's timestamp stores no zone, so it cannot say which instant '2026-11-01 01:30' was in New York, where that wall-clock time happened twice. Arithmetic on it ignores DST entirely.","MySQL has both DATETIME and TIMESTAMP with different behavior: DATETIME stores the wall clock untouched, TIMESTAMP converts from the session zone to UTC on the way in and back out.","SQLite comparisons work by text ordering, which is only correct while every value is the same ISO-8601 shape; mixing '2026-02-14' with '2026-02-14 09:30:00' breaks ordering.","Oracle's TIMESTAMP still has no zone, same as its DATE; the zone-aware choices are TIMESTAMP WITH TIME ZONE and WITH LOCAL TIME ZONE."],"see_also":["timestamptz","datetime2","date","time"],"faqs":[{"question":"What is the difference between TIMESTAMP and DATETIME?","answer":"In MySQL they are different types: DATETIME stores the wall clock as written (5 to 8 bytes, 1000-9999), while TIMESTAMP converts to UTC for storage (4 bytes, 1970-2038). In SQL Server, DATETIME is the legacy 3.33 ms type and 'timestamp' means rowversion."},{"question":"Which engine type matches PostgreSQL's timestamp?","answer":"SQL Server DATETIME2, MySQL DATETIME, Oracle TIMESTAMP. All store date plus time with no zone. SQLite has no equivalent - store ISO-8601 text."},{"question":"How many bytes is a timestamp without time zone?","answer":"8 bytes in PostgreSQL, 6 to 8 for SQL Server DATETIME2 depending on precision, 5 to 8 for MySQL DATETIME, and 7 to 11 for Oracle TIMESTAMP."}],"examples":[{"engine_slug":"sql-server","sql":"CREATE TABLE t (id INT, rv TIMESTAMP);\nINSERT INTO t (id) VALUES (1);\nSELECT rv FROM t;  -- a binary row counter: 'timestamp' means rowversion here"},{"engine_slug":"mysql","sql":"CREATE TABLE t (seen DATETIME);\nSET time_zone = '+02:00';\nINSERT INTO t VALUES ('2026-02-14 09:30:00');\nSELECT seen FROM t;  -- 09:30:00 unchanged: DATETIME stores the wall clock, TIMESTAMP would convert"},{"engine_slug":"postgresql","sql":"SELECT '2026-02-14 09:30'::timestamp AT TIME ZONE 'UTC';  -- adds a zone: without one, the instant was ambiguous"}]},"source_url":"https://sqlly.app/sql-data-types/timestamp","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/timestamptz","corpus":"sql-data-types","engine":null,"language":"en","title":"TIMESTAMPTZ (timestamp with time zone)","description":"Time-zone-aware timestamps: PostgreSQL TIMESTAMPTZ, SQL Server DATETIMEOFFSET, Oracle TIMESTAMP WITH TIME ZONE, and what MySQL and SQLite do instead.","body":{"slug":"timestamptz","name":"TIMESTAMPTZ","h1":"TIMESTAMPTZ (timestamp with time zone)","family":"datetime","lede":"The zone-aware timestamp is the only datetime type that names a real instant. The engines disagree on whether to keep the offset you gave them or throw it away.","summary":"A timestamp plus a UTC offset. PostgreSQL normalizes to UTC and stores 8 bytes; SQL Server DATETIMEOFFSET and Oracle's WITH TIME ZONE keep the original offset; MySQL has no true equivalent.","variants":[{"engine_slug":"sql-server","type_name":"DATETIMEOFFSET","storage":"8 to 10 bytes","note":"DATETIMEOFFSET(p) keeps a DATETIME2 plus an offset from -14:00 to +14:00; 8 bytes at p 0-2, 10 at p 5-7.","has_native_type":true},{"engine_slug":"postgresql","type_name":"TIMESTAMPTZ","storage":"8 bytes","note":"Stores UTC internally; the zone you type is converted on the way in and reapplied from the session TimeZone on the way out. The original offset is not kept.","has_native_type":true},{"engine_slug":"mysql","type_name":"TIMESTAMP","storage":"4 bytes","note":"Closest match but stores no offset: values are converted from the session time zone to UTC (4 bytes, range 1970-2038) and back on retrieval.","has_native_type":true},{"engine_slug":"sqlite","type_name":"TEXT","storage":"variable","note":"No native type. Store ISO-8601 text with an offset, such as '2026-02-14T09:30:00+02:00', and convert with datetime() or the unixepoch modifiers.","has_native_type":true},{"engine_slug":"oracle","type_name":"TIMESTAMP WITH TIME ZONE","storage":"13 bytes","note":"Keeps the original zone as a region name (like 'America/New_York') or a fixed offset; a region shows the right DST offset for each instant.","has_native_type":true}],"gotchas":["PostgreSQL's timestamptz does not store a time zone, despite the name. It stores a UTC instant; the offset you entered is discarded and output re-rendered in the session's TimeZone setting.","SQL Server's DATETIMEOFFSET keeps the offset alongside the time, so comparisons convert to UTC first - two rows with different offsets compare by the instant they name, not the digits on disk.","Oracle's 13-byte WITH TIME ZONE can store a region name instead of a numeric offset, so the same column shows -05:00 for January rows and -04:00 for July rows; a stored -05:00 is -05:00 forever.","MySQL has no offset-preserving type at all. TIMESTAMP silently normalizes to UTC through the session time zone, which moves with each connection's settings.","SQLite leaves every decision to you: text with offsets compares incorrectly as strings when offsets differ, so normalize to UTC text or use the unixepoch for ordering."],"see_also":["timestamp","date","time"],"faqs":[{"question":"Does PostgreSQL TIMESTAMPTZ store the time zone?","answer":"No. It converts your input to UTC, stores 8 bytes, and formats output in the session's time zone. To keep the original offset, add a separate zone or offset column."},{"question":"What is the SQL Server equivalent of TIMESTAMPTZ?","answer":"DATETIMEOFFSET. It stores a DATETIME2 plus the offset, so unlike timestamptz it preserves what was entered. CAST(dt2 AS datetimeoffset) just attaches +00:00; use AT TIME ZONE or TODATETIMEOFFSET to attach a real zone."},{"question":"How many bytes does a time-zone-aware timestamp use?","answer":"8 bytes in PostgreSQL, 8 to 10 for SQL Server DATETIMEOFFSET, 13 in Oracle, and 4 for MySQL's UTC-normalized TIMESTAMP."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE TABLE events (at TIMESTAMPTZ);\nINSERT INTO events VALUES ('2026-02-14 09:30+02');\nSET TimeZone = 'UTC';\nSELECT at FROM events;  -- 07:30: the offset you gave was not kept"},{"engine_slug":"sql-server","sql":"SELECT CAST('2026-02-14T09:30:00+02:00' AS DATETIMEOFFSET);  -- +02:00 kept: unlike timestamptz, the offset is preserved"},{"engine_slug":"oracle","sql":"CREATE TABLE t (at TIMESTAMP WITH TIME ZONE);\nINSERT INTO t VALUES (TIMESTAMP '2026-02-14 09:30:00 America/New_York');\nSELECT EXTRACT(TIMEZONE_REGION FROM at) FROM t;  -- America/New_York: the region rides along"}]},"source_url":"https://sqlly.app/sql-data-types/timestamptz","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/tinyint","corpus":"sql-data-types","engine":null,"language":"en","title":"TINYINT","description":"The 1-byte integer: unsigned 0-255 in SQL Server, signed -128 to 127 by default in MySQL, absent from PostgreSQL and Oracle, a bare name in SQLite.","body":{"slug":"tinyint","name":"TINYINT","h1":"TINYINT","family":"integer","lede":"TINYINT is the smallest integer type in the engines that have one, and the same name means 0-255 in one engine and -128 to 127 in another.","summary":"1 byte, 0-255 in SQL Server; signed -128 to 127 by default in MySQL; nowhere else has it, so SMALLINT or NUMBER(3) stands in.","variants":[{"engine_slug":"sql-server","type_name":"TINYINT","storage":"1 byte","note":"Unsigned only: 0 to 255. There is no signed tinyint here.","has_native_type":true},{"engine_slug":"postgresql","type_name":"no TINYINT - use SMALLINT","storage":"2 bytes (SMALLINT)","note":"PostgreSQL's smallest integer is SMALLINT; a domain with CHECK can narrow it.","has_native_type":false},{"engine_slug":"mysql","type_name":"TINYINT","storage":"1 byte","note":"Signed -128 to 127 by default; TINYINT UNSIGNED reaches 0 to 255.","has_native_type":true},{"engine_slug":"sqlite","type_name":"TINYINT (INTEGER affinity)","storage":"variable, 1-8 bytes","note":"Any type name containing INT gets INTEGER affinity, so TINYINT stores full 64-bit integers.","has_native_type":true},{"engine_slug":"oracle","type_name":"NUMBER(3)","storage":"1-3 bytes","note":"No tinyint; NUMBER(3) allows -999 to 999 in variable-length decimal storage, so add a CHECK for 0-255.","has_native_type":true}],"gotchas":["SQL Server's TINYINT is unsigned (0-255) while MySQL's default is signed (-128 to 127): the same column name holds different ranges.","MySQL's TINYINT(1) is treated as a boolean by many clients, but the (1) is display width only - the column still stores the full tinyint range.","PostgreSQL and Oracle have no 1-byte integer: SMALLINT costs 2 bytes and NUMBER(3) up to 4, and neither stops a 300 from going in without a CHECK constraint.","SQLite accepts the type name but gives it INTEGER affinity, so a TINYINT column happily stores 9,223,372,036,854,775,807."],"see_also":["smallint","integer","bit","serial"],"faqs":[{"question":"How do I get a 1-byte integer in PostgreSQL?","answer":"You cannot. The smallest is SMALLINT at 2 bytes. Add a CHECK constraint or a domain to enforce a smaller range."},{"question":"What is TINYINT(1) in MySQL?","answer":"A TINYINT declared with display width 1. Clients often map it to boolean, but it stores the full signed (or unsigned) tinyint range."},{"question":"Is SQL Server's TINYINT signed?","answer":"No. It only stores 0 to 255. For -128 to 127 you need SMALLINT, which is 2 bytes."}],"examples":[{"engine_slug":"mysql","sql":"CREATE TABLE sensors (battery TINYINT);\nINSERT INTO sensors VALUES (127);\nINSERT INTO sensors VALUES (200);  -- error 1264 in strict mode: signed tops out at 127"},{"engine_slug":"sqlite","sql":"CREATE TABLE t (v TINYINT);\nINSERT INTO t VALUES (9223372036854775807);\nSELECT v;  -- INTEGER affinity keeps the full 64-bit value"},{"engine_slug":"oracle","sql":"CREATE TABLE t (v NUMBER(3) CHECK (v BETWEEN 0 AND 255));\nINSERT INTO t VALUES (255);\nINSERT INTO t VALUES (300);  -- ORA-01438: the CHECK, not the type, holds the line"}]},"source_url":"https://sqlly.app/sql-data-types/tinyint","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/uuid","corpus":"sql-data-types","engine":null,"language":"en","title":"UUID (universally unique identifier)","description":"How five engines store a 128-bit UUID: natively, or faked with CHAR(36), BINARY(16) and RAW(16).","body":{"slug":"uuid","name":"UUID","h1":"UUID (universally unique identifier)","family":"identifier","lede":"A UUID hands out globally unique keys without a round trip to the database: any server, any offline client, no collisions. Only some engines give it a real column type; the rest store a string or a byte array and get along fine.","summary":"Every engine can hold a UUID. The differences are whether it has a native type, how many bytes it costs (16 vs 36), and whether the engine generates one for you.","variants":[{"engine_slug":"sql-server","type_name":"UNIQUEIDENTIFIER","storage":"16 bytes","note":"NEWID() generates a random version-4 value, NEWSEQUENTIALID() an increasing one. ORDER BY compares the last 6 bytes first, so the sort order differs from the text form.","has_native_type":true},{"engine_slug":"postgresql","type_name":"UUID","storage":"16 bytes","note":"Native type; gen_random_uuid() (version 4) is built in since PostgreSQL 13, and uuidv7() (time-ordered) since PostgreSQL 18.","has_native_type":true},{"engine_slug":"mysql","type_name":"BINARY(16) or CHAR(36)","storage":"16 or 36 bytes","note":"No native UUID type. UUID() returns a 36-char string; UUID_TO_BIN(..., 1) in 8.0 packs it into BINARY(16) and can swap the timestamp block for better index locality.","has_native_type":true},{"engine_slug":"sqlite","type_name":"TEXT","storage":"36 bytes","note":"No UUID type and no built-in generator (the uuid extension is optional). Store the hyphenated text or a 16-byte BLOB; randomblob(16) gives random bytes but not a valid v4 layout.","has_native_type":true},{"engine_slug":"oracle","type_name":"RAW(16)","storage":"16 bytes","note":"SYS_GUID() returns a 16-byte RAW that is not an RFC 4122 UUID; 23ai adds UUID(), which returns a random version-4 RAW(16). Formatting as 8-4-4-4-12 is your job.","has_native_type":true}],"gotchas":["NEWID() values are random, so as a clustered key they land all over the index and split pages. NEWSEQUENTIALID() fixes that but only works in a DEFAULT constraint, and its sequence can restart lower after a Windows reboot.","The same UUID is spelled differently per engine: SQL Server prints uppercase (and accepts braces on input), PostgreSQL prints lowercase, Oracle RAW(16) is hex with no dashes, and SQLite holds whatever text you put in. Normalize on write or text joins silently miss.","MySQL UUID() is version-1 style (time and MAC based), which leaks the host's identity and needs UUID_TO_BIN plus BINARY(16) if you want compact storage.","SQLite has no built-in UUID generator, so a DEFAULT that generates the id does not port; the application (or a loaded extension) must create it.","Oracle SYS_GUID() values are not RFC UUIDs and are often nearly sequential, so mixing them with app-generated v4 UUIDs in one RAW(16) column works but leaves two id formats to explain."],"see_also":["identity","sequence","oid"],"faqs":[{"question":"Does MySQL have a UUID type like PostgreSQL?","answer":"No. MySQL stores UUIDs either as CHAR(36) text or, better, packed into BINARY(16) with UUID_TO_BIN(). 8.0's UUID_TO_BIN(..., 1) also reorders blocks so sequential UUIDs index better."},{"question":"Should I store a UUID as text or bytes?","answer":"Bytes: 16 bytes in BINARY(16)/RAW(16)/bytea vs 36 as text. Text wins only when humans read the column or the file format demands it, such as a plain SQLite column."},{"question":"Why do random UUIDs slow down SQL Server?","answer":"They enter the clustered index in random order, so inserts hit random pages and split them. Use NEWSEQUENTIALID(), a sequential UUID version (v7), or keep the UUID as a secondary unique index instead of the clustered key."}],"examples":[{"engine_slug":"postgresql","sql":"CREATE TABLE users (id UUID DEFAULT gen_random_uuid());\nINSERT INTO users VALUES (DEFAULT);\nSELECT id FROM users;  -- a v4 UUID; uuidv7() (time-ordered) arrives in PostgreSQL 18"},{"engine_slug":"mysql","sql":"CREATE TABLE users (id BINARY(16));\nINSERT INTO users VALUES (UUID_TO_BIN(UUID(), 1));\nSELECT BIN_TO_UUID(id, 1) FROM users;  -- packed 16 bytes, blocks swapped for index locality"},{"engine_slug":"sql-server","sql":"CREATE TABLE users (id UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID());\nINSERT INTO users VALUES (DEFAULT);\nSELECT id FROM users;  -- increasing keys instead of random index splits"}]},"source_url":"https://sqlly.app/sql-data-types/uuid","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/varchar","corpus":"sql-data-types","engine":null,"language":"en","title":"VARCHAR and NVARCHAR","description":"Variable-length strings: byte versus character limits, VARCHAR(MAX), NVARCHAR versus VARCHAR collations, VARCHAR2's empty-string trap and SQLite's indifference.","body":{"slug":"varchar","name":"VARCHAR / NVARCHAR","h1":"VARCHAR and NVARCHAR","family":"text","lede":"The everyday string type, plus the length and encoding traps each engine adds.","summary":"All five engines have a VARCHAR, but the limit is bytes or characters, MAX or 4000, enforced or ignored - and Oracle's empty string is NULL.","variants":[{"engine_slug":"sql-server","type_name":"VARCHAR(n) / VARCHAR(MAX) / NVARCHAR","storage":"n bytes + 2, or 2 GB (MAX)","note":"VARCHAR(n) allows n up to 8,000 bytes, NVARCHAR(n) up to 4,000 UTF-16 code units (emoji take two); the collation decides casing and sorting.","has_native_type":true},{"engine_slug":"postgresql","type_name":"VARCHAR(n) / VARCHAR","storage":"bytes used + 1 (or 4) bytes","note":"Length in characters; VARCHAR without (n) behaves like TEXT, up to 1 GB.","has_native_type":true},{"engine_slug":"mysql","type_name":"VARCHAR(n)","storage":"bytes used + 1 or 2 bytes","note":"n counts characters; utf8mb4 caps it at 16,383, and all columns together must fit the 65,535-byte row limit.","has_native_type":true},{"engine_slug":"sqlite","type_name":"VARCHAR(n) (TEXT affinity)","storage":"variable","note":"TEXT affinity: no length enforcement, no padding, no separate Unicode type.","has_native_type":true},{"engine_slug":"oracle","type_name":"VARCHAR2(n BYTE|CHAR)","storage":"up to 4000 bytes","note":"VARCHAR exists as ANSI syntax, but VARCHAR2 is the idiomatic (and empty-string-is-NULL) type; 32,767 bytes with extended data types.","has_native_type":true}],"gotchas":["Oracle VARCHAR2 sizes in bytes unless told otherwise: in AL32UTF8, VARCHAR2(50) rejects a 17-character Chinese or Japanese name (3 bytes per character, 51 bytes). Declare VARCHAR2(n CHAR).","SQL Server's VARCHAR is a legacy code page while NVARCHAR is UTF-16: emoji or multilingual data in VARCHAR can become ? unless the column uses a UTF-8 collation.","Oracle treats the empty string '' as NULL: inserting '' into VARCHAR2 stores NULL and IS NULL matches it. None of the other engines do this.","MySQL enforces the 65,535-byte row limit across all columns together, and a utf8mb4 VARCHAR tops out at 16,383 characters: VARCHAR(20000) fails CREATE TABLE with error 1074.","SQLite's VARCHAR(n) does not enforce n at all; validation moves entirely to the application."],"see_also":["char","text"],"faqs":[{"question":"VARCHAR(n) or VARCHAR(MAX)?","answer":"n when a real limit exists: it documents intent, validates input and helps the optimizer. MAX is for genuinely unbounded text."},{"question":"VARCHAR or NVARCHAR in SQL Server?","answer":"NVARCHAR for user-entered multilingual text. VARCHAR with a UTF-8 collation is an option from SQL Server 2019 onward."},{"question":"Why VARCHAR2 in Oracle?","answer":"History: Oracle reserved VARCHAR for future ANSI semantics and guaranteed VARCHAR2 would never change, so everyone uses VARCHAR2."}],"examples":[{"engine_slug":"oracle","sql":"CREATE TABLE names (n VARCHAR2(10));\nINSERT INTO names VALUES ('');\nSELECT COUNT(*) FROM names WHERE n IS NULL;  -- 1: the empty string is NULL in Oracle"},{"engine_slug":"postgresql","sql":"CREATE TABLE t (v VARCHAR(3));\nINSERT INTO t VALUES ('abc');\nINSERT INTO t VALUES ('abcd');  -- error 22001: PostgreSQL enforces n, SQLite does not"},{"engine_slug":"sqlite","sql":"CREATE TABLE t (v VARCHAR(5));\nINSERT INTO t VALUES ('way too long');\nSELECT v FROM t;  -- stored whole: TEXT affinity never enforces n"}]},"source_url":"https://sqlly.app/sql-data-types/varchar","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-data-types/xml","corpus":"sql-data-types","engine":null,"language":"en","title":"The XML column type","description":"XML columns: native XML in SQL Server and Oracle, text storage in MySQL, SQLite and plain PostgreSQL.","body":{"slug":"xml","name":"XML","h1":"The XML column type","family":"semi","lede":"JSON pushed XML out of new designs, but the columns still exist: SQL Server and Oracle have real XML types with query support, the rest store text and hope.","summary":"Real XML types (SQL Server, Oracle) validate and can be queried with XQuery; PostgreSQL's xml stores well-formed text; MySQL and SQLite store raw text with no checks.","variants":[{"engine_slug":"sql-server","type_name":"XML","storage":"Variable, up to 2 GB","note":"Untyped or typed against an XML SCHEMA COLLECTION; XQuery via .query/.value/.exist, and selective XML indexes (2012 SP1 onward) make path queries indexable.","has_native_type":true},{"engine_slug":"postgresql","type_name":"XML","storage":"Textual, variable","note":"Checks well-formedness on insert and offers xpath(), XMLEXISTS and XMLTABLE, but XPath 1.0 only (no XQuery), and the server must be built with libxml.","has_native_type":true},{"engine_slug":"mysql","type_name":"none (TEXT)","storage":"TEXT limits","note":"No XML type. Store in TEXT; ExtractValue() and UpdateXML() handle a subset of XPath 1.0, and malformed XML returns NULL with a warning, not an error.","has_native_type":false},{"engine_slug":"sqlite","type_name":"none (TEXT)","storage":"TEXT limits","note":"No XML type or functions. Store text; parse in the application.","has_native_type":false},{"engine_slug":"oracle","type_name":"XMLType","storage":"Variable","note":"The heavyweight: object-relational or binary storage, registered schemas, XMLQuery/XMLTable/XDB features, and index options down to structured storage of elements.","has_native_type":true}],"gotchas":["PostgreSQL's xml type only enforces well-formedness (one root element, balanced tags), not validity against a schema; and if the server lacks libxml, the XML functions error out while the type still stores text.","MySQL's ExtractValue() returns an empty string when the path matches nothing and NULL (plus warning 1525) when the XML is malformed, so validate documents before they are written.","SQL Server typed XML (bound to a schema collection) validates on write, untyped XML only checks well-formedness; switching a column to typed with ALTER COLUMN revalidates every existing row and fails on the first one that does not conform.","Oracle XMLType in object-relational storage can be extremely fast and extremely rigid: adding an element to a registered schema means schema evolution work nobody budgeted.","Namespaces are the classic trap: a document with a default xmlns returns nothing for //item in SQL Server, PostgreSQL and Oracle until the query declares the namespace."],"see_also":["json","jsonb"],"faqs":[{"question":"Is there any reason to use an XML column today?","answer":"Legacy documents, SOAP-era integrations, and office formats (docx, xlsx are zipped XML) that arrive as-is. For new application data, JSON is the default; keep XML when the data already is XML."},{"question":"Does MySQL validate XML in a TEXT column?","answer":"No. It stores any text, and ExtractValue() on malformed XML returns NULL with a warning. There is no XML validation function to put in a CHECK constraint."},{"question":"What is the difference between typed and untyped XML in SQL Server?","answer":"Typed XML is bound to an XML SCHEMA COLLECTION and validated against it on insert; untyped accepts any well-formed fragment. Typed gives you validation and better storage inference at the cost of schema rigidity."}],"examples":[{"engine_slug":"sql-server","sql":"CREATE TABLE docs (x XML);\nINSERT INTO docs VALUES (N'<a><b>1</b></a>');\nSELECT x.value('(/a/b)[1]', 'int') FROM docs;  -- 1: XQuery built in"},{"engine_slug":"postgresql","sql":"CREATE TABLE docs (x XML);\nINSERT INTO docs VALUES ('<a><b>1</b></a>');\nSELECT xpath('/a/b/text()', x) FROM docs;  -- {1}: well-formedness checked, XPath 1.0 only"},{"engine_slug":"mysql","sql":"CREATE TABLE docs (x TEXT);\nINSERT INTO docs VALUES ('<a><b>1</b></a>');\nSELECT ExtractValue(x, '/a/b') FROM docs;  -- 1: no XML type; malformed input returns NULL with a warning"}]},"source_url":"https://sqlly.app/sql-data-types/xml","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
