MariaDB SUBSTRING and SUBSTRING_INDEX: extract text by position or delimiter

In MariaDB, use SUBSTRING() to extract characters by position and length. Use SUBSTRING_INDEX() to return a prefix or suffix by counting a delimiter from the left or right. Both functions can return results in a SELECT.

Extract text by position and length with SUBSTRING

SELECT SUBSTRING('12345678', 5) AS to_end,
       SUBSTRING('12345678', 5, 2) AS two_chars,
       SUBSTRING('12345678' FROM 5 FOR 2) AS standard_form,
       SUBSTR('12345678', 5, 2) AS alias_form,
       SUBSTRING(_utf8mb4'가나다라', 2, 2) AS korean;

Run the first query without a table. Omitting the length gives 5678 in to_end. The three expressions with length 2 all return 56. FROM and FOR use standard SQL syntax, and SUBSTR() is an alias. The Korean example takes two characters from position 2 and returns 나다. For utf8mb4 the positions count characters. A displayed grapheme, such as a combined emoji, can contain several encoded characters. MariaDB Docs · MariaDB SUBSTRING() MariaDB Docs · MariaDB CHAR_LENGTH()

Check negative positions and out-of-range results

SELECT SUBSTRING('abcdef', -3) AS last_three,
       SUBSTRING('abcdef', -4, 2) AS from_back,
       SUBSTRING('abcdef', 4, 99) AS available_only,
       CONCAT('[', SUBSTRING('abc', 0), ']') AS zero_pos,
       CONCAT('[', SUBSTRING('abc', 9), ']') AS outside_pos,
       CONCAT('[', SUBSTRING('abc', 1, 0), ']') AS zero_length,
       SUBSTRING(NULL, 1, 2) AS null_input;

A negative position counts backward to find the start, then reads to the right. The first three results are def, cd, and def. The third returns the available suffix even though the requested length is 99. In ordinary mode, position zero, a start outside the string, and length zero all return empty strings in this example. The brackets make an empty result visible as [].

Any NULL argument gives NULL. Oracle compatibility mode treats position 0 as 1. If the output differs, use SELECT @@session.sql_mode to check the settings of the current connection. MariaDB Docs · MariaDB SQL_MODE

Count delimiters from either side with SUBSTRING_INDEX

In SUBSTRING_INDEX(string, delimiter, count), a positive count returns the text before the specified delimiter from the left. A negative count returns the text after the specified delimiter from the right. The dot examples return 12.34.56 and 56.78. The two-character delimiter :: gives alpha and gamma. This demonstrates string extraction; IP address validation is a separate task. MariaDB Docs · MariaDB SUBSTRING_INDEX()

SELECT SUBSTRING_INDEX('12.34.56.78', '.', 3) AS first_three,
       SUBSTRING_INDEX('12.34.56.78', '.', -2) AS last_two,
       SUBSTRING_INDEX('alpha::beta::gamma', '::', 1) AS before_first,
       SUBSTRING_INDEX('alpha::beta::gamma', '::', -1) AS after_last;
SELECT SUBSTRING_INDEX('a|b|c', '|', 9) AS too_many,
       SUBSTRING_INDEX('abc', '|', 1) AS no_delimiter,
       CONCAT('[', SUBSTRING_INDEX('a|b', '|', 0), ']') AS zero_count,
       SUBSTRING_INDEX('aXb', 'x', 1) AS case_sensitive,
       SUBSTRING_INDEX('a|b', NULL, 1) AS null_delimiter;

If there are too few delimiters, the whole original string comes back. too_many returns a|b|c and no_delimiter returns abc. A count of zero gives an empty string, shown as [] in zero_count. Delimiter matching is case sensitive, so looking for x in aXb leaves aXb intact. A NULL delimiter gives NULL.

Check for a third field before extracting it

To extract the third field, keep the first three fields, then take the last of those. A nested expression on a|b can return b even though there is no third field. Check for at least two occurrences of the single-character delimiter | first. Use the learning practice database with CREATE, INSERT, and SELECT permissions. Choose a new database if that example table already exists.

USE learning;
CREATE TABLE extract_parts_demo (
    id INT PRIMARY KEY,
    parts VARCHAR(100) NULL
) DEFAULT CHARSET=utf8mb4;
INSERT INTO extract_parts_demo VALUES
    (1, 'a|b|c|d'), (2, 'a|b'), (3, 'a||'), (4, NULL), (5, 'a|b|c');

WITH inspected AS (
    SELECT id, parts,
           CHAR_LENGTH(parts) - CHAR_LENGTH(REPLACE(parts, '|', '')) AS pipe_count,
           SUBSTRING_INDEX(SUBSTRING_INDEX(parts, '|', 3), '|', -1) AS unchecked_third
    FROM extract_parts_demo
)
SELECT id, pipe_count, unchecked_third,
       CASE WHEN pipe_count >= 2 THEN unchecked_third ELSE NULL END AS third_part
FROM inspected
ORDER BY id;

The checked third_part is c for IDs 1 and 5, NULL for IDs 2 and 4, and empty for ID 3. The third field in a|| exists but is empty. In a|b, it is missing. The length-difference rule in the example counts a one-character delimiter. For a fixed multi-character delimiter, account for the number of characters removed per occurrence.

Check the data format and plan for indexed expressions

This approach is for simple delimiter-separated text with no quoting or escapes. Use a format-aware parser for CSV or JSON. From MariaDB 11.8, the optimizer can use an index for some comparisons such as SUBSTR(indexed_column, 1, n) = a constant. Inspect the actual query with EXPLAIN. MariaDB Docs · MariaDB EXPLAIN