PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 14, 2022

[FIXED] How to split name column into firstName and lastName columns in PostgreSQL?

 April 14, 2022     migration, postgresql, sql     No comments   

Issue

Assume this User table in PostgreSQL:

CREATE TABLE "User" (
    id SERIAL PRIMARY KEY,
    email text NOT NULL,
    name text,
);

I want to split name into firstName and lastName and update the existing rows accordingly. I understand that I can use the following SQL to return the data as firstName and lastName:

SELECT 
  split_part("name", ' ', 1) AS "firstName", 
  split_part("name", ' ', 2)  AS "lastName"
FROM "User";

I guess I now need to use UPDATE somehow in order to update the existing rows, but I'm not clear on the exact syntax.


Solution

One straightforward way to do this would be:

UPDATE "User"
    SET "firstName" =  split_part("name", ' ', 1),
        "lastName" = split_part("name", ' ', 2)

(No WHERE clause because I'm assuming you want to transform the whole table that way.)



Answered By - Tom Houlé
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing