Skip to content

Instantly share code, notes, and snippets.

@Querela
Forked from paulochf/strsplit.sql
Created August 12, 2020 20:15

Revisions

  1. @paulochf paulochf created this gist Feb 10, 2015.
    35 changes: 35 additions & 0 deletions strsplit.sql
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    -- Retrieved from http://dev.mysql.com/doc/refman/5.6/en/string-functions.html at 2015-feb-10 18:16
    -- Working on MySQL version 5.6.19-0ubuntu0.14.04.1 (Ubuntu)
    --
    -- Posted by Chris Stubben on August 21 2008 3:49pm
    -- Split delimited strings

    CREATE FUNCTION
    strSplit(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 strSplit("aaa,b,cc,d", ',', n) AS nth;
    SELECT strSplit("aaa,b,cc,d", ',', 2) AS second;
    +--------+
    | second |
    +--------+
    | b |
    +--------+

    SELECT strSplit("a|bb|ccc|dd", '|', 3) AS third;
    +-------+
    | third |
    +-------+
    | ccc |
    +-------+

    SELECT strSplit("aaa,b,cc,d", ',', 7) AS 7th;
    +------+
    | 7th |
    +------+
    | NULL |
    +------+