MySQL INSTR() String Function



MySQL INSTR() String Function

The MySQL INSTR() string function returns the position of the first occurrence of a substring within a string. This function is essential for finding the position of a substring in a string in SQL queries.


Syntax

SELECT INSTR(string, substring) AS result
FROM table_name;

The INSTR() function has the following components:

  • string: The string to be searched.
  • substring: The substring to search for within the string.
  • result: An alias for the resulting position.
  • table_name: The name of the table from which to retrieve the data.

Example MySQL INSTR() String Function

Let's look at some examples of the MySQL INSTR() string function:

Step 1: Using the Database

USE mydatabase;

This query sets the context to the database named mydatabase.

MySQL USE DATABASE

Step 2: Creating a Table

Create a table to work with:

CREATE TABLE sample_strings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    value VARCHAR(255) NOT NULL
);

This query creates a table named sample_strings with columns for id and value.

MySQL CREATE TABLE

Step 3: Inserting Initial Rows

Insert some initial rows into the table:

INSERT INTO sample_strings (value)
VALUES ('Hello world'),
       ('MySQL database'),
       ('String function'),
       ('Instr example'),
       ('Test case');

This query inserts five rows into the sample_strings table.

MySQL INSERT INTO TABLE

Step 4: Using INSTR() with WHERE Clause

Use the INSTR() function to find the position of a substring within a string:

SELECT value, INSTR(value, 'world') AS position
FROM sample_strings;

This query retrieves the value column from the sample_strings table and returns the position of the substring 'world' within the string.

MySQL INSTR() WITH WHERE CLAUSE

Step 5: Using INSTR() with Multiple Columns

Use the INSTR() function with multiple columns:

SELECT id, value, INSTR(value, 'function') AS position
FROM sample_strings;

This query retrieves the id and value columns from the sample_strings table and returns the position of the substring 'function' within the string.

MySQL INSTR() WITH MULTIPLE COLUMNS

Step 6: Using INSTR() with Constants

Use the INSTR() function with constants:

SELECT INSTR('Sample text', 'text') AS position;

This query finds the position of the substring 'text' within the constant string 'Sample text'.

MySQL INSTR() WITH CONSTANTS

Conclusion

The MySQL INSTR() function is a powerful tool for finding the position of a substring in a string in SQL queries. Understanding how to use the INSTR() function is essential for effective data querying and manipulation in MySQL.