Skip to content

String types: CHAR, VARCHAR, BIT and ENUM

View as Markdown

CoraDB has two character string types:

Type Synonyms Length n Storage
CHAR(n) CHARACTER(n) 1 to 268,435,455 characters, default 1 Always n characters, padded with spaces
VARCHAR(n) CHAR VARYING(n), CHARACTER VARYING(n) 1 to 1,073,741,823 characters, default the maximum The characters entered
STRING VARCHAR(1,073,741,823)
  • n counts characters, not bytes. How many bytes a character takes depends on the character set; see An overview of globalization.
  • A DEFAULT value can be declared for columns of these types.
  • In the e-commerce sample database the text columns are VARCHAR, for example product.name is VARCHAR(64) and city.postal_code is VARCHAR(32). SHOW COLUMNS reports VARCHAR(n) and CHAR(n) whatever synonym was used.
  • NCHAR and NCHAR VARYING are still accepted for compatibility. Use CHAR and VARCHAR instead.

Too long values. A value longer than n is rejected by INSERT and UPDATE (Cannot coerce 'pacesetter' to type char.). If the system parameter allow_truncated_string is yes, the value is truncated to n characters instead.

Character set and collation. The character set defines how characters are encoded; the collation defines how strings are compared and sorted. Both come from the database locale and can be changed per value with the CHARSET introducer and the COLLATE modifier. See An overview of globalization.

Conversion. CHAR and VARCHAR values of the same character set are converted into each other automatically, for example when a CHAR(5) value is inserted into a CHAR(10) column. Use CAST for explicit conversions.

CHAR(n) always holds n characters: a shorter value is padded with spaces on the right. Trailing spaces beyond n are dropped without error.

Value stored in Result
'pacesetter' in CHAR(12) 'pacesetter ' (10 characters + 2 spaces)
'pacesetter ' in CHAR(10) 'pacesetter' (the extra spaces are dropped)
'pacesetter' in CHAR(4) Error, or 'pace' with allow_truncated_string = yes
'p ' in CHAR 'p' (default length 1)
'' in CHAR(10) Ten spaces: LENGTH returns 10

VARCHAR(n) stores the value as entered, including trailing spaces, up to n characters. STRING is VARCHAR with the maximum length.

Value stored in Result
'pacesetter' in VARCHAR(12) 'pacesetter' (10 characters)
'pacesetter ' in VARCHAR(12) 'pacesetter ' (11 characters)
'pacesetter' in VARCHAR(4) Error, or 'pace' with allow_truncated_string = yes
'p ' in STRING 'p '
'' in VARCHAR(12) An empty string: LENGTH returns 0

String compression

VARCHAR values of 255 bytes or more are compressed with the LZO1X algorithm before they are stored in heap, index or temporary files, and decompressed when read. A value is kept uncompressed if compression would not make it smaller. Compression adds 8 bytes (the compressed and the original size) and can be turned off with the system parameter enable_string_compression.

To see whether a value is compressed, compare DISK_SIZE with OCTET_LENGTH:

SELECT OCTET_LENGTH(REPEAT('a', 1000)) AS octets, DISK_SIZE(REPEAT('a', 1000)) AS on_disk;
octets on_disk
1000 24
  • A string literal is enclosed in single quotes. To include a single quote, write it twice: '''abcde''fghij' is 'abcde'fghij.
  • Double quotes enclose identifiers by default. If the system parameter ansi_quotes is no, double quotes enclose strings too.
  • Two literals separated only by white space (spaces, tabs, line breaks) are joined into one, as in ANSI SQL.
  • A single string token can be at most 16 KB long; longer values are built with functions such as CONCAT or bound as parameters.
SELECT 'abc'
'def' AS joined, '''abcde''fghij' AS quotes, 'say "hi"' AS dq;
joined quotes dq
abcdef 'abcde'fghij say "hi"

There are two ways to escape special characters in a string literal.

With quotes (always available)

  • Inside single quotes, write a single quote twice (''). Double quotes need no escaping.
  • When ansi_quotes is no, inside double quotes write a double quote twice (""); single quotes need no escaping.

With a backslash (only when the system parameter no_backslash_escapes is no; the default is yes)

Sequence Character
\' Single quote
\" double quote
\n Newline (line feed)
\r Carriage return
\t Tab
\\ Backslash
\% Percent sign, in LIKE patterns
\_ Underscore, In LIKE patterns

Any other character after a backslash stands for itself (\x is x). \% and \_ only matter in pattern matching such as LIKE; elsewhere they are the two characters as written.

With the default no_backslash_escapes = yes a backslash is an ordinary character, so '\\' is two characters long; with no it is one:

SELECT LENGTH('\\') AS len;
len
2

With no_backslash_escapes = no, STRCMP('single quotes test('')', 'single quotes test(\')') returns 0, because both literals contain the same string. With the default setting the second literal is unterminated and the statement is a syntax error.

Escaping LIKE wildcards. To match a literal % or _ with LIKE, declare an escape character with ESCAPE. Any character works; with the default setting a backslash can be used directly:

SELECT ('aaa%' LIKE 'aaa#%' ESCAPE '#') AS a, ('aaabbb' LIKE 'aaa#%' ESCAPE '#') AS b, ('aaa%' LIKE 'aaa\%' ESCAPE '\') AS c;
a b c
1 0 1

When no_backslash_escapes is no, the backslash in the ESCAPE clause must itself be escaped: ESCAPE '\\'.

The padding spaces of a CHAR value are ignored when it is compared. Trailing spaces in a VARCHAR value or in a string literal are significant.

Comparison Result
CHAR 'abc' = CHAR 'abc ' Equal: both are padded and the padding is ignored
VARCHAR 'abc' = VARCHAR 'abc ' Not equal
CHAR(5) 'abc' = VARCHAR 'abc' Equal: the CHAR padding is ignored
CHAR(5) 'abc' = VARCHAR 'abc ' Not equal: the VARCHAR spaces count
Literal 'abc' = literal 'abc ' Not equal
SELECT (CAST('abc' AS CHAR(5)) = CAST('abc ' AS CHAR(7))) AS char_char,
(CAST('abc' AS VARCHAR(5)) = CAST('abc ' AS VARCHAR(7))) AS varchar_varchar,
(CAST('abc' AS CHAR(5)) = CAST('abc' AS VARCHAR(5))) AS char_varchar,
('abc' = 'abc ') AS literals;
char_char varchar_varchar char_varchar literals
1 0 1 0

Use TRIM or RTRIM when user input may carry trailing spaces.

A bit string is a sequence of bits (0 and 1). CoraDB has two bit string types:

Type Length n
BIT(n) Fixed, 1 to 1, 073, 741, 823 bits, Default 1
BIT VARYING(n) Variable, up to n bits, default 1,073,741,823

Bit string literals are written in binary or hexadecimal:

Form Example Value
B'…' B'1010' 1010
0b… 0b1010 1010
X'…' X'a' 1010
0x… 0xA 1010

Hexadecimal digits are case-insensitive: X'4f' and X'4F' are the same value.

  • Bits are filled from the left, and a shorter value is padded with 0 bits on the right when it is compared or stored in a BIT(n) column. B'1' therefore equals B'10000000'. Declare lengths and write values in multiples of 8 bits to avoid surprises.
  • A value longer than the declared length is rejected (Cannot coerce X'aaa' to type bit).
  • BIT and BIT VARYING values are compared with each other automatically. Use CAST for explicit conversions.
  • A DEFAULT value can be declared for columns of these types.

Bit strings are shown in hexadecimal. CoraDB's text form (corasql, CAST(... AS STRING)) shows only the hex digits that hold the stored bits, so a 1-bit value B'1' is shown as 8; drivers return the bytes, 0x80.

A BIT(n) value always has n bits; a shorter value is padded with 0 bits.

CREATE TABLE bit_tbl (a1 BIT, a2 BIT(1), a3 BIT(8), a4 BIT VARYING);
INSERT INTO bit_tbl VALUES (B'1', B'1', B'1', B'1');
INSERT INTO bit_tbl VALUES (0b1, 0b1, 0b1, 0b1);
INSERT INTO bit_tbl (a3, a4) VALUES (B'1010', B'1010');
INSERT INTO bit_tbl (a3, a4) VALUES (0xaa, 0xaa);
SELECT CAST(a1 AS STRING) a1, CAST(a2 AS STRING) a2, CAST(a3 AS STRING) a3, CAST(a4 AS STRING) a4, BIT_LENGTH(a4) a4_bits FROM bit_tbl;
a1 a2 a3 a4 a4_bits
8 8 80 8 1
8 8 80 8 1
NULL NULL a0 a 4
NULL NULL aa aa 8

a3 is BIT(8), so B'1' becomes 10000000 (80) and B'1010' becomes 10100000 (a0).

A BIT VARYING(n) value keeps the number of bits it was given, up to n; it is not padded.

CREATE TABLE bitvar_tbl (a1 BIT VARYING, a2 BIT VARYING(8));
INSERT INTO bitvar_tbl VALUES (B'1', B'1');
INSERT INTO bitvar_tbl VALUES (0b1010, 0b1010);
INSERT INTO bitvar_tbl VALUES (0xaa, 0xaa);
INSERT INTO bitvar_tbl (a1) VALUES (0xaaa);
SELECT CAST(a1 AS STRING) a1, CAST(a2 AS STRING) a2, BIT_LENGTH(a1) a1_bits FROM bitvar_tbl;
a1 a2 a1_bits
8 8 1
a a 4
aa aa 8
aaa NULL 12

INSERT INTO bitvar_tbl (a2) VALUES (0xaaa) fails, because 12 bits do not fit in BIT VARYING(8).

ENUM is an ordered set of distinct string constants, the enum values. A column of this type holds one of them (or NULL).

ENUM ( 'value1' [, 'value2' ...] )
  • An ENUM has at most 512 values, and the values must be unique (Duplicate values in enum type).
  • Each value has an index: 1 for the first value, 2 for the second, and so on. Only the index is stored, in 2 bytes.
  • A DEFAULT value can be declared.
  • A value that is not in the set is rejected: Cannot coerce 'c' to type enum.

The examples below use a shipment status column:

CREATE TABLE shipment (
id INT,
status ENUM ('pending', 'packed', 'shipped', 'delivered') DEFAULT 'pending'
);
Value Index
NULL NULL
'pending' 1
'packed' 2
'shipped' 3
'delivered' 4

You can insert either the value or its index:

INSERT INTO shipment (id, status) VALUES (1, 'shipped'), (2, 1), (3, 'delivered'), (4, 'packed');
INSERT INTO shipment (id) VALUES (5); -- DEFAULT 'pending'

In expressions an ENUM behaves as its index in a numeric context and as its value in a string context:

SELECT id, status, status + 0 AS idx, CONCAT(status, '!') AS txt FROM shipment ORDER BY id;
id status idx txt
1 shipped 3 shipped!
2 pending 1 pending!
3 delivered 4 delivered!
4 packed 2 packed!
5 pending 1 pending!

When an ENUM is converted to another type, numeric types use the index and all other types use the value:

Target type Uses
SHORT, INTEGER, BIGINT, FLOAT, DOUBLE, NUMERIC Index
CHAR, VARCHAR, BIT, BIT VARYING, DATE, TIME, DATETIME, TIMESTAMP Value

In = and IN predicates of the form enum_column operator constant, CoraDB converts the constant to the ENUM type, so that an index can be used. A constant that cannot be converted makes the comparison false instead of raising an error.

Predicate Matches
status = 'packed' Row 4
status = 2 Row 4 (index 2 is 'packed')
status = 'lost', status = 15, status = DATE'2010-01-01' Nothing, Without error

With every other comparison operator, the ENUM is converted to the type of the other operand. Two ENUM values are compared as strings. Only = and IN can use an index.

Predicate Compared as Matches
status < 'q' Strings pending, delivered, packed, pending (rows 2, 3, 4, 5)
status > 3 Indexes delivered (row 3)
status > DATE'2012-01-01' Error: Cannot coerce value of domain "enum" to domain "date".

ENUM values sort by index, that is in the order of the definition. To sort alphabetically, cast to VARCHAR:

SELECT status FROM shipment ORDER BY status;
SELECT status FROM shipment ORDER BY CAST(status AS VARCHAR);
ORDER BY status ORDER BY CAST(status AS VARCHAR)
pending delivered
pending packed
packed pending
shipped pending
delivered shipped

Every ENUM column has its own set of values; the type cannot be shared between columns. Comparing two ENUM columns compares their values as strings, even if both columns define the same set.

ALTER TABLE … CHANGE can redefine the set. Existing rows are converted by value, not by index. Adding a value works:

ALTER TABLE shipment CHANGE status status ENUM ('pending', 'packed', 'shipped', 'delivered', 'returned');

Removing a value that is still used fails with the default configuration:

ALTER TABLE shipment CHANGE status status ENUM ('pending', 'shipped', 'delivered');
ERROR: ALTER TABLE .. CHANGE : changing to new domain : cast failed, current configuration doesn't allow truncation or overflow.

Update the rows that use the value first, then change the column.

Drivers return ENUM values as strings. In JDBC:

Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT status FROM shipment");
while (rs.next()) {
System.out.println(rs.getString(1));
}

In CCI, fetch the column with CCI_A_TYPE_STR:

req = cci_prepare(conn, "SELECT status FROM shipment", 0, &err);
res = cci_execute(req, 0, 0, &err);
while (cci_cursor(req, 1, CCI_CURSOR_CURRENT, &err) == CCI_ER_NO_ERROR) {
char *data; int ind;
cci_fetch(req, &err);
cci_get_data(req, 1, CCI_A_TYPE_STR, &data, &ind);
printf("%s\n", data);
}