Welcome!

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
FROM Item
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)>
<CFELSE>
<CFSET SumPrice=SumPrice+(Quantity*Price)>
</CFIF>
</CFLOOP>

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:

SELECT
SUM(CASE WHEN SaleItem=1 THEN SalePrice ELSE Price END)
FROM Item
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#'
</CFQUERY>

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>
<CFELSE>
<CFSET ShippingState=Form.sState>
</CFIF>
<CFQUERY NAME="GetSalesTaxes" DATASOURCE="#Application.Datasource#">
SELECT Pct
FROM Tax
WHERE Gov = '#ShippingState#'
</CFQUERY>

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>
<CFELSE>
<CFSET TaxRate=0>
</CFIF>

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.

(SELECT
SUM(CASE
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.

(SELECT
SUM(CASE
WHEN SaleItem=1
THEN CASE WHEN Discount=1 THEN Quantity*SalePrice*(1-#Discount#) ELSE Quantity*SalePrice
END
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.

(SELECT
SUM(CASE
WHEN Tax=1
THEN CASE WHEN SaleItem=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
ELSE 0
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.

(SELECT
SUM(CASE
WHEN Shipping=1
THEN CASE WHEN SaleItem=1
THEN CASE WHEN Discount=1 THEN Quantity*SalePrice*(1-#Discount#) ELSE Quantity*SalePrice
END
ELSE CASE WHEN Discount=1 THEN Quantity*Price*(1-#Discount#) ELSE Quantity*Price END
END
ELSE 0
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#'
ORDER BY Name
</CFQUERY>

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#">
SELECT ShipCost
FROM Shipping
WHERE #GetCartItems.TotalShippingPrice# >= MinTotal
and #GetCartItems.TotalShippingPrice# <= MaxTotal
</CFQUERY>

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

Conclusion
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) View Comments

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.


Most Recent Comments
yousokkong 12/18/03 09:35:56 PM EST

Hi how are you

@ThingsExpo Stories
Imagine if you will, a retail floor so densely packed with sensors that they can pick up the movements of insects scurrying across a store aisle. Or a component of a piece of factory equipment so well-instrumented that its digital twin provides resolution down to the micrometer.
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. 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 settle...
BnkToTheFuture.com is the largest online investment platform for investing in FinTech, Bitcoin and Blockchain companies. We believe the future of finance looks very different from the past and we aim to invest and provide trading opportunities for qualifying investors that want to build a portfolio in the sector in compliance with international financial regulations.
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
Product connectivity goes hand and hand these days with increased use of personal data. New IoT devices are becoming more personalized than ever before. In his session at 22nd Cloud Expo | DXWorld Expo, Nicolas Fierro, CEO of MIMIR Blockchain Solutions, will discuss how in order to protect your data and privacy, IoT applications need to embrace Blockchain technology for a new level of product security never before seen - or needed.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
We are given a desktop platform with Java 8 or Java 9 installed and seek to find a way to deploy high-performance Java applications that use Java 3D and/or Jogl without having to run an installer. We are subject to the constraint that the applications be signed and deployed so that they can be run in a trusted environment (i.e., outside of the sandbox). Further, we seek to do this in a way that does not depend on bundling a JRE with our applications, as this makes downloads and installations rat...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
DX World EXPO, LLC, a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
Digital Transformation (DX) is not a "one-size-fits all" strategy. Each organization needs to develop its own unique, long-term DX plan. It must do so by realizing that we now live in a data-driven age, and that technologies such as Cloud Computing, Big Data, the IoT, Cognitive Computing, and Blockchain are only tools. In her general session at 21st Cloud Expo, Rebecca Wanta explained how the strategy must focus on DX and include a commitment from top management to create great IT jobs, monitor ...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
The IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...