开发者

SQL: fetching-order

my $sth = $dbh->prepare( "SE开发者_如何学GoLECT id, name, size, date FROM $table" );

while ( my @row = $sth->fetchrow_array ) {
    say "@row";
}

Are the elements in the @row-array always be in the same order as written in the SELECT-query?


The columns will always be in the same order as in the SELECT query.

If you want the rows in a specific order you have to specify it using an ORDER BY clause.


DBI modules usually rely on the idea that the database client library knows to return columns back in the order of the select statement. But, if you find some obscure DBD (DB driver) that was half implemented, nothing it guaranteed.

But for mainstream database client libraries, it is a good assumption that they know to return the columns listed in the select statement. Otherwise, it's not a good implementation of the SQL language--because that's what it means to SELECT columns.

However, as mentioned in other posts, the rows are not guaranteed to be sorted in that order. For that you would use:

SELECT id, name, size, date 
  FROM $table
ORDER BY id, name, size, date


If you need to rely on a certain order you have to specify an ORDER BY, otherwise the database is free to return the rows in any order it thinks is suitable.


Order is not guaranteed (from SQL) unless you actually specify an ORDER BY. Do you have a column you can sort over?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜