117

I'm trying to compile this in my mind.. i have a table with firstname and lastname fields and i have a string like "Bob Jones" or "Bob Michael Jones" and several others.

the thing is, i have for example Bob in firstname, and Michael Jones in lastname

so i'm trying to

SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
  FROM users 
 WHERE firstlast = "Bob Michael Jones"

but it says unknown column "firstlast".. can anyone help please ?

Chandu
  • 81,493
  • 19
  • 133
  • 134
Alex K
  • 6,737
  • 9
  • 41
  • 63

6 Answers6

183

The aliases you give are for the output of the query - they are not available within the query itself.

You can either repeat the expression:

SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
FROM users
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"

or wrap the query

SELECT * FROM (
  SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
  FROM users) base 
WHERE firstLast = "Bob Michael Jones"
mdma
  • 56,943
  • 12
  • 94
  • 128
34

Try this:

SELECT * 
  FROM  (
        SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
        FROM users 
    ) a
WHERE firstlast = "Bob Michael Jones"
Chandu
  • 81,493
  • 19
  • 133
  • 134
10
SELECT needefield, CONCAT(firstname, ' ',lastname) as firstlast 
FROM users 
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"
Jeff Swensen
  • 3,513
  • 28
  • 52
8

Use CONCAT_WS().

SELECT CONCAT_WS(' ',firstname,lastname) as firstlast FROM users 
WHERE firstlast = "Bob Michael Jones";

The first argument is the separator for the rest of the arguments.

Viraj Dhamal
  • 5,165
  • 10
  • 32
  • 41
7

There is an alternative to repeating the CONCAT expression or using subqueries. You can make use of the HAVING clause, which recognizes column aliases.

SELECT 
  neededfield, CONCAT(firstname, ' ', lastname) AS firstlast 
FROM
  users 
HAVING firstlast = "Bob Michael Jones"

Here is a working SQL Fiddle.

Bogdan
  • 43,166
  • 12
  • 128
  • 129
  • Not sure why the having clause is not garnering more attention. It allows the direct use of the virtual column name. Does the having clause have more overhead? – Paul Mar 18 '14 at 17:11
  • @Paul having clause applied in the end of executing query so we can use it to set condition on aggregate functions(like MAX()). Having clause cannot use index so it is slow. – Mostafa Vatanpour Jul 05 '16 at 04:15
7

Try:

SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
  FROM users 
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"

Your alias firstlast is not available in the where clause of the query unless you do the query as a sub-select.

RC.
  • 27,409
  • 9
  • 73
  • 93