33. Text and Thai

How SQL counts, searches, compares and sorts text, and what to watch for when the text is Thai.

length() counts characters, not what you see

length(x) of a text counts its characters. In Thai that is not always what the eye counts as letters: vowels above and below a consonant, tone marks and ำ are characters of their own:

SELECT length('Coffee') AS coffee, length('กาแฟ') AS kafae, length('น้ำ') AS nam, length('สวัสดี') AS sawasdee;
coffeekafaenamsawasdee
6436
1 row

กาแฟ is 4 characters, as it looks. But น้ำ is 3 (น, the tone mark ้, and ำ) and สวัสดี is 6 (ส ว ั ส ด ี), although it takes four places on the line.

Stored in the file, text is UTF-8, and each Thai character takes 3 bytes. octet_length(x) (or length of the text turned into a BLOB) counts bytes:

SELECT length(CAST('Coffee' AS BLOB)) AS coffee_bytes, length(CAST('กาแฟ' AS BLOB)) AS kafae_bytes, octet_length('กาแฟ') AS octets;
coffee_byteskafae_bytesoctets
61212
1 row

When a program limits a name to "50 letters", decide whether it means characters (length) or bytes (octet_length). A Thai name of 20 characters is 60 bytes; a column or a screen sized for 50 bytes will cut it off in the middle.

upper() and lower() leave Thai alone

upper and lower change the capitals of the English letters A to Z. Thai has no capitals, so Thai letters pass through untouched:

SELECT upper('Green Tea ชาเขียว') AS up, lower('BANGKOK กรุงเทพฯ') AS low;
uplow
GREEN TEA ชาเขียวbangkok กรุงเทพฯ
1 row

Thai words in a table of our own

The practice shop's names are in English. To try Thai, make a table of the products' Thai names, linked to product by product_id:

CREATE TABLE product_th (
  product_id INTEGER PRIMARY KEY REFERENCES product(id),
  name       TEXT NOT NULL
);

INSERT INTO product_th (name, product_id) VALUES
  ('กาแฟ', 1), ('ชาเขียว', 2), ('น้ำส้ม', 3), ('ครัวซองต์', 4),
  ('ขนมปังกล้วย', 5), ('ชีสเค้ก', 6), ('มันฝรั่งทอด', 7), ('มะม่วงอบแห้ง', 8),
  ('เม็ดมะม่วงหิมพานต์', 9), ('สมุด', 10), ('ปากกา', 11), ('ปากกาเน้นข้อความ', 12);

SELECT * FROM product_th;
product_idname
1กาแฟ
2ชาเขียว
3น้ำส้ม
4ครัวซองต์
5ขนมปังกล้วย
6ชีสเค้ก
7มันฝรั่งทอด
8มะม่วงอบแห้ง
9เม็ดมะม่วงหิมพานต์
10สมุด
11ปากกา
12ปากกาเน้นข้อความ
12 rows

Searching Thai: LIKE, instr, substr, trim

LIKE (chapter 5) works with Thai as with English: % is any run of characters, _ one character. Everything with มะม่วง (mango) in its name:

SELECT product_id, name FROM product_th WHERE name LIKE '%มะม่วง%' ORDER BY product_id;
product_idname
8มะม่วงอบแห้ง
9เม็ดมะม่วงหิมพานต์
2 rows

Dried mango, and cashew nuts too, whose Thai name เม็ดมะม่วงหิมพานต์ has มะม่วง inside it. A search for words that start with ปากกา (pen) finds the pen and the highlighter:

SELECT product_id, name FROM product_th WHERE name LIKE 'ปากกา%' ORDER BY product_id;
product_idname
11ปากกา
12ปากกาเน้นข้อความ
2 rows

instr(text, part) gives the place where part starts (counting characters from 1), or 0 when it isn't there. substr(text, start, n) cuts out n characters:

SELECT name, instr(name, 'ม่วง') AS at, substr(name, 1, 3) AS first_3
FROM product_th
WHERE instr(name, 'ม่วง') > 0;
nameatfirst_3
มะม่วงอบแห้ง3มะม
เม็ดมะม่วงหิมพานต์7เม็
2 rows

Look at first_3 of the second row: เม็ is three characters (เ, ม, the mark ็), not three letters you would read. Cutting Thai by characters can leave a mark without its letter, or a word cut in half.

A Thai search must match every mark. Someone who types มะมวง, forgetting the tone mark, finds nothing at all:

SELECT (SELECT count(*) FROM product_th WHERE name LIKE '%มะม่วง%') AS with_mark,
       (SELECT count(*) FROM product_th WHERE name LIKE '%มะมวง%') AS without_mark;
with_markwithout_mark
20
1 row

trim takes spaces off both ends, ltrim only the left (the start), rtrim only the right. Give it a second argument and it takes off those characters instead of spaces. The [ ] show where the text begins and ends:

SELECT '[' || trim('  ชาเขียว  ') || ']', '[' || ltrim('  ชาเขียว  ') || ']', '[' || rtrim('  ชาเขียว  ') || ']', trim('--ชาเขียว--', '-');
'[' || trim(' ชาเขียว ') || ']''[' || ltrim(' ชาเขียว ') || ']''[' || rtrim(' ชาเขียว ') || ']'trim('--ชาเขียว--', '-')
[ชาเขียว][ชาเขียว ][ ชาเขียว]ชาเขียว
1 row

COLLATE NOCASE: comparing without capitals

Normally = compares text exactly, capitals included. COLLATE NOCASE after a comparison makes it ignore the difference between capitals and small letters:

SELECT 'Bangkok' = 'BANGKOK', 'Bangkok' = 'BANGKOK' COLLATE NOCASE;
'Bangkok' = 'BANGKOK''Bangkok' = 'BANGKOK' COLLATE NOCASE
01
1 row

Useful when people type a city in all sorts of ways:

SELECT name, city FROM customer WHERE city = 'bangkok' COLLATE NOCASE ORDER BY id;
namecity
Somchai JaideeBangkok
Anan WongsaBangkok
Wichai SaelimBangkok
Lalita MeesukBangkok
4 rows

NOCASE knows only the English letters A to Z. Letters such as É and é are still different to it; and Thai has no capitals, so NOCASE changes nothing for Thai:

SELECT 'élan' = 'ÉLAN' COLLATE NOCASE AS accented, 'elan' = 'ELAN' COLLATE NOCASE AS plain;
accentedplain
01
1 row

Sorting Thai: code order and dictionary order

ORDER BY on text sorts by each character's number in Unicode (its code point), one character at a time. For English that is alphabetical order. For Thai it is nearly right, with one big exception:

SELECT name FROM product_th ORDER BY name;
name
กาแฟ
ขนมปังกล้วย
ครัวซองต์
ชาเขียว
ชีสเค้ก
น้ำส้ม
ปากกา
ปากกาเน้นข้อความ
มะม่วงอบแห้ง
มันฝรั่งทอด
สมุด
เม็ดมะม่วงหิมพานต์
12 rows

เม็ดมะม่วงหิมพานต์ comes last, after สมุด. The vowels written before a consonant, เ แ โ ใ ไ, have bigger numbers than every consonant, so every word starting with them goes to the end. A Thai dictionary sorts by the consonant first: เม็ด belongs with the ม words. A short list shows it plainly:

SELECT column1 AS word FROM (VALUES ('ไก่'), ('กา'), ('เกาะ'), ('ขนม'), ('แกง'), ('โต๊ะ'), ('ข้าว'), ('ใจ'), ('จาน'), ('ก้าว'))
ORDER BY word;
word
กา
ก้าว
ขนม
ข้าว
จาน
เกาะ
แกง
โต๊ะ
ใจ
ไก่
10 rows

เกาะ, แกง, โต๊ะ, ใจ and ไก่ are all at the bottom, after จาน.

Phai SQL has a collation of its own for this, COLLATE THAI: Thai dictionary order. A leading vowel is sorted after the consonant it is written before (as it is said), and tone marks only decide between words that are otherwise the same (กา before ก่า before ก้า):

Phai SQL
SELECT column1 AS word FROM (VALUES ('ไก่'), ('กา'), ('เกาะ'), ('ขนม'), ('แกง'), ('โต๊ะ'), ('ข้าว'), ('ใจ'), ('จาน'), ('ก้าว'))
ORDER BY word COLLATE THAI;
word
กา
ก้าว
เกาะ
แกง
ไก่
ขนม
ข้าว
จาน
ใจ
โต๊ะ
10 rows

Now the ก words are together (กา, ก้าว, เกาะ, แกง, ไก่), then the ข words, จ, and โต๊ะ last, under ต. The product names in dictionary order:

Phai SQL
SELECT name FROM product_th ORDER BY name COLLATE THAI;
name
กาแฟ
ขนมปังกล้วย
ครัวซองต์
ชาเขียว
ชีสเค้ก
น้ำส้ม
ปากกา
ปากกาเน้นข้อความ
มะม่วงอบแห้ง
มันฝรั่งทอด
เม็ดมะม่วงหิมพานต์
สมุด
12 rows

เม็ดมะม่วงหิมพานต์ is now among the ม words, after มันฝรั่งทอด and before สมุด.

COLLATE THAI is Phai SQL's own; SQLite hasn't got it. The same query in SQLite stops with the error "no such collation sequence: THAI". The blocks marked Phai SQL in this chapter run on Phai SQL only.

Because a Phai SQL file must stay a SQLite file that SQLite can read and check, COLLATE THAI is for queries only (ORDER BY, WHERE, GROUP BY), never part of a table or an index. Phai SQL refuses it there, with a clear message:

Phai SQL
CREATE TABLE word (w TEXT COLLATE THAI);
Error: not supported yet: COLLATE THAI in a table or index: SQLite has no THAI collation, so it couldn't check or write the file; use it in queries (ORDER BY name COLLATE THAI)

Searching people's names goes wrong far more often because of how the names were typed than because of SQL. Here are the customers' names in Thai, in a table of their own; two of them were typed carelessly, as happens in real data: Malee's has two spaces in the middle, Anan's a space at the start:

CREATE TABLE customer_th (
  id   INTEGER PRIMARY KEY REFERENCES customer(id),
  name TEXT NOT NULL,
  city TEXT
);

INSERT INTO customer_th (name, city, id) VALUES
  ('สมชาย ใจดี', 'กรุงเทพฯ', 1), ('มาลี  ศรีสุข', 'เชียงใหม่', 2), (' อนันต์ วงศา', 'กรุงเทพฯ', 3),
  ('พิม ไชยา', 'ภูเก็ต', 4), ('นรินทร์ ทองดี', 'ขอนแก่น', 5), ('กันยา บุญมี', 'เชียงใหม่', 6),
  ('วิชัย แซ่ลิ้ม', 'กรุงเทพฯ', 7), ('ศิริพร แก้วดี', 'ภูเก็ต', 8), ('ตะวัน รุ่งเรือง', 'ขอนแก่น', 9),
  ('ลลิตา มีสุข', 'กรุงเทพฯ', 10);
✓ 10 rows changed

Look for the two of them by name, typed properly:

SELECT id, name FROM customer_th WHERE name = 'มาลี ศรีสุข' OR name = 'อนันต์ วงศา' ORDER BY id;
idname
no rows

Nothing. The spaces are invisible on screen, but [ ] and length show them:

SELECT id, '[' || name || ']' AS name, length(name) FROM customer_th WHERE id IN (2, 3);
idnamelength(name)
2[มาลี ศรีสุข]12
3[ อนันต์ วงศา]12
2 rows

The cure is to tidy the data once, and to tidy everything that goes in from then on the same way: trim the ends, and turn double spaces into one. The WHERE changes only the rows that need it:

UPDATE customer_th SET name = trim(replace(name, '  ', ' '))
WHERE name <> trim(replace(name, '  ', ' '));
SELECT id, name FROM customer_th WHERE name = 'มาลี ศรีสุข' OR name = 'อนันต์ วงศา' ORDER BY id;
idname
2มาลี ศรีสุข
3อนันต์ วงศา
2 rows

2 rows tidied, and both are found now. (One replace turns each pair of spaces into one; three spaces in a row would need it again.)

Thai has a trap of its own as well: some marks can be typed in two ways that look exactly the same. ำ (sara am) is one character, but some people type the circle ํ and า instead, two characters. To SQL they are different texts:

SELECT 'น้ำ' = 'น้ํา' AS same, length('น้ำ') AS len_1, length('น้ํา') AS len_2,
       replace('น้ํา', 'ํา', 'ำ') = 'น้ำ' AS same_after;
samelen_1len_2same_after
0341
1 row

They look alike but are not equal; one is 3 characters, the other 4. After replace turns ํา into ำ, they match.

Search tips for Thai: keep spaces one way everywhere (one space between first name and surname, none at the ends); turn look-alike forms into one form (ํา into ำ) when the data goes in, not at every search; search with LIKE '%...%' when people may type only part of a name; and sort with COLLATE THAI when Thai people will read the list.

With the names tidied, here are the customers by city and then by name, both in dictionary order. In plain code order เชียงใหม่ would come last, after ภูเก็ต; in dictionary order it sits under ช:

Phai SQL
SELECT name, city FROM customer_th ORDER BY city COLLATE THAI, name COLLATE THAI;
namecity
ลลิตา มีสุขกรุงเทพฯ
วิชัย แซ่ลิ้มกรุงเทพฯ
สมชาย ใจดีกรุงเทพฯ
อนันต์ วงศากรุงเทพฯ
ตะวัน รุ่งเรืองขอนแก่น
นรินทร์ ทองดีขอนแก่น
กันยา บุญมีเชียงใหม่
มาลี ศรีสุขเชียงใหม่
พิม ไชยาภูเก็ต
ศิริพร แก้วดีภูเก็ต
10 rows
  1. Show the Thai names of the products that have กา in them, with their length in characters.
  2. From customer, show the customers whose city is BANGKOK, ignoring capitals, sorted by name.
  3. (Phai SQL) Show the Thai names of all customers in Thai dictionary order.
Show the answer
SELECT name, length(name) FROM product_th WHERE name LIKE '%กา%' ORDER BY product_id;

SELECT name, city FROM customer WHERE city = 'BANGKOK' COLLATE NOCASE ORDER BY name;
namelength(name)
กาแฟ4
ปากกา5
ปากกาเน้นข้อความ16
3 rows
namecity
Anan WongsaBangkok
Lalita MeesukBangkok
Somchai JaideeBangkok
Wichai SaelimBangkok
4 rows
Show the answer
Phai SQL
SELECT name FROM customer_th ORDER BY name COLLATE THAI;
name
กันยา บุญมี
ตะวัน รุ่งเรือง
นรินทร์ ทองดี
พิม ไชยา
มาลี ศรีสุข
ลลิตา มีสุข
วิชัย แซ่ลิ้ม
ศิริพร แก้วดี
สมชาย ใจดี
อนันต์ วงศา
10 rows

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made