1

I was trying to create a query that finds products with price less than or equals to avgPrice.

Below is the sample query.

await Product.findAll({
    attributes: [
      'id', 'name', 'price',
      [sequelize.literal(`SELECT AVG(price) from Products`), 'avgPrice']
    ],
    where: {
      price: {
        [Sequelize.Op.lte]: sequelize.col('avgPrice')
      }
    }

But it gives the following error.

Unknown column 'Products.avgPrice' in 'where clause'

Also I tried to copy the query generated by sequelize and execute it manually in mysql but it gives the same error.

Isn't this how we run the query?

Edit: I changed the query requirements from avgPrice < 100 to price < avgPrice. However, the problem in the question is the same.

3
  • 1
    to filter aggregate you need to use having instead of where Commented Dec 23, 2019 at 10:46
  • 1
    @LukaszSzozda thanks for helping me out. So we should using having clause. Damn it! mysql should give error message like somehting else. You can post your answer. Commented Dec 23, 2019 at 11:01
  • Create your query in sql first and verify its working. Then write it in sequelize and check if sequelize is generating the same query (semantically) or not. It will help you in debugging. Commented Dec 23, 2019 at 11:03

1 Answer 1

2

If you want to filter based on aggregated column you need to change WHERE clause to HAVING.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.