You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Using the CASE Expression in SQL Queries

Make the most of SQL in development projects

The DBMS (database management system) is often faster at performing calculations like summing up or averaging the values in a column of numbers than, for instance, the application server. However, there are many cases in which performing the same calculation on all of the data in a column will not provide the correct result.

This article will show you how to use the CASE expression in SQL queries to more flexibly perform aggregate calculations and set values based on a logical statement.

An example of the need to apply the CASE expression in an aggregate function is an online shopping cart with several item-specific options that, depending on the options chosen, change the way an item's price is added to the cart and, therefore, the final total price of the order. I will discuss a shopping cart for an online store that requires variable pricing within four option areas. The price calculation of the final order will vary depending on the setting of each option.

The example store sells items including artwork, books, gifts, events, and memberships. It's a dynamic store allowing administrators to add and delete categories, subcategories, and items. One item can exist in as many categories as the administrator would like. Individual items within a category may be subject to different pricing options. With these requirements, the programmer does not know what categories and subcategories will exist in the store in the future or under what category or pricing options an item will be placed. Therefore, options must be set at the item level and be available for administrators to set and change.

Requirements for the example store include the ability of administrators to choose options in these four areas:

  1. Sale price: Individual items may or may not be on sale. The database table contains a column for regular price and sale price and an additional flag column named SaleItem, allowing the administrator simply to change the SaleItem setting rather than change the value for regular price each time the item goes on sale.
  2. Shipping: Shipping cost is calculated based on the shopping cart total. However, administrators can select certain items such as memberships so that they do not carry a shipping charge.
  3. Member and employee discount: The organization has members and employees who are entitled to different discounts on purchases from the store. However, some items do not qualify for discounting under any circumstance.
  4. Sales taxes: Some items are taxed and some are not. For example, tax law does not require sales tax on memberships.

Overview of the SUM Function
Programmers often use the SUM() aggregate function to total the numbers contained in a database column. For instance, in a shopping cart, you might use the sum function as follows:

SELECT Name, SUM(Price) as Total
WHERE ItemID=#SomeValue#

The database will return rows of records, each containing the Name of the item and the sum total of the values found in the Price column for the records selected. Each row will contain the same value for Total. If no columns are selected, the query will return one row with the value of Total.

Based on the discussion above, simply totaling the prices in the Price column will not work for this shopping cart. For example, if the customer chooses an item that's on sale, the price in the SalePrice column must be used for that item. You might choose to solve this problem with CFML as follows:

<CFSET SumPrice=0>
<CFLOOP QUERY="GetCartItems">
<CFIF SaleItem is 1>
<CFSET SumPrice=SumPrice+(Quantity*SalePrice)>
<CFSET SumPrice=SumPrice+(Quantity*Price)>

This solution does not rely on SQL to total the item prices. Instead, the application loops through all of the items selected and adds them up in a CFLOOP loop. However, SQL does provide an elegant way to perform the same calculation using the SUM aggregate function in combination with the CASE expression. The total price of the items, taking into account those that are on sale, is included in the returned table using this method.

Overview of the CASE Expression
The CASE expression, introduced in SQL-92, provides the programmer with the ability to choose one of multiple values based on a logical expression. The value added to the item total of our shopping cart using the SUM() aggregate function is the value in the Price column for an item that is not on sale and the value in the SalePrice column for an item that is on sale. The CASE expression is supported by SQL Server, MySQL, PostgreSQL, and Oracle beginning with Oracle8i.

The SQL query to total the price of the items, taking into account those that are on sale, looks like:

SUM(CASE WHEN SaleItem=1 THEN SalePrice ELSE Price END)
as TotalPrice
WHERE Item.CartID=#SomeValue#

In the query above, the item is evaluated to see if SaleItem is 1. If it is, the SalePrice column is used for that item in calculating the total price. If not, the Price column is used.

Database Tables
The critical database tables for our cart include Item, Cart, CartItems, Tax, Discount, and Shipping.

The important columns in each table are:

  1. Item: ItemID (primary key), Price, SalePrice, SaleItem (1 or 0), Shipping (1 or 0), Discount (1 or 0), Tax (1 or 0)
  2. Cart: CartID (primary key)
  3. CartItems: CartItemID(primary key), CartID, ItemID, Quantity
  4. Tax: Pct, Gov
  5. Discount: DiscountID (primary key), Name, Pct
  6. Shipping: MinTotal, MaxTotal, ShipCost

The columns SaleItem, Shipping, Discount, and Tax, in the Item table, are switches used to turn each of the item pricing options on and off. For instance, if SaleItem is 1, then the product will be priced at the sale price. Of course, there are a number of other columns in the Item table that contain the content required to display the item.

The Cart table stores keys to identify carts and to find items in a cart. A Cart record is created when a customer adds his first item to a cart. The CartID is stored to allow for the retrieval of cart items after the cart session has expired.

The CartItems table allows for the joining of the cart with the items in the cart. It also stores the quantity of the item to be included in the cart.

The Tax table stores the abbreviated names and the percent sales tax for each government requiring the addition of tax.

The Discount table stores the names of member or employee discounts and their respective discount percentage.

The Shipping table stores min/max ranges of item totals and the corresponding shipping charge to be applied to the order based on the order total falling between or being equal to the min and/or max total.

Shopping Cart Calculation Example
Before summing the cart for the customer prior to final checkout using the SUM() aggregate function and CASE expression, information necessary for the calculation of the cart total is retrieved from the database as follows.

First, get the discount percentage based on the member type (individual, student, etc.) or employee status selected by the customer in the checkout form. Optionally, if a member and/or employee database exists, you can verify the member type or employee status from the employee or member records.

<CFQUERY NAME="GetDiscount" DATASOURCE="#Application.Datasource#">
SELECT Name, Pct
FROM Discount
WHERE DiscountID='#Form.DiscountID#'

Next, get the sales tax based on the state to which the order will be shipped. The customer has provided a "bill to" address and, optionally, a "ship to" address. Sales tax is based on the "ship to" state. If the "bill to" address is the same as the "ship to" address, the customer completes only the "bill to" address form. At this point, check to see if the form field Form.sState (the "ship to" state) is not available or is null. If either is true we use Form.State (the "bill to" state) to calculate sales taxes because the "ship to" address and the "bill to" address are the same. If both are false, use the "ship to" state.

<CFIF Not IsDefined('Form.sState') or Form.sState is "">
<CFSET ShippingState=Form.State>
<CFSET ShippingState=Form.sState>
<CFQUERY NAME="GetSalesTaxes" DATASOURCE="#Application.Datasource#">
WHERE Gov = '#ShippingState#'

Finally, check to see if sales tax applies. If there are no sales tax records for the state to which the order will be shipped, GetSalesTaxes.RecordCount will be 0 and sales tax will not be added.

<CFIF GetSalesTaxes.RecordCount gte 1 and GetSalesTaxes.Pct is not "">
<CFSET TaxRate=GetSalesTaxes.Pct>
<CFSET TaxRate=0>

Now it is known what discount to apply and what percentage of the total price of the taxable items will be added to the bill for sales tax. The real work using the CASE expression can begin.

Elsewhere in the application when the customer places his or her first item into the cart, Session.Cart is created and set to a unique value generated by the CreateUUID() function. Because records in the CartItems table contain the field CartID that is set to a value equal to Session.Cart as items are added to the cart by the shopper, using Session.Cart directly in the query GetCartItems detailed below works as long as Session.Cart exists.

However, Session.Cart is deleted after final checkout to end the cart session. In order to re-use the following code to process orders after the cart session is over and Session.Cart no longer exists, or to extend the life of the cart beyond the existence of Session.Cart if desired, create CartSumCartID and use it in the GetCartItems query in place of Session.Cart. This allows the value of CartSumCartID to be set using a database record instead of Session.Cart (e.g., the value in the CartID field in the Cart table described in the Database Tables section above). For now, just set CartSumCartID to Session.Cart because in this example the query GetCartItems is being used prior to final checkout.

<CFSET CartSumCartID=Session.Cart>

The query at the heart of the shopping cart is as follows:

<!---begin query to retrieve the cart items and the shopping cart totals needed to generate the cart final total--->

<CFQUERY NAME="GetCartItems" DATASOURCE="#Application.Datasource#">
SELECT CartItems.CartItemID, CartItems.Quantity, Item.*,

  • The following subquery calculates the value for TotalPrice.
  • Join Item and CartItems to find items contained in the cart.
  • If it is a sale item use the sale price, if not use the price.

WHEN SaleItem=1
THEN Quantity*SalePrice
ELSE Quantity*Price
END) FROM (Item INNER JOIN CartItems ON Item.ItemID = CartItems.ItemID)
WHERE CartItems.CartID='#CartSumCartID#') as TotalPrice,

  • To calculate the total after discounting. (TotalDiscountPrice) use the following nested CASE expressions in the subquery below.
  • If it is a sale item use the sale price, if not use the price.
  • If discounting is allowed for this item multiply total item price (quantity*price) by 1-Discount; otherwise, use the total item price without discount.

WHEN SaleItem=1
THEN CASE WHEN Discount=1 THEN Quantity*SalePrice*(1-#Discount#) ELSE Quantity*SalePrice
ELSE CASE WHEN Discount=1 THEN Quantity*Price*(1-#Discount#) ELSE Quantity*Price END
END) FROM (Item INNER JOIN CartItems ON Item.ItemID = CartItems.ItemID)
WHERE CartItems.CartID='#CartSumCartID#') as TotalDiscountPrice,

  • Next calculate SalesTax.
  • TaxRate was set above.
  • Apply sale prices and discounts before calculating sales tax.
  • If the item is nontaxable, 0 is added to SalesTax.

WHEN Tax=1
THEN CASE WHEN Discount=1 THEN Quantity*SalePrice*(1-#Discount#)*#TaxRate#*1/100 ELSE
Quantity*SalePrice*#TaxRate#*1/100 END
ELSE CASE WHEN Discount=1 THEN Quantity*Price*(1-#Discount#)*#TaxRate#*1/100 ELSE
Quantity*Price*#TaxRate#*1/100 END
END) FROM (Item INNER JOIN CartItems ON Item.ItemID = CartItems.ItemID) WHERE
CartItems.CartID='#CartSumCartID#') as SalesTax,

  • Now see if the total item price is to be used in the calculation of shipping charges by again using nested CASE expressions.
  • If the item is not to be used in the shipping calculation, it is added as 0.

WHEN Shipping=1
THEN CASE WHEN Discount=1 THEN Quantity*SalePrice*(1-#Discount#) ELSE Quantity*SalePrice
ELSE CASE WHEN Discount=1 THEN Quantity*Price*(1-#Discount#) ELSE Quantity*Price END
END) FROM (Item INNER JOIN CartItems ON Item.ItemID = CartItems.ItemID) WHERE
CartItems.CartID='#CartSumCartID#') as TotalShippingPrice

  • Finish the query.

FROM (Item INNER JOIN CartItems ON Item.ItemID = CartItems.ItemID)
WHERE CartItems.CartID='#CartSumCartID#'

The table returned contains rows of items in the customer's cart with the information about each item and the quantity ordered. In addition, each row of the table includes the item total prior to discount (TotalPrice), the item total after discount (TotalDiscountedPrice), the sales tax to be added to the order (SalesTax), and the item total for items that are to be used in the calculation of shipping charges (TotalShippingPrice).

There is one last task to complete prior to displaying the cart summary to the customer - determining shipping cost. Shipping cost is determined by the value of GetCartItems.TotalShippingPrice. ShipCost is returned by the following query where the value of GetCartItems.TotalShippingPrice falls between or is equal to MinTotal and/or MaxTotal in the Shipping table.

<CFQUERY NAME="GetShippingFee" DATASOURCE="#Application.Datasource#">
FROM Shipping
WHERE #GetCartItems.TotalShippingPrice# >= MinTotal
and #GetCartItems.TotalShippingPrice# <= MaxTotal

Later the shipping cost and sales tax will be added to the total and passed along to the display template.

The CASE expression allows the programmer to create queries that use logical expressions to determine what value to use and/or what calculation to perform. Used in a subquery, the CASE expression allows for the generation of multiple values from the same data set. The CASE expression is, in many instances, a viable alternative to post query loops and calculations. Application of the CASE expression can help you make the most of SQL in development projects.

More Stories By Hudson Benson

Hudson Benson is the owner of The Cattail Company, a Web and media development company located in northeastern Maryland. His experience includes the development and marketing of Web applications for businesses, universities, and nonprofit organizations. Hudson also serves as North American director of marketing and business development for a global firm headquartered in Sweden.

Comments (1)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

IoT & Smart Cities Stories
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...