// you’re reading...

Apache / PHP / MySQL

A case for CASE in your SQL

I’m going to add more to this later, but for now…

SQL CASE scenario #1

Ever wanted to offer quantity discounts for shoppers? Here’s an example of a trivial implementation of the CASE condition in MySQL to get the job done.

mysql> SET @cart_quantity := 3;
Query OK, 0 rows affected (0.00 sec)

mysql> select @cart_quantity;
+----------------+
| @cart_quantity |
+----------------+
|              3 |
+----------------+
1 row in set (0.00 sec)

mysql> SET @cart_subtotal := 100.00;
Query OK, 0 rows affected (0.02 sec)

mysql> select @cart_subtotal;
+----------------+
| @cart_subtotal |
+----------------+
|         100.00 |
+----------------+
1 row in set (0.00 sec)

mysql> select @cart_total := CASE WHEN @cart_quantity > 1 THEN (@cart_subtotal * .9) END;
+----------------------------------------------------------------------------+
| @cart_total := CASE WHEN @cart_quantity > 1 THEN (@cart_subtotal * .9) END |
+----------------------------------------------------------------------------+
|                                                                     90.000 |
+----------------------------------------------------------------------------+
1 row in set (0.03 sec)

mysql> select @cart_total;
+-------------+
| @cart_total |
+-------------+
|      90.000 |
+-------------+
1 row in set (0.00 sec)

mysql>

Discussion

Comments are disallowed for this post.

Comments are closed.

 

December 2009
S M T W T F S
« Sep   Jan »
 12345
6789101112
13141516171819
20212223242526
2728293031