Handling MySQL JSON field default values

462 Views Asked by At

I need to come up with an SQL that can ALTER a JSON field.

  1. A JSON field was configured with default value of {}
  2. But I'm getting _utf8mb4'{}' back when querying the DDL
  3. I was expecting the default value to be {}.
  4. Any idea where is _utf8mb4 documented and how do I handle it correctly?

UPDATE:

  1. Version is 8.0.33-0ubuntu0.22.04.2
ALTER TABLE demo MODIFY COLUMN settings JSON NOT NULL DEFAULT ('{}');
SHOW CREATE TABLE demo;
CREATE TABLE `demo` (
  ...
  `settings` json NOT NULL DEFAULT (_utf8mb4'{}'),
  ...  
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
1

There are 1 best solutions below

0
Bill Karwin On

https://dev.mysql.com/doc/refman/8.0/en/json.html says:

MySQL handles strings used in JSON context using the utf8mb4 character set and utf8mb4_bin collation. Strings in other character sets are converted to utf8mb4 as necessary.

The syntax you see, _utf8mb4'{}' is just a string literal with a character set introducer.

https://dev.mysql.com/doc/refman/8.0/en/string-literals.html says:

A character string literal may have an optional character set introducer and COLLATE clause, to designate it as a string that uses a particular character set and collation:

[_charset_name]'string' [COLLATE collation_name]

Since JSON must use utf8mb4, I am guessing it is adding the introducer to the default expression to ensure that the string is encoded with the proper character set, just in case someone tries to insert into the table from a session configured with a different session character set.

The same thing happens if you add other text columns:

mysql> alter table demo add column t text default ('abc');

mysql> show create table demo\G
*************************** 1. row ***************************
       Table: demo
Create Table: CREATE TABLE `demo` (
  `settings` json NOT NULL DEFAULT (_utf8mb4'{}'),
  `t` text DEFAULT (_utf8mb4'abc')
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci