Skip to content
Advertisement

Is there an optional prepared statement in SQL for different specific levels of querying

Suppose I have a query that returns the total monthly sales of individual products in my database:

product = input("Enter product column to search")
milkOptions = input("Enter milkOptions column to search")
size = input("Enter size to search")

import sqlite3

conn=sqlite3.connect("system.db")
cur=conn.cursor()
sql ="""
select sum(quantity*price), strftime("%m-%Y", orderDate) 
as month 
from customerOrders
WHERE product = ? and milkOptions = ? and size = ?
group by orderDate"""

Is there a way to query various levels of specificity without creating many similar queries. For instance, If i enter Espresso for the product, leave out the milkoptions entry, and enter small for size, could I return all Small Espresso sales. Vice versa for leaving out and entering other options.

Here is my database:

+---------+-----------+--------+-------------+------------+----------+-------+------------+
| orderid |  product  |  size  | milkOptions | orderDate  | quantity | price | customerid |
+---------+-----------+--------+-------------+------------+----------+-------+------------+
|       1 | Espresso  | Small  | Soya        | 2019-10-29 |        1 | 1.0   |        1   |
|       2 | Cappucino | Small  | SemiSkimmed | 2019-10-29 |        1 | 1.0   |        1   |
|       3 | Cappucino | Small  | SemiSkimmed | 2019-10-29 |        1 | 1.0   |        1   |
|       4 | Cappucino | Medium | SemiSkimmed | 2019-10-29 |        1 | 1.0   |        1   |
+---------+-----------+--------+-------------+------------+----------+-------+------------+

Advertisement

Answer

Pass an additional flag parameter 0 or 1 for each of the columns, like:

WHERE 
  (product = ? OR 0 = ?)  
  AND 
  (milkOptions = ? OR 0 = ?) 
  AND 
  (size = ? OR 0 = ?)
  • When you pass 0 for the product‘s flag parameter (and anything not null for the column product) the condition will evaluate to TRUE which is equivalent to not setting a condition for the column product.
  • When you pass 1 for the product‘s flag parameter and 'someproduct' for the column product then the condition is equivalent to product = 'someproduct'.
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement