Charset and collation of columns, tables and expressions
Every string value in CoraDB has a charset and a collation. This page explains where they come from and how CoraDB chooses between them when values with different settings meet. For the concepts and the list of collations, see Globalization.
Collation
Section titled “Collation”A collation defines how characters and strings are compared and sorted. The charset and collation of a value are determined as follows:
| Value | Charset and collation |
|---|---|
| Column | Its CHARSET / COLLATE modifiers, otherwise those of its table, otherwise those of the database |
| Table | Its CHARSET / COLLATE clauses, otherwise those of the database |
| String literal | Its charset introducer or COLLATE modifier, otherwise those set by SET NAMES, otherwise those of the database |
| Expression | Inferred from its arguments by coercibility |
The database charset comes from the locale given to coradb createdb; the database collation is always the bin collation of that charset (utf8_bin for a UTF-8 database such as the e-commerce sample).
Charset and collation of column
Section titled “Charset and collation of column”Charsets and collations apply to the string types CHAR, VARCHAR (STRING) and ENUM.
Charset
Section titled “Charset”The supported charsets are:
| Charset | Name in SQL | Notes |
|---|---|---|
| ISO-8859-1 | iso88591 |
One byte per character |
| UTF-8 | utf8 |
One to four bytes per character, code points 0 to 10FFFF |
| EUC-KR | euckr |
For backward compatibility only; not recommended |
| binary | binary |
Raw bytes, no character semantics |
String check
Section titled “String check”Input strings are assumed to be in the database charset, unless SET NAMES or a charset introducer says otherwise (see Charset and collation of string literals). CoraDB does not check by default that UTF-8 and EUC-KR input is correctly encoded; invalid input can lead to undefined behavior. Turn checking on with the system parameter intl_check_input_string if your clients may send invalid data, and leave it off for better performance if they do not. ISO-8859-1 needs no check, because every byte is a valid character.
Charset conversion
Section titled “Charset conversion”When a modifier or collation inference requires it, values are converted from one charset to another. Conversion translates characters (transcoding) and is not reversible. A character that does not exist in the destination charset is replaced with ?; this also applies when converting binary data. Bytes 80–A0, which are not valid ISO-8859-1 characters, become ? when converted to UTF-8.
| Source \ destination | binary | ISO-8859-1 | UTF-8 | EUC-KR |
|---|---|---|---|---|
| binary | no change | No change: same bytes and length | Bytes kept, each character validated, invalid ones become ? |
Bytes kept, each character validated, invalid ones become ? |
| ISO-8859-1 | no change | no change | Converted; byte size grows, no loss | Converted; byte size grows, no loss |
| UTF-8 | Bytes kept; character length grows | Converted; byte size may shrink, characters may be lost | no change | Converted; byte size may shrink, characters may be lost |
| EUC-KR | Bytes kept; character length grows | Converted; byte size may shrink, characters may be lost | Converted; byte size may grow, no loss | no change |
The precision (number of characters) is kept and the byte size changes. Converting UTF-8 or EUC-KR to ISO-8859-1 can truncate data.
Collation
Section titled “Collation”The collations of a database are listed in the db_collation catalog view and by SHOW COLLATION. The built-in collations, available without compiling locales, are:
SELECT coll_id, coll_name, charset_name, is_builtin, has_expansions, contractions, uca_strengthFROM db_collation WHERE is_builtin = 'Yes' ORDER BY coll_id;| coll_id | coll_name | charset_name | is_builtin | has_expansions | contractions | uca_strength |
|---|---|---|---|---|---|---|
| 0 | iso88591_bin | iso88591 | Yes | No | 0 | Not applicable |
| 1 | utf8_bin | utf8 | Yes | No | 0 | Not applicable |
| 2 | iso88591_en_cs | iso88591 | Yes | No | 0 | Not applicable |
| 3 | iso88591_en_ci | iso88591 | Yes | No | 0 | Not applicable |
| 4 | utf8_en_cs | utf8 | Yes | No | 0 | Not applicable |
| 5 | utf8_en_ci | utf8 | Yes | No | 0 | Not applicable |
| 6 | utf8_tr_cs | utf8 | Yes | No | 0 | Not applicable |
| 7 | utf8_ko_cs | utf8 | Yes | No | 0 | Not applicable |
| 8 | euckr_bin | euckr | Yes | No | 0 | Not applicable |
| 9 | binary | binary | Yes | No | 0 | Not applicable |
Every collation belongs to one charset, so a charset and a collation that do not match cannot be combined. With only COLLATE, the charset is the collation's charset; with only CHARSET, the collation is the charset's bin collation: iso88591_bin, utf8_bin, euckr_bin or binary (binary is both a charset and its collation).
CHARSET and COLLATE modifier
Section titled “CHARSET and COLLATE modifier”data_type [ { CHARACTER_SET | CHARSET } charset_name ] [ COLLATE collation_name ]The names can be written as identifiers or string literals. Examples:
CREATE TABLE note (txt VARCHAR(100) CHARSET utf8);ALTER TABLE note CHANGE txt txt CHAR(10) COLLATE utf8_en_cs; -- charset utf8 from the collation
-- sort case-insensitively without changing the columnSELECT name FROM city ORDER BY CAST(name AS VARCHAR(32) COLLATE utf8_en_ci);SELECT name FROM city ORDER BY name COLLATE utf8_en_ci;COLLATE on an expression is cheaper than CAST, but it can only change the collation within the same charset; CAST can also convert the charset.
How to determine collation among columns with different collation
Section titled “How to determine collation among columns with different collation”When the arguments of an operator or function have different collations, CoraDB must choose one. If it cannot, the statement fails:
CREATE TABLE coll_t ( s1 STRING COLLATE utf8_en_cs, s2 STRING COLLATE utf8_tr_cs, s3 STRING COLLATE utf8_en_ci, s4 STRING COLLATE utf8_bin);SELECT s1 FROM coll_t WHERE s1 > s2;ERROR: '>' requires arguments with compatible collations.The choice is based on collation coercibility: how readily a value gives up its collation. Lower numbers win.
- The argument with the lowest coercibility determines the collation; arguments with higher coercibility are converted to it.
- If arguments with the same coercibility have different collations, the collation cannot be resolved and an error is raised, with one exception: two host or session variables (coercibility 11) with the same charset, one of them with a bin collation, use the other's collation. See Session and host variables.
| Coercibility | Argument |
|---|---|
| -1 | Expression whose arguments are all host variables (decided at execution) |
| 0 | Operand with a COLLATE modifier |
| 1 | Column with a non-bin, non-binary collation |
| 2 | Column with the binary collation |
| 3 | Column with a bin collation (iso88591_bin, utf8_bin, euckr_bin) |
| 4 | SELECT value or expression with a non-bin, non-binary collation |
| 5 | SELECT value or expression with the binary collation |
| 6 | SELECT value or expression with a bin collation |
| 7 | Special functions: SYSTEM_USER, DATABASE, SCHEMA, VERSION |
| 8 | String literal with a non-bin, non-binary collation |
| 9 | String literal with the binary collation |
| 10 | String literal with a bin collation |
| 11 | Host variable, session variable |
COERCIBILITY returns the value for an expression:
SELECT COERCIBILITY(s1), COERCIBILITY(s4), COERCIBILITY(CONCAT(s1, '')), COERCIBILITY(CONCAT(s4, '')), COERCIBILITY('a'), COERCIBILITY('a' COLLATE utf8_en_ci), COERCIBILITY(_binary'a'), COERCIBILITY(DATABASE())FROM coll_t;-- 1, 3, 4, 6, 10, 0, 9, 7Resolving conflicts. With the table above:
| Condition | Result |
|---|---|
s1 > s2 |
Error: two columns (1 and 1) with different collations |
s1 > CAST(s2 AS STRING COLLATE utf8_en_cs) |
Compared with utf8_en_cs |
s1 > CAST(s2 AS STRING COLLATE utf8_tr_cs) |
The CAST is an expression (4), so it is converted to s1's utf8_en_cs |
s1 > CONCAT(s2, '') |
Expression (4) is converted to s1's collation (1) |
s1 > s4 |
s4 has a bin collation (3), so utf8_en_cs is used |
s1 > 'abc' |
The literal (10) takes s1's collation |
s1 > s2 + s3 |
Error: '+' requires arguments with compatible collations. (s2 and s3, both 1) |
Numbers and dates that are converted to strings always take the other string's collation. A column with an ISO-8859-1 bin collation compared with a UTF-8 column is converted to UTF-8, at some cost.
Expressions with only host variables. The coercibility of UPPER(?) is not known before execution, so COERCIBILITY returns -1. If all arguments have coercibility 11 and different collations, the common collation is resolved at run time instead of raising an error:
PREPARE st FROM 'SELECT COLLATION(UPPER(?)), COERCIBILITY(UPPER(?))';EXECUTE st USING 'a', 'a'; -- utf8_bin, -1
PREPARE st1 FROM 'SELECT INSERT(?, 2, 2, ?)';EXECUTE st1 USING _utf8'abcd', _binary'ef'; -- 'aefd'Session and host variables. When a host variable and a session variable with the same charset are compared and one has a bin collation, the other's collation is used:
SET NAMES utf8;SET @v1 = 'a'; -- utf8_binPREPARE stmt FROM 'SELECT COLLATION(?), COLLATION(@v1), ? = @v1';
SET NAMES utf8 COLLATE utf8_en_ci;EXECUTE stmt USING 'A', 'A'; -- utf8_en_ci, utf8_bin, 1: compared case-insensitively
SET NAMES utf8 COLLATE utf8_en_cs;EXECUTE stmt USING 'A', 'A'; -- utf8_en_cs, utf8_bin, 0If neither has a bin collation and the collations differ (for example @v1 set under utf8_en_ci and the parameter under utf8_en_cs), the comparison fails with Context requires compatible collations.
Charset and collation of an ENUM type column
Section titled “Charset and collation of an ENUM type column”An ENUM column takes the charset and collation of its table or database, not those of its value literals: in the e-commerce database, ENUM(_iso88591'a', _iso88591'b') is still a utf8_bin column. Give the column or the table a COLLATE clause to change it:
CREATE TABLE t (e ENUM ('a', 'b') COLLATE utf8_en_ci);CREATE TABLE t (e ENUM ('a', 'b')) COLLATE utf8_en_ci;Charset and collation of tables
Section titled “Charset and collation of tables”CREATE TABLE table_name ( column_definitions ) [ CHARSET charset_name ] [ COLLATE collation_name ];Columns without their own settings use the table's; a table without settings uses the database's. A column that specifies only a charset gets that charset's bin collation, regardless of the table collation:
CREATE TABLE note (col STRING CHARSET utf8, c2 STRING) COLLATE utf8_en_ci;SHOW FULL COLUMNS FROM note;| Field | Type | Collation |
|---|---|---|
| col | VARCHAR(1073741823) | utf8_bin |
| c2 | VARCHAR(1073741823) | utf8_en_ci |
Charset and collation of string literals
Section titled “Charset and collation of string literals”The charset and collation of a string literal are taken from the first that applies:
- Its charset introducer or COLLATE modifier;
- The last SET NAMES of the session;
- The database charset and its bin collation.
SET NAMES statement
Section titled “SET NAMES statement”SET NAMES sets the charset and collation of the string literals sent by the client in this session.
SET NAMES [ charset_name ] [ COLLATE collation_name ];- charset_name:
iso88591,utf8,euckrorbinary. - collation_name: any collation of that charset (see
db_collation); without it, the charset's bin collation. An incompatible pair is an error.
SET NAMES sets the session value of the system parameter intl_collation: SET NAMES utf8 is the same as SET SYSTEM PARAMETERS 'intl_collation=utf8_bin'.
Charset introducer
Section titled “Charset introducer”A charset introducer, the charset name with a leading underscore, gives one literal a charset; a COLLATE modifier gives it a collation:
[ _utf8 | _iso88591 | _euckr | _binary ] 'string' [ COLLATE collation_name ]- With an introducer and no COLLATE: the client collation if the introducer matches the client charset (from SET NAMES), otherwise the introducer's bin collation.
- With COLLATE and no introducer: the collation's charset.
- An introducer only labels the bytes as written; it does not convert them.
_iso88591'Ç'sent from a UTF-8 client contains the two UTF-8 bytes C3 87.
SELECT 'coradb', _utf8'coradb', _utf8'coradb' COLLATE utf8_en_cs;
SET NAMES utf8 COLLATE utf8_en_ci;SELECT 'a' COLLATE utf8_en_cs; -- the COLLATE modifier overrides SET NAMESCharset and collation of expressions
Section titled “Charset and collation of expressions”The charset and collation of an expression are inferred from its arguments by coercibility:
SELECT COLLATION(CONCAT(s1, s4)) FROM coll_t; -- utf8_en_cs: the column with coercibility 1 wins over 3All string matching functions (LIKE, REPLACE, INSTR, POSITION, LOCATE, SUBSTRING_INDEX, FIND_IN_SET, …) and comparison operators use the collation.
Charset and collation of system data
Section titled “Charset and collation of system data”The system charset is the charset of the database locale; the system collation is always its bin collation (iso88591_bin, euckr_bin or utf8_bin). It applies to identifiers and to the values in the system catalog.
Impact of charset specified when creating DB
Section titled “Impact of charset specified when creating DB”The locale given when the database is created also determines:
- Which characters identifiers can contain and how they are cased (the alphabet);
- The default language of date/string and number/string conversion functions;
- The console conversion in corasql.
Casing and identifiers
Section titled “Casing and identifiers”Identifiers are case-insensitive. Table, column, session variable, trigger and stored procedure names are stored in lower case; user and group names in upper case.
- ISO-8859-1 and EUC-KR casing is built in; EUC-KR cases only ASCII characters.
- The built-in UTF-8 locales (
en_US.utf8,ko_KR.utf8,tr_TR.utf8) case only their own letters: ASCII, plus Turkish letters fortr_TR.utf8. Other characters are allowed in identifiers but are not converted:CREATE TABLE ÈABCcreates a table namedÈabc. - LDML locales (compiled with
make_locale) case all Unicode characters up to FFFF: withes_ES.utf8,CREATE TABLE ÈABCcreatesèabc.
Some languages have special casing rules: in Turkish, LOWER('I') is ı (dotless i) and UPPER('i') is İ; in German, UPPER('ß') is SS. Such locales have two alphabets: one with the special rules for user data and one without them for identifiers, so that identifiers stay compatible between databases with different locales. With the built-in utf8_tr_cs collation:
SELECT UPPER(_utf8'istanbul' COLLATE utf8_tr_cs), UPPER(_utf8'istanbul' COLLATE utf8_en_cs), LOWER('I' COLLATE utf8_tr_cs);-- İSTANBUL, ISTANBUL, ıString literal input and output
Section titled “String literal input and output”Strings reach CoraDB through the CCI API, the language drivers (JDBC, Python, Node.js, …) and corasql. CoraDB treats the bytes between quotes as raw data; the client is responsible for telling which charset they are in, through the connection settings, SET NAMES or charset introducers.
Text conversion for corasql
Section titled “Text conversion for corasql”corasql can convert between the console's encoding and the database charset. A locale's LDML file may declare the console encoding it supports, for example for tr_TR.utf8:
<consoleconversion type="ISO88599" windows_codepage="28599" linux_charset="iso88599,ISO_8859-9,ISO8859-9,ISO-8859-9">If the console uses one of these encodings (chcp 28599 on Windows, export LANG=tr_TR.iso88599 on Linux), corasql converts input from ISO-8859-9 to UTF-8 and output back. At input, everything is converted if it contains characters that need it; at output, only the result data. Locales without this tag (for example km_KH.utf8) have no console conversion.
Example: French. Enable fr_FR in coradb_locales.txt, compile the locales (see Locale setting) and create the database with fr_FR.utf8. Then either set the console to UTF-8 (LANG=fr_FR.utf8 on Linux), which accepts any character, or to ISO-8859-15 (LANG=fr_FR.iso885915 on Linux, chcp 28605 on Windows) with the matching linux_charset="iso885915" or windows_codepage="28605" in the LDML tag.
Example: Romanian. Enable ro_RO, compile, create the database with ro_RO.utf8. Use a UTF-8 console, or ISO-8859-2 (LANG=ro_RO.iso88592, linux_charset="iso88592") on Linux, or codepage 1250 (chcp 1250, windows_codepage="1250") on Windows. Codepage 1250 lacks some ISO-8859-2 characters, and typing S and T with comma below on Windows requires the Romanian (legacy) keyboard.
Unicode normalization
Section titled “Unicode normalization”A glyph can be written in different ways in Unicode. "Ä" is one code point in composed form (00C4, UTF-8 bytes C3 84) and two in decomposed form (0041 0308, UTF-8 bytes 41 CC 88). CoraDB can convert decomposed input to composed form and composed output to decomposed form; normalization does not depend on the locale.
- unicode_input_normalization =
yescomposes input. - unicode_output_normalization =
yesdecomposes output.
Enable both for clients that only handle decomposed text. Enable only input normalization for clients that send both forms but accept composed output. Only code points 0000–FFFF are normalized.
Contraction and expansion of collation
Section titled “Contraction and expansion of collation”LDML collations of the UTF-8 charset can define contractions and expansions. They change the results of comparisons and therefore affect several features; see Collation settings impacting CoraDB features.
The collations are based on the Unicode Collation Algorithm and its default table, DUCET (http://www.unicode.org/Public/UCA/latest/allkeys.txt). Each code point has one or more collation elements of four weights, one per comparison level (base letter, accent, case, tie-breaker). The Korean letter kiyeok, for example:
1100 ; [.313B.0020.0002.1100] # HANGUL CHOSEONG KIYEOKCoraDB uses code points 0000–FFFF only.
Contraction
Section titled “Contraction”A contraction is a sequence of code points that sorts as one letter. In traditional Spanish sorting, "ch" is a letter after "c": all words starting with "ch" come after all other words starting with "c". Contractions work with and without expansions; the collation stores a table of contractions.
Expansion
Section titled “Expansion”An expansion is a code point with more than one collation element, so that it compares like a sequence of letters: "æ" like "ae", or in German "Ä" like "AE". Expansions are enabled in a collation's LDML definition with CoraDBExpansions="use"; collations with expansions have exp in their name.
- Without expansions, every code point gets a single weight per level and strings are compared character by character. With DUCET weights, "Ar" and "Är" are equal at primary strength and "Ar" < "Är" at secondary and tertiary strength.
- With expansions, the collation elements of all characters are concatenated and the lists are compared level by level, which is slower but gives whole-word ordering. If "Ä" expands to "A" + "E" (German), then "Ar" > "Är", because R sorts after E at the first level.
Accent ordering. In Canadian French sorting (utf8_fr_exp_ab, which requires expansions), accents are compared from the end of the string:
- Normal accent ordering: cote < coté < côte < côté
- Backward accent ordering: cote < côte < coté < côté
Operations requiring collation and charset
Section titled “Operations requiring collation and charset”Charset
Section titled “Charset”Functions that work on characters need the charset; OCTET_LENGTH and BIT_LENGTH do not, because they count bytes. The same character can take a different number of bytes:
SELECT OCTET_LENGTH(_utf8'È'), LENGTH(_utf8'È'); -- 2, 1Collation
Section titled “Collation”Functions and operators that compare or match strings need the collation: comparisons, STRCMP, POSITION, LIKE, REPLACE, INSTR, LOCATE, SUBSTRING_INDEX, FIND_IN_SET, ORDER BY, GROUP BY, DISTINCT and others.
UPPER and LOWER use the user alphabet of the collation's default locale:
- The locale in the name:
utf8_tr_cs→tr_TR.utf8,iso88591_en_ci→en_US(ISO-8859-1); - The bin collations:
iso88591_bin→en_US(ISO-8859-1),utf8_bin→en_US.utf8(ASCII only),euckr_bin→ko_KR.euckr(ASCII only); - Generic LDML collations (
utf8_gen,utf8_gen_ci,utf8_gen_ai_ci): the first locale in$CORADB/conf/coradb_locales.txtthat contains them,de_DEin the default alphabetical order.
Charset conversion
Section titled “Charset conversion”Converting a value to another charset keeps its precision (number of characters); the byte size may change. Converting UTF-8 or EUC-KR to ISO-8859-1 keeps the precision and may truncate data. In a database created with an ISO-8859-1 locale, for example, a UTF-8 client that inserts 'Ç' (two bytes in UTF-8) into a CHAR(1) column stores a converted or truncated value, because the column holds one ISO-8859-1 byte.
Collation settings impacting CoraDB features
Section titled “Collation settings impacting CoraDB features”LIKE conditional optimization
Section titled “LIKE conditional optimization”For a collation without expansions, every character has one weight, so a prefix pattern can be turned into a range that an index can use:
s LIKE 'abc%' → s >= 'abc' AND s < 'abd'For collations with expansions, or that give several characters the same weight (case- or accent-insensitive collations), the range is not exact. CoraDB then keeps the LIKE condition after the range, as a filter:
s LIKE 'abc%' → s >= 'abc' AND s < 'abd' AND s LIKE 'abc%'Index covering
Section titled “Index covering”In a collation that does not distinguish 'abc' and 'ABC', an index stores only one of the values (whichever was inserted first). A covering index would then return the wrong spelling, so covering index scans are not used for such collations. In LDML, collations with strength="tertiary" or "quaternary" distinguish case; quaternary needs more memory and is slower.
Summary of CoraDB features for each collation
Section titled “Summary of CoraDB features for each collation”| Collation | LIKE kept after rewrite to a range | Index covering |
|---|---|---|
| iso88591_bin | no | yes |
| iso88591_en_cs | no | yes |
| iso88591_en_ci | yes | no |
| utf8_bin | no | yes |
| euckr_bin | no | yes |
| utf8_en_cs | no | yes |
| utf8_en_ci | yes | no |
| utf8_tr_cs | no | yes |
| utf8_ko_cs | no | yes |
| utf8_gen | no | yes |
| utf8_gen_ai_ci | yes | no |
| utf8_gen_ci | yes | no |
| utf8_de_exp_ai_ci | yes | no |
| utf8_de_exp | yes | no |
| utf8_ro_cs | no | yes |
| utf8_es_cs | no | yes |
| utf8_fr_exp_ab | yes | no |
| utf8_ja_exp | yes | no |
| utf8_ja_exp_cbm | yes | no |
| utf8_km_exp | yes | no |
| utf8_ko_cs_uca | no | yes |
| utf8_tr_cs_uca | no | yes |
| utf8_vi_cs | no | yes |
| binary | no | yes |
Viewing collation information
Section titled “Viewing collation information”- CHARSET, COLLATION and COERCIBILITY return the charset, collation and coercibility of an expression.
- The db_collation catalog view and SHOW COLLATION list the collations of the database.
- SHOW FULL COLUMNS shows the collation of each column.
Using i18n characters with JDBC
Section titled “Using i18n characters with JDBC”The CoraDB JDBC driver returns string values as Java String objects (UTF-16), converted from the charset that the server sends with each value: the charset of the column or expression, or the system charset. Values with the binary charset are not converted; they are returned as coradb.jdbc.driver.CORADBBinaryString objects, which wrap the bytes. CORADBResultSetMetaData.getColumnCharset() tells which case applies.
A table with a UTF-8 column and a binary column:
CREATE TABLE label (txt VARCHAR(10) CHARSET utf8, raw VARCHAR(10) CHARSET binary);Inserting a string and raw bytes:
PreparedStatement st = conn.prepareStatement("INSERT INTO label VALUES (?, ?)");st.setObject(1, "abc");st.setObject(2, new CORADBBinaryString(new byte[] { (byte) 161, (byte) 224 }));st.executeUpdate();Reading them back, as text or as bytes depending on the column charset:
Statement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery("SELECT txt, raw FROM label");CORADBResultSetMetaData md = (CORADBResultSetMetaData) rs.getMetaData();while (rs.next()) { for (int j = 1; j <= md.getColumnCount(); j++) { if ("BINARY".equals(md.getColumnCharset(j))) { byte[] bytes = ((CORADBBinaryString) rs.getObject(j)).getBytes(); System.out.println(java.util.HexFormat.of().formatHex(bytes)); } else { System.out.println(rs.getString(j)); } }}