Combining Fields in Query

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
AliasBDI
Forum Contributor
Posts: 286
Joined: Fri Nov 15, 2002 10:35 am
Location: Spring, TX, USA

Combining Fields in Query

Post by AliasBDI »

Not sure how to do this... if someone can help me.

I have a query that looks for a record which has "firstname" and "lastname" fields. I want it to take those two fields and combine them under a new variable name called "fullname". How would this look?
User avatar
Kriek
Forum Contributor
Posts: 238
Joined: Wed May 29, 2002 3:46 am
Location: Florida
Contact:

Post by Kriek »

A SELECT expression may be given an alias using AS.

Code: Select all

SELECT firstname, lastname AS fullname FROM table ORDER BY fullname;
AliasBDI
Forum Contributor
Posts: 286
Joined: Fri Nov 15, 2002 10:35 am
Location: Spring, TX, USA

Well here it is...

Post by AliasBDI »

Kriek-

I tried that but it did not work. I think it reads the "firstname" as a field and then "lastname" as a field with a new variable name, which is "fullname".

Nevertheless, I was able to pull it off with the CONCAT.

Code: Select all

SELECT CONCAT("firstname", " ", "lastname") AS fullname FROM table
It displayed the firstname (John) and the lastname (Doe) as the fullname (John Doe).

Superb!
microthick
Forum Regular
Posts: 543
Joined: Wed Sep 24, 2003 2:15 pm
Location: Vancouver, BC

Post by microthick »

I think it's something like:

SELECT FirstName + ' ' + LastName as WholeName FROM ...
User avatar
Kriek
Forum Contributor
Posts: 238
Joined: Wed May 29, 2002 3:46 am
Location: Florida
Contact:

Post by Kriek »

Alias, I did not mention the CONCAT() function, because you did not specify whether or not you wanted to retain the previous fields as values. At any rate, it works now; glad I could be of assistance to you.
Post Reply