Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between select() and table.select()

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?

like image 888
BlaShadow Avatar asked Dec 02 '12 20:12

BlaShadow


1 Answers

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.

like image 73
Martijn Pieters Avatar answered Sep 21 '22 09:09

Martijn Pieters