Mysql: ORDER BY not working as expected

Created on 3 Dec 2016  路  2Comments  路  Source: mysqljs/mysql

Query:

SELECT
  ID                 AS 'id',
  ReceivedAt         AS 'received'
FROM SystemEvents
ORDER BY ? DESC
LIMIT ?;

Parameters: [ 'received', 3 ]

Result from mysql CLI:

+------+---------------------+
| id   | received            |
+------+---------------------+
| 1838 | 2016-12-01 14:06:47 |
| 1837 | 2016-12-01 14:06:47 |
| 1836 | 2016-12-01 14:06:47 |
+------+---------------------+

The result from connection.query:

[ RowDataPacket {
    id: 1,
    received: 2016-11-22T22:28:58.000Z},
  RowDataPacket {
    id: 2,
    received: 2016-11-22T22:29:17.000Z},
  RowDataPacket {
    id: 3,
    received: 2016-11-22T22:29:19.000Z} ]
question

Most helpful comment

Hi @Otetz since the ORDER BY takes an identifier, not a value, you just need to escape using ?? as the placeholder instead of ?. Example:

SELECT
  ID                 AS 'id',
  ReceivedAt         AS 'received'
FROM SystemEvents
ORDER BY ?? DESC
LIMIT ?;

All 2 comments

I found solution :)
Don't use a placeholder in ORDER BY clause.

Hi @Otetz since the ORDER BY takes an identifier, not a value, you just need to escape using ?? as the placeholder instead of ?. Example:

SELECT
  ID                 AS 'id',
  ReceivedAt         AS 'received'
FROM SystemEvents
ORDER BY ?? DESC
LIMIT ?;
Was this page helpful?
0 / 5 - 0 ratings

Related issues

nanom1t picture nanom1t  路  3Comments

bologer picture bologer  路  3Comments

Axxxx0n picture Axxxx0n  路  3Comments

Rhapsody-Sky picture Rhapsody-Sky  路  3Comments

wahengchang picture wahengchang  路  3Comments