Junior — Middle
How can you limit the number of fields returned in a database query?
sobes.tech AI
Answer from AI
To limit the number of fields returned in a database query in Python, you need to explicitly specify the required fields in the SQL query or ORM query.
For example, when using the sqlite3 or psycopg2 library with raw SQL:
cursor.execute("SELECT id, name FROM users WHERE active=1")
rows = cursor.fetchall()
Here, only the id and name fields are selected; other fields are not returned.
If using an ORM, such as SQLAlchemy:
session.query(User.id, User.name).filter(User.active == True).all()
Thus, limiting the number of returned fields is achieved by selecting specific columns in the query, rather than selecting all (SELECT *). This reduces the amount of data transmitted and improves performance.