Basic Syntax
Ascending Order (Default)
| Database | Output |
|---|---|
| PostgreSQL | SELECT * FROM users ORDER BY name ASC |
| MySQL | SELECT * FROM users ORDER BY name ASC |
| MongoDB | db.users.find({}).sort({ name: 1 }) |
Descending Order
| Database | Output |
|---|---|
| PostgreSQL | SELECT * FROM users ORDER BY created_at DESC |
| MongoDB | db.users.find({}).sort({ created_at: -1 }) |
Multiple Columns
| Database | Output |
|---|---|
| PostgreSQL | SELECT * FROM users ORDER BY status ASC, created_at DESC |
| MongoDB | db.users.find({}).sort({ status: 1, created_at: -1 }) |
Expressions in ORDER BY
Sort by calculated values or function results.| Database | Output |
|---|---|
| PostgreSQL | SELECT * FROM products ORDER BY price * quantity DESC |
| MySQL | SELECT * FROM products ORDER BY price * quantity DESC |
Function in ORDER BY
| Database | Output |
|---|---|
| PostgreSQL | SELECT * FROM users ORDER BY LENGTH(name) DESC |
| MongoDB | db.users.aggregate([{ $addFields: { nameLen: { $strLenCP: '$name' } } }, { $sort: { nameLen: -1 } }]) |
With WHERE Clause
| Database | Output |
|---|---|
| PostgreSQL | SELECT * FROM users WHERE active = true ORDER BY name ASC |
| MongoDB | db.users.find({ active: true }).sort({ name: 1 }) |
With LIMIT
| Database | Output |
|---|---|
| PostgreSQL | SELECT * FROM users ORDER BY created_at DESC LIMIT 10 |
| MongoDB | db.users.find({}).sort({ created_at: -1 }).limit(10) |
Pagination Pattern
| Database | Output |
|---|---|
| PostgreSQL | SELECT * FROM users ORDER BY id ASC LIMIT 20 OFFSET 40 |
| MongoDB | db.users.find({}).sort({ id: 1 }).skip(40).limit(20) |

