Hot Koehls
  • Email
  • Feedburner
  • Linkedin
  • Twitter
  • Home
  • About
  • Archives
  • Contact
  • Software
    • S3imple Backup
    • Twitter Feed Archiver
    • FileTime
    • Flickr API Demo
Search
Home» For techies » Using SQL computations in WHERE clause

Using SQL computations in WHERE clause

Posted by Frank - August 8, 2008 - For techies
2

When writing SQL statements, sometimes I want to filter the result set based on a value that must be computed out of the stored data. Here’s an example:

SELECT widgetID, count( widgetID ) AS totalWidgets
FROM table_widget_sales
WHERE totalWidgets > 1
GROUP BY widgetID
ORDER BY totalWidgets DESC

I want to see which widgets have been sold more than once, and how many times each of those remaining widgets have sold. Obviously we could pass a simpler query into a scripting language to calculate it for us, but that’s more cycles and memory. I love to squeeze as much out of my SQL statements as possible.

Problem is, when I run that query above, I get this error:

#1054 - Unknown column 'totalWidgets' in 'where clause'

My first reaction is, “I can use that column in the order by clause, why not where clauses!?” Simple, the value doesn’t exist when the WHERE clause is evaluated. The number is calculated as each matching record is passed. By the time we reach the ORDER BY clause, we have the data we need. But the WHERE clause is used to actually figure out what records we need to perform that calculation, so we’ve got a chicken-egg issue.

The solution is to use a subquery, sometimes called a “sub-select statement.” Using two select statements, we can split the duties for filtering (more than 1 widget sale) and counting (total number of sales per widget).

Here’s the working query:

SELECT w.widgetID, COUNT( ws.widgetID ) AS totalWidgets
FROM table_widgets AS w
INNER JOIN table_widget_sales AS ws ON ( w.widgetID = ws.widgetID )
WHERE (
SELECT COUNT( ws.widgetID ) AS number
FROM table_widget_sales AS ws
WHERE ws.widgetID = w.widgetID
) > 1
GROUP BY widgetID
ORDER BY totalWidgets DESC

See what’s going on? We’re doing the same count twice, but the subquery returns everything (number of sales per widget for all widgets), while the first select only grabs the results we want (sales greater than 1).

mysql, programming

2 comments on “Using SQL computations in WHERE clause”

  1. DrByte says:
    August 9, 2008 at 4:34 pm

    Another way to tackle the same thing would be to use a HAVING clause instead of a WHERE clause, to give the same results:

    SELECT widgetID, count( widgetID ) AS totalWidgets
    FROM table_widget_sales
    GROUP BY widgetID
    HAVING totalWidgets > 1
    ORDER BY totalWidgets DESC

  2. Frank says:
    August 22, 2008 at 10:17 am

    Also a good solution, Chris. Thanks! See, that’s why you gotta hang out with these Zen Cart guys.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Categories

  • For entrepreneurs
  • For everyone
  • For techies

Latest Tweets

  • The word traps planners plan themselves into | Life. Then strategy http://t.co/iANAdASb
    May 8, 2012 - 2:43 pm
  • Random network security tip for those about to appear on TV - Boing Boing http://t.co/tC1lXFQ4
    May 8, 2012 - 1:42 pm
  • A Picture http://t.co/H846Uy69
    April 27, 2012 - 12:25 pm
  • The Broken "Buy-One, Give-One" Model: 3 Ways to Save Toms Shoes | Co.Exist: World changing ideas and innovation http://t.co/RI0sVMW6
    April 10, 2012 - 12:23 pm

Recent Comments

  • whiz on What 255 characters looks like
  • Andrew on Find the second (or third, or fourth) occurence in a string
  • IanArcher on Get number of message parts in an email using PHP
  • Usama on Remove parent directories from tar archives
  • Frank on It’s dangerous to go alone

Recent Posts

  • It’s dangerous to go alone
  • Create Self-Signed Wildcard SSL Certificate
  • What comes after the yottabyte?
  • Write code like they do in Hollywood
  • Brian Rolle machine gun celebration
(c) 2012 Frank Koehl. All Rights Reserved.
  • Contact Us
  • Sitemap