Home > Software engineering >  how to select min, max and average with sqlalchemy
how to select min, max and average with sqlalchemy

Time:12-12

I want to select the min, max and average value of the column VALUE and where the timestamp > some date and < some other date with LIMIT and offset

from sqlalchemy import func
...

engine = create_engine(URL)
metadata = MetaData()

my_table = Table(
    "my_table",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("value", Numeric()),
    Column("timestamp", DateTime(timezone=True)),
)

database = Database(DATABASE_URL)
metadata.create_all(engine)

query = my_table.select(func.min(my_table.c.value)).where(my_table.c.timestamp > some_date).where(my_table.c.timestamp < some_other_date).limit(100)
result = database.fetch_all(query=query)

But i get the following error:

aggregate functions are not allowed in WHERE

This is partially the generated query:

SELECT my_table.id, my_table.value, my_table.timestamp FROM my_table WHERE min(my_table.value)

One might think that the min would be used in the select statement and not in the where clause.

Looking on the internet people are using all kind of different ways with sessions and ORMs and raw queries with filers etc.

How do I create it with the above example?

CodePudding user response:

The first parameter to Table.select is a where clause. You have passed an aggregate function, and since aggregate functions are not permitted in WHERE clauses in SQL you get an error.

As Ben suggests in their comment, you would be better to use sqlalchemy.select like this:

query = sqlalchemy.select(func.min(my_table.c.value)).where(my_table.c.timestamp > some_date).where(my_table.c.timestamp < some_other_date).limit(100)
  • Related