How to select specific columns from database table?

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google “How to X in SQLModel” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from typing import Optional

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


class Hero(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: Optional[int] = None


sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"

engine = create_engine(sqlite_url, echo=True)


def create_db_and_tables():
    SQLModel.metadata.create_all(engine)


def create_heroes():
    hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
    hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
    hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)

    with Session(engine) as session:
        session.add(hero_1)
        session.add(hero_2)
        session.add(hero_3)

        session.commit()


def select_heroes():
    with Session(engine) as session:
        session.exec(select(Hero)).all()


def main():
    create_db_and_tables()
    create_heroes()
    select_heroes()


if __name__ == "__main__":
    main()

Description

In the docu it is mentioned that it is possible to select only specific columns from the datatable. However, the example is only given for SQL and not for SQLModel

So how can I implement this query in SQLModel?

SELECT id, name
FROM hero

Finally I also dont want to hardcode the column of interest but the column name(s) will be stored in a variable.

Operating System

Windows

Operating System Details

No response

SQLModel Version

0.0.6

Python Version

3.8.1

Additional Context

No response

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:1
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
StefanBrandcommented, Mar 15, 2022

For reference, it is possible to select columns like this:

with Session(engine) as session:
    heroes = session.exec(
        select(
            Hero.id,
            Hero.name
        )
    ).all()

However, the return type is <class 'sqlalchemy.engine.row.Row'>

1reaction
byrmancommented, Feb 1, 2022

Perhaps there are other / better ways, but examining the echoed SQL, this seems to work:

from sqlalchemy.orm import load_only

def select_heroes():
    with Session(engine) as session:
        session.exec(select(Hero).options(load_only("id", "name"))).all()

Or (addressing your 2nd question) via: load_only(*fields)

Read more comments on GitHub >

github_iconTop Results From Across the Web

SQL Exercises: Select specific columns from a table
SQL Exercise, Practice and Solution: Write a SQL statement to display specific columns such as names and commissions for all salespeople.
Read more >
Selecting columns and tables - IBM
To select columns, choose one of the following options: Type SELECT , followed by the names of the columns in the order that...
Read more >
Select specific rows and columns from an SQL database
Identify the rows which hold the data of interest (WHERE clause). This is done by putting conditions on column values (there are no...
Read more >
Finding Tables that Contain a Specific Column in SQL Server
Find all tables in the database which contain a specific column in SQL Server through catalog views and the LIKE statement.
Read more >
SQL SELECT Statement - W3Schools
The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found