mysql split str code example

Example: mysql split string

CREATE FUNCTION `SPLIT_STRING`(
	str VARCHAR(255) ,
	delim VARCHAR(12) ,
	pos INT
) RETURNS VARCHAR(255) CHARSET utf8 RETURN REPLACE(
	SUBSTRING(
		SUBSTRING_INDEX(str , delim , pos) ,
		CHAR_LENGTH(
			SUBSTRING_INDEX(str , delim , pos - 1)
		) + 1
	) ,
	delim ,
	''
);

SELECT
	-- keyword 1
	SPLIT_STRING(`keywords`,',',1) AS keyword_1,
	-- keyword 4, NOT trimmed
	SPLIT_STRING(`keywords`,',',4) AS keyword_4,
	-- keyword 4, trimmed
	trim(SPLIT_STRING(`keywords`,',',4)) AS keyword_4_trimmed
FROM `test`;

Tags:

Sql Example