firstname from name in PostgreSQL

by Derek Sivers

Today's post is a one-liner that saves me a few lines of PHP every time I do a people query.

I used to always select my clients' or customers' names from the database, then use PHP/Ruby/something to grab just the first word of the name.

From now on I'm doing it in the database directly, though it took a while to figure out how.

SELECT name, INITCAP(SPLIT_PART(name, ' ', 1)) AS firstname FROM clients

(Ok so it only took like 3 minutes to figure out but I'm posting it here so I don't lose it.)



2004-12-28 19:14:26
Or, with regex...
SELECT name, INITCAP(SUBSTRING(name FROM '\\S+')) AS firstname FROM clients
2004-12-29 21:21:50
separate name fields from get go!
Columns like first_name, last_name seem like a better way to go plus when someone has a first name like 'mary ann' or 'anna maria' or maybe 'sir raleigh' they don't get bogus greetings like "welcome back sir. Or am a I missing something?