Search code examples
mysqlwhere-clausestring-interpolationcomparison-operators

Is there a way to 'interpoloate' a column's value as the comparison operator in the WHERE clause in MySQL?


Let's say I have a column named "comparison_operator" with values like '>', '=', '<'. in the "products" table. Is there a way to use it in the WHERE clause like the following?

SELECT products.name FROM products WHERE products.price #{comparison_operator} products.cost

I believe the answer to this question is no but would like to see if there's alternative way to achieve the same purpose. Thank you!


Solution

  • Yes, but not like that.

    CASE
      WHEN products.comparison_operator = ">"
        THEN products.price > products.cost
      WHEN products.comparison_operator = "<"
        THEN products.price < products.cost
      ELSE
        products.price = products.cost
    END