Johnny Metz
Johnny Metz

Reputation: 5955

Extract the first word before a space using SQL

Let's say I have a column in my users table called name:

name
----
Brian
Jill Johnson
Sarah
Steven Smith

I want to write a PostgreSQL query to fetch just the first name. This is what I have so far:

select substr(name, 0, position(' ' IN name) | length(name) + 1) as first_name from users;
name
----
Brian
Jill
Sarah
Steven

This appears to work but I feel like there much be an easier way.

Upvotes: 1

Views: 919

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269503

Although I don't follow the logic, your code looks like Postgres. If so, use split_part():

select split_part(name, ' ', 1)
from users;

Upvotes: 1

Related Questions