Search code examples
sqlmysqlselect

How to move the last row to the top in a table in MySQL?


I have a row in the following table which is the first row but added to the table at the end and now I'd like to modify the table in a way to show employee ids in order starting by number 1.

Here's a Screenshot of the Table:

Issue:

(
  SELECT * FROM employees
  ORDER BY employee_id DESC
  LIMIT 1
)
UNION ALL
(
  SELECT * FROM employees
  WHERE employee_id != (SELECT MAX(employee_id) FROM employees)
);

The above code is the solution from chatGPT but still doesn't move the last row to the top. Any clues?


Solution

  • SQL tables are inherently unordered sets. You can never assume nor trust the order of rows returned from a query that doesn't explicitly order them.

    If you want the employee with employee_id of 1 to come first, you could order by it:

    SELECT   *
    FROM     employees
    ORDER BY employee_id