SQL

Reversing Output of SQL SELECT

In the SQL programming language (scripting language) for database operations, this article introduces how to reverse the output of select. There are situations where you want to reverse the output of SQL select. For example, in this case…

Shou Arisaka
2 min read
Oct 26, 2025

In the SQL programming language (scripting language) for database operations, this article introduces how to reverse the output of select.

There are situations where you want to reverse the output of SQL select. For example, in this case, we want to retrieve some clipboard history from the database “in the order they were copied to the clipboard”.

Bash has a command called tac that reverses command output results. Depending on the situation, you can output SQL select to standard output and then tac it, but if there are fields containing line breaks, commands like tac won’t make sense.

If you’re going to do that kind of processing, you should handle it on the SQL side, but how exactly should you do it?

We have SQL like this:

SELECT mText from Main
WHERE mText REGEXP "."
order by clipOrder desc
LIMIT 3 OFFSET 0

This produces output like:

hoge
fuga
foo

We want to change this to:

foo
fuga
hoge

Pass a subquery to select and sort it again.

SELECT q.mText
    FROM (SELECT * from Main
          WHERE mText REGEXP "."
          order by clipOrder desc
          LIMIT 3 OFFSET 0) as q
    ORDER BY q.clipOrder ASC

Share this article

Shou Arisaka Oct 26, 2025

🔗 Copy Links