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 mean sqlalchemy.sql.select()
.
The select()
function expressly takes a set of columns as it's argument, and it's result is a stand-alone Select
instance. You can also pass in a FromClause
object (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 a whereclause
first argument, not a set of columns. In other words, whatever you pass to that method, form the WHERE
filter 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 on WHERE [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:
table.select(table.c.name != None)
which would be compiled to:
SELECT * FROM tablename WHERE tablename.name IS NOT NULL;
(although SQLAlchemy, knowing what columns exist, expands *
to an explicit list of all table
column names).
You should stick to the select()
function to select only specific columns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With