Chris Nizzardini, Salt Lake City Utah, Web Developer Specializing in LAMP+Ajax Since 2006

My Blog

Here is my awesome blog.

MySQL Case Statement

The database I was working on the other day is FAR from normalized. It stores shipping types as regular VARCHAR strings. We needed to orderby Overnight and International orders so they print first in the batch. Using a case statement I was able to create a temporary sane column in this query, using the integer values in this temporary shipType column I was then easily able to orderby and it only added 1/10 of a second to the query’s execution time. Here is an example of the MySQL case statement:

				CASE SUBSTRING_INDEX( shipping, '|', 1 )
				     WHEN 'Overnight' THEN 1
				     WHEN 'Overnight Delivery' THEN 2
				     WHEN 'International' THEN 3
				     WHEN 'USPS International Shipping' THEN 4
				     WHEN '' THEN 5
				     WHEN ' * Product(s) qualify for Free shipping * ' THEN 6
				     ELSE SUBSTRING_INDEX( shipping, '|', 1 )
				    END AS shipType 

Leave a Reply