Search code examples
mysqlsqlmysql-error-1054

Can I use a column I have selected later in a query?


Imagine this query...

SELECT `id`,
       `hits` + `other_hits` AS `total_hits`
  FROM `something`
 WHERE `hits` + `other_hits` > 30

As you can see, I've repeated the addition of hits and other_hits. Can I refer to total_hits column I created in other parts of the query?

I tried it, and I got 1054: Unknown column in where clause.


Solution

  • Use:

    SELECT `id`,
           `hits` + `other_hits` AS `total_hits`
      FROM `something`
    HAVING `total_hits` > 30
    

    The earliest MySQL allows references to column aliases is the GROUP BY clause; clauses after that support references (HAVING, ORDER BY). Most other databases don't support referencing a table alias before the ORDER BY, which typically requires using a derived table/inline view:

    SELECT t.id, t.total_hits
      FROM (SELECT `id`,
                   `hits` + `other_hits` AS `total_hits`
              FROM `something`) t
     WHERE t.total_hits > 30
    

    Otherwise, you have to reuse the logic in the WHERE clause:

    SELECT `id`,
           `hits` + `other_hits` AS `total_hits`
      FROM `something`
     WHERE `hits` + `other_hits` > 30