🗂️SQL ORDER BY Builder

List sort keys in order to get an ORDER BY clause, with a fallback where NULL placement is unsupported.

The second field takes ASC or DESC and the third takes NULLS FIRST or NULLS LAST. The third field may be left empty. Column names pass only when built from letters, digits and underscores, and function calls or expressions as sort keys are not supported.

You Might Also Need

About this tool

List your sort keys in priority order and the tool builds the ORDER BY clause. Each column takes ascending or descending order and, if you want, an explicit NULL placement. Pick the identifier quoting your database uses and the clause comes out in that form; name a unique column to append last and it is folded into the clause as well.

Support for NULL placement differs across databases. PostgreSQL accepts NULLS FIRST and NULLS LAST directly, while MySQL and MariaDB have no such clause. Choosing MySQL therefore inserts an IS NULL expression as an extra sort key in front of that column to produce the same order, and the tool reports which keys were rewritten. The default NULL position each database documents is shown as well.

This tool builds the ORDER BY clause only. It does not write condition clauses or table creation statements, and it does not support function calls or computed expressions as sort keys, custom collation orders or case-folding rules. It also makes no prediction about sort performance or index use.

Frequently asked questions

How do I push NULLs to the end in MySQL?

Put an IS NULL expression one step ahead as a sort key. That expression is 1 for NULL rows and 0 otherwise, so sorting it ascending sends NULLs to the end. Choosing MySQL in this tool produces exactly that form.

Why append a unique column at the end?

Rows that share the same sort key values have no defined order among themselves. The same query can return them differently on a second run, which makes paged reads repeat or skip rows. One unique value at the end makes the order stable.

What does this tool not do?

It does not write condition clauses, sort by functions or expressions, apply custom collations or predict performance. It builds a column-based ORDER BY clause only.