What are the differences between select and tablename.select()? When I pass column name to table.select like:
table.select(table.c.name)
the sql is like
select * from tablename where tablename.name
and when I pass a column to select (instance method):
select([table.c.name])
the sql is like
select name from tablename
I want the same result as select with table.select.
When I read the docs of select it’s the same so it’s the same method but why they have a different behavior?
Presumably, with
select()you meansqlalchemy.sql.select().The
select()function expressly takes a set of columns as it’s argument, and it’s result is a stand-aloneSelectinstance. You can also pass in aFromClauseobject (like a table or an alias) and it’ll take the columns from that object. This is described in detail in the Selecting chapter of the core tutorial.The
.select()method on a table on the other hand, takes awhereclausefirst argument, not a set of columns. In other words, whatever you pass to that method, form theWHEREfilter for the select, not the columns you wanted to select. By passing in a column for the where clause, you are selecting all columns, but filtering onWHERE [columnname]. Not much of a filter, since there the expression doesn’t really restrict what rows will match.Proper use of the
table.select()function is to pass in a selection filter, and the intention to select all columns:which would be compiled to:
(although SQLAlchemy, knowing what columns exist, expands
*to an explicit list of alltablecolumn names).You should stick to the
select()function to select only specific columns.