ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

SQL MariaDB: Find First Occurrence of Character

SQL MariaDB

Goal -- WPM

Ready
Exercise Algorithm Area
1SELECT INSTR(column_name, 'char_to_find') AS first_occurrence_index FROM table_name WHERE INSTR(column_name, 'char_to_find') > 0;
2
3-- This query uses the built-in INSTR function.
4-- INSTR(string, substring) returns the starting position of the first occurrence of substring within string.
5-- It returns 0 if the substring is not found.
6
7-- Edge case: Character not found
8-- If 'char_to_find' is not present in 'column_name', INSTR returns 0.
9-- The WHERE clause filters out these rows, returning an empty result set.
10
11-- Edge case: Empty string
12-- If 'column_name' is an empty string (''), INSTR will return 0.
13-- This is handled by the WHERE clause.
14
15-- Edge case: NULL string
16-- If 'column_name' is NULL, INSTR typically returns NULL.
17-- The WHERE clause (INSTR(...) > 0) will evaluate to FALSE, correctly excluding NULL strings.
18
19-- Note: MariaDB's INSTR function is equivalent to LOCATE. The index is 1-based.
Algorithm description viewbox

SQL MariaDB: Find First Occurrence of Character

Algorithm description:

This SQL query efficiently finds the 1-based index of the first occurrence of a specified character within a string column in a MariaDB table. It leverages the built-in `INSTR` function, which is optimized for string searching. This is commonly used for data validation, parsing text fields, or extracting specific parts of string data based on character positions.

Algorithm explanation:

The query utilizes the `INSTR(string, substring)` function, which is a standard SQL function available in MariaDB. `INSTR` returns the starting position (1-based index) of the first occurrence of `substring` within `string`. If `substring` is not found, it returns 0. The `WHERE INSTR(column_name, 'char_to_find') > 0` clause ensures that only rows where the character is actually found are returned. The time complexity for `INSTR` is typically O(M*N) in the worst case, where M is the length of the string and N is the length of the substring, but it's highly optimized in database engines. Space complexity is O(1). Edge cases like the character not being present, an empty string, or a NULL string are handled by the `INSTR` function's return values and the `WHERE` clause.

Pseudocode:

FUNCTION findFirstCharIndex(string_column, char_to_find):
  index = INSTR(string_column, char_to_find)
  IF index > 0 THEN
    RETURN index
  ELSE
    RETURN NULL (or indicate not found)
  END IF
END FUNCTION