Search
Tweets
Recent Changes
« Three Months and Thirteen Days | Main | Bring It On Back »
Friday
Jan202006

Clever SQL Of The Day

I've been working on Greenspan's coupon system for the past few days. This work is being done a bit early because quantity discounts, a feature we need soon, are being handled much like coupons.


Coupons can be general, i.e. $5 off anything, or specific to certain products. When a user enters a coupon code, I acquire it with SQL like this:



SELECT * FROM coupons
WHERE active=1
AND code=?
AND (date_start < NOW() OR date_start IS NULL)
AND (date_start > NOW() OR date_end IS NULL)

This ensures that we are getting a valid coupon. Now for the clever part. We must determine if this coupon is applicable to our cart. The wrenches in our plans are the aforementioned title-specific guys. We need to quickly determine if either: (a) the coupon is global or (b) the cart contains a product that is attached to the coupon. SQL to the rescue:



SELECT 1 FROM coupon_products
WHERE
(coupon_id=? AND product_id IN
(SELECT product_id FROM cart_products
WHERE deleted=0 AND cart_id=?))
OR
NOT EXISTS
(SELECT product_id FROM coupon_products
WHERE coupon_id=?)

Wh00t!!11oneeleven. That will return a '1' if the coupon has products attached that are in the cart (and not deleted) OR if there are NO products associated with the coupon (meaning it's global).


The alternative to doing it this way would've been much, much slower and involved a lot of iterating and comparison. I'm getting this SQL thing figured out.

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>