Home >Database >Mysql Tutorial >How to Extract First, Middle, and Last Names from a String in MySQL?

How to Extract First, Middle, and Last Names from a String in MySQL?

Susan Sarandon
Susan SarandonOriginal
2025-01-19 15:42:08990browse

How to Extract First, Middle, and Last Names from a String in MySQL?

Extract first name, middle name and last name from string field in MySQL

Splitting a name string into first, middle, and last name is a common task in data processing. MySQL provides a variety of functions for this purpose.

Method 1: Separate first name, middle name and last name

This method utilizes the SUBSTRING_INDEX and LENGTH functions to extract each part of the name:

<code class="language-sql">SELECT
   SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 1), ' ', -1) AS first_name,
   IF(LENGTH(fullname) - LENGTH(REPLACE(fullname, ' ', '')) > 1,
       SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 2), ' ', -1), NULL)
       AS middle_name,
   SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 3), ' ', -1) AS last_name
FROM registeredusers;</code>

Description:

  • SUBSTRING_INDEX(fullname, ' ', 1) Extracts the part of the string up to the first space.
  • SUBSTRING_INDEX(..., ' ', -1) Retrieve the last element from this string, providing the name.
  • IF Checks if the string contains multiple spaces (indicating the presence of a middle name).
  • SUBSTRING_INDEX(..., ' ', 2) Then isolate the part containing the middle name and last name.
  • SUBSTRING_INDEX(..., ' ', -1) Extracts the last part of the string, providing the last name.

Method 2: Separate first name and last name

If the middle name is considered part of the last name, you can use this method:

<code class="language-sql">SELECT
   SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 1), ' ', -1) AS first_name,
    TRIM(SUBSTR(fullname, LOCATE(' ', fullname))) AS last_name
FROM registeredusers;</code>

Description:

  • SUBSTRING_INDEX(fullname, ' ', 1) Extracts the part of the string up to the first space, providing the name.
  • LOCATE(' ', fullname) Find the position of the first space.
  • SUBSTR(fullname, ...), starting at LOCATE, retrieves the rest of the string, including the middle and last name.
  • TRIM Remove any leading or trailing spaces.

The above is the detailed content of How to Extract First, Middle, and Last Names from a String in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn