Search code examples
mysqlsqlwhere-clauseordinals

Reference column in mysql where clause by its index


All tables in my database always have an id (autoincrement), at column 0 regardless of its name, it's always there.

So, in table teste I probably have idTeste, in table cars I should have idCars, but the format is not a standard, I could have a table example with a column simply called id.

I'm trying to create a generic update like:

update tablename set bla='ble' where column[0]='id';

so, don't matter the column's name, I wish to reference it by its id. Is that possible?

I know I can do something like:

show columns from table

and pick the first name before execute my update, and, in fact, I did that to solve my problem, but I'm curious if it was possible.


Solution

  • What you're after is called the ordinal position, or simply "ordinal".

    SQL does not support using ordinals in the WHERE clause. Support for ordinals differs between database vendors -- the most common support is in the ORDER BY clause:

    ORDER BY 2, 1
    

    ...which relies on the column(s) listed in the SELECT clause. Some support ordinals in the GROUP BY clause.

    That said, using ordinals is not a recommended practice because it's dependent on the order of the columns in the SELECT clause. If that order changes without the ORDER BY/etc being updated, you won't know until runtime.