Skip to content

How to write statements like "select count(*) from table_name where col_name>0"? #1465

Answered by notypecheck
rxy1212 asked this question in Questions
Discussion options

You must be logged in to vote

@rxy1212 You can use count function via sqlalchemy.func object like in regular sql:

from typing import Optional

from sqlalchemy import func
from sqlmodel import Field, SQLModel, Session, create_engine, select


class Table(SQLModel, table=True):
    id: Optional[int] = Field(primary_key=True)
    column: int


engine = create_engine(
    "sqlite:///",
    echo=True,
)

SQLModel.metadata.create_all(engine)

stmt = select(func.count(Table.id)).where(Table.column > 10)
print(stmt)
"""
SELECT count("table".id) AS count_1 
FROM "table" 
WHERE "table"."column" > :column_1
"""

with Session(engine) as session:
    for i in range(150):
        session.add(Table(column=i))
    session.flush()
    p…

Replies: 11 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by YuriiMotov
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested investigate
Converted from issue

This discussion was converted from issue #494 on August 07, 2025 13:22.