Skip to content

Instantly share code, notes, and snippets.

@mrclay
Created April 3, 2012 14:02
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save mrclay/2292253 to your computer and use it in GitHub Desktop.
Save mrclay/2292253 to your computer and use it in GitHub Desktop.
MySQL: Extract last and first name(s) from a full "name" field (for Elgg)
SELECT
-- Assumed to be trimmed
name
-- Does name contain multiple words?
,(LOCATE(' ', name) = 0) AS hasMultipleWords
-- Returns the end of the string back until reaches a space.
-- E.g. "John Doe" => "Doe"
-- E.g. "Francis Scott Key" => "Key"
-- E.g. "Prince" => "Prince"
,REVERSE(SUBSTRING_INDEX(REVERSE(name), ' ', 1)) AS lastName
-- Everything not included in the last name.
-- E.g. "John Doe" => "John"
-- E.g. "Francis Scott Key" => "Francis Scott"
-- E.g. "Prince" => ""
,TRIM(SUBSTRING(name, 1, CHAR_LENGTH(name) - CHAR_LENGTH(SUBSTRING_INDEX(REVERSE(name), ' ', 1)))) AS firstNames
FROM `elgg_users_entity`
LIMIT 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment