Mateusz Kimont - Principal Full-Stack Engineer

Mateusz Kimont


Mysql 5.7 Notes


Set collation dynamically
SET @your_variable = 'your_value';
SET @collation_variable = 'utf8mb4_unicode_ci';
SET @sql = CONCAT('SELECT * FROM your_table WHERE your_column = ? COLLATE ', @collation_variable);
PREPARE stmt FROM @sql;
EXECUTE stmt USING @your_variable;
DEALLOCATE PREPARE stmt;
Set collation for string variable. Terrible hack but do you know better solution ?
SET @coll = (SELECT COLLATION(column_name) AS column_collation FROM table_name WHERE column_name = 'column_value' LIMIT 1);
SET @newFileLocation = 'dir/imageName.jpg';
# need to use string as variable doesnt work as expected
SET @newLocation = CONCAT('dir/imageName.jpg', @coll);
SET @newLocation =  SUBSTRING(@newLocation, 1, LENGTH(@newFileLocation));

Split delimited strings

Thanks to https://blog.fedecarg.com/2014/02/22/mysql-split-string-function/
CREATE FUNCTION SPLIT_STR(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
       LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
       delim, '');
Usage
SELECT SPLIT_STR(string, delimiter, position)