SUBSTRING_INDEX()

Description

This function SUBSTRING_INDEX() returns the substring from string str before count occurrences of the delimiter delim.

If count is positive, everything to the left of the final delimiter (counting from the left) is returned.

If count is negative, everything to the right of the final delimiter (counting from the right) is returned. SUBSTRING_INDEX() performs a case-sensitive match when searching for delim.

SUBSTRING_INDEX() returns NULL if any of its arguments are NULL.

Syntax

  1. > SUBSTRING_INDEX(str,delim,count)

Arguments

ArgumentsDescription
strA string.
delimA delimiter.
countAn integer indicating the number of occurrences of delim.

Examples

  1. mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2);
  2. +--------------------------------------+
  3. | substring_index(www.mysql.com, ., 2) |
  4. +--------------------------------------+
  5. | www.mysql |
  6. +--------------------------------------+
  7. 1 row in set (0.03 sec)
  8. mysql> select substring_index('xyz', 'abc', 9223372036854775808);
  9. +------------------------------------------------+
  10. | substring_index(xyz, abc, 9223372036854775808) |
  11. +------------------------------------------------+
  12. | xyz |
  13. +------------------------------------------------+
  14. 1 row in set (0.02 sec)
  15. mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2);
  16. +---------------------------------------+
  17. | substring_index(www.mysql.com, ., -2) |
  18. +---------------------------------------+
  19. | mysql.com |
  20. +---------------------------------------+
  21. 1 row in set (0.02 sec)
  22. mysql> SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('192,168,8,203', ',', 2), ',',-1);
  23. +--------------------------------------------------------------+
  24. | substring_index(substring_index(192,168,8,203, ,, 2), ,, -1) |
  25. +--------------------------------------------------------------+
  26. | 168 |
  27. +--------------------------------------------------------------+
  28. 1 row in set (0.02 sec)
  29. create table test(a varchar(100), b varchar(20), c int);
  30. insert into test values('www.mysql.com', '.', 0);
  31. insert into test values('www.mysql.com', '.', 1);
  32. insert into test values('www.mysql.com', '.', 2);
  33. insert into test values('www.mysql.com', '.', 3);
  34. insert into test values('www.mysql.com', '.', 9223372036854775808);
  35. insert into test values('www.mysql.com', '.', -1);
  36. insert into test values('www.mysql.com', '.', -2);
  37. insert into test values('www.mysql.com', '.', -3);
  38. mysql> select SUBSTRING_INDEX(a, b, c) from test;
  39. +--------------------------+
  40. | substring_index(a, b, c) |
  41. +--------------------------+
  42. | |
  43. | www |
  44. | www.mysql |
  45. | www.mysql.com |
  46. | com |
  47. | mysql.com |
  48. | www.mysql.com |
  49. +--------------------------+
  50. 7 rows in set (0.02 sec)