MySQL WEIGHT_STRING() Function
The MySQL WEIGHT_STRING() function returns the weight for the input string.
It accepts a non-binary string as input and returns the weight string for it, this string contains the collation weights. If the input string is a binary value, the result is the same as the input string. This is because the weight for each byte in a binary string is the byte value.
Syntax
Following is the syntax of MySQL WEIGHT_STRING() function −
WEIGHT_STRING(str [AS {CHAR|BINARY}(N)] [flags])
Parameters
This function takes a non-binary string value as a parameter.
Return Value
This function returns the weight of the given string.
Example
The following example returns the weight string for the input string 'tutorialspoint' using the specified collation ('utf8mb4_0900_ai_ci') −
SELECT WEIGHT_STRING(_utf8mb4 'tutorialspoint' COLLATE utf8mb4_0900_ai_ci);
The result is a binary string that represents the comparison and sorting value of the input string as shown below −
| WEIGHT_STRING(_utf8mb4 'tutorialspoint' COLLATE utf8mb4_0900_ai_ci |
|---|
| 0x1E951EB51E951DDD1E331D321C471D771E711E0C1DDD1D321DB91E95 |
If you disable the --binary-as-hex value, the result of the above query will be as follows. To display the non-printable values, you can use the HEX() function −
SELECT HEX(WEIGHT_STRING(_utf8mb4 'tutorialspoint' COLLATE utf8mb4_0900_ai_ci));
The result obtained is as follows −
| HEX(WEIGHT_STRING(_utf8mb4 'tutorialspoint' COLLATE utf8mb4_0900_ai_ci)) |
|---|
| 1E951EB51E951DDD1E331D321C471D771E711E0C1DDD1D321DB91E95 |
Example
If you pass a binary string as an argument to this function it returns the same binary string −
SELECT WEIGHT_STRING(CAST('test' AS BINARY));
The output obtained is as follows −
| WEIGHT_STRING(CAST('test' AS BINARY)) |
|---|
| 0x74657374 |
If you disable the --binary-as-hex value, the result of the above query will be as follows. To display the non-printable values, you can use the HEX() function −
SELECT WEIGHT_STRING(CAST('test' AS BINARY));
The result produced is as shown below −
| WEIGHT_STRING(CAST('test' AS BINARY)) |
|---|
| test |
Example
You can also cast the string using CHAR or BINARY −
SET NAMES 'latin1';
SELECT HEX(WEIGHT_STRING('tutorialspoint' AS CHAR(4)));
The result produced is as follows −
| HEX(WEIGHT_STRING('tutorialspoint' AS CHAR(4))) |
|---|
| 5455544F |
Example
If you pass NULL as an argument to this function it returns the same NULL −
SELECT WEIGHT_STRING(NULL);
Following is the output of the above code −
| WEIGHT_STRING(NULL) |
|---|
| 0x |
If you disable the --binary-as-hex value, the result of the above query will be as follows. To display the non-printable values, you can use the HEX() function −
SELECT WEIGHT_STRING(NULL);
The result obtained is as shown below −
| WEIGHT_STRING(NULL) |
|---|
| NULL |