User-Defined Ordering

2025-11-27


The Problem

Let’s say you’re building a to-do app. Users want to drag tasks around and create their own order. Not alphabetical, not by due date, just whatever makes sense to them. Seems simple enough. You add an integer position column to your tasks table, and whenever a user drags a task, you update the position.

This works fine for the first few thousand users. But then you scale up. Now you’ve got users with hundreds of tasks, concurrent users dragging things around at the same time, and things start to break down. Every single drag operation requires you to renumber potentially every other task in the list. That’s O(n) database writes for a single interaction. At scale, this is a disaster.

To fully understand the issue, we must first distinguish between semantic ordering and user-defined ordering.

Semantic Ordering

Semantic ordering is ordering by something inherent to the data. You’re ordering by a property that already exists:

Semantic ordering is deterministic and reconstructible. If a user deletes a task and re-adds it, it automatically goes back to its correct position. If you decide to change the ordering algorithm, all your data still makes sense, you just change your query.

Semantic ordering is cheap. You add an index, adjust your ORDER BY clause, and you’re done.

User-Defined Ordering

User-defined ordering is different. It’s explicit state. The user is saying “I want this item here”, independent of any property on the item itself. You’re now responsible for tracking a ranking that lives outside the item’s data.

This is what to-do apps, kanban boards, and wishlists do. The position doesn’t come from the data, it’s something the user explicitly decided on.

Naive Implementation: Integer Ordering

In our naive implementation, we added an integer column to the table to represent the ordering. Let’s look at an example to see how that works.

Here’s what the table looks like. We’ve got two columns: ID and Name.

Data sorted by ID
IDName
01Orange
02Grape
03Banana
04Cherry
05Strawberry
06Raspberry
07Lemon
08Lime
09Pineapple
10Mango
Data sorted by Name
IDName
03Banana
04Cherry
02Grape
07Lemon
08Lime
10Mango
01Orange
09Pineapple
06Raspberry
05Strawberry

Let’s throw an integer column Order onto the table and see how manual ordering works.

Data sorted by Order
IDNameOrder
01Orange1
02Grape2
03Banana3
04Cherry4
05Strawberry5
06Raspberry6
07Lemon7
08Lime8
09Pineapple9
10Mango10
→

Lime
to first

Data sorted by Order
IDNameOrder
08Lime1
01Orange↓2
02Grape↓3
03Banana↓4
04Cherry↓5
05Strawberry↓6
06Raspberry↓7
07Lemon↓8
09Pineapple9
10Mango10

After moving Lime to the top of the list, we had to update the order for all entries that were previously above it. The number of entries we update depends on how far up (or down) the list a user is adjusting their item.

With a small list, this isn’t a big deal. But imagine you’re on a large software development team, and you decide to finally bring that ticket out of the backlog (that one ticket you’ve been putting off for years). You’re bringing that ticket up in priority over potentially hundreds or even thousands of other tickets.

Now imagine you’re a stakeholder in the meeting when that happens, and you figure it’s time for your long-awaited task to get prioritized. So you move a different ticket deep out of the backlog at the same time. We’re now putting fairly large load on our database for relatively normal user behavior.

Improved Implementation: Float Ordering

Let’s try using a float instead of an integer. When we move an item, we can calculate a new order based on the position of the surrounding items. We’ll use a formula like…

new order = (order above + order below) / 2

If we move an item to the top of the list, we’ll use 0.0 as the order above value.

If we move an item to the bottom of the list, we can simply use new order = order above + arbitrary value.

Data sorted by Order
IDNameOrder
01Orange1.0
02Grape2.0
03Banana3.0
04Cherry4.0
05Strawberry5.0
06Raspberry6.0
07Lemon7.0
08Lime8.0
09Pineapple9.0
10Mango10.0
→

Lime
to first

Data sorted by Order
IDNameOrder
08Lime0.5
01Orange1.0
02Grape2.0
03Banana3.0
04Cherry4.0
05Strawberry5.0
06Raspberry6.0
07Lemon7.0
09Pineapple9.0
10Mango10.0
→

Lemon
to second

Data sorted by Order
IDNameOrder
08Lime0.5
07Lemon0.75
01Orange1.0
02Grape2.0
03Banana3.0
04Cherry4.0
05Strawberry5.0
06Raspberry6.0
09Pineapple9.0
10Mango10.0
→

Grape
to last

Data sorted by Order
IDNameOrder
08Lime0.5
07Lemon0.75
01Orange1.0
03Banana3.0
04Cherry4.0
05Strawberry5.0
06Raspberry6.0
09Pineapple9.0
10Mango10.0
02Grape11.0

Notice that while many items have shifted positions (when ordering), the underlying data ordering them hasn’t changed.

This does leave us with “holes” in our order column, there are no longer rows with 2.0, 7.0, or 8.0. Holes themselves aren’t an issue though, and holes can be filled if another item is moved into that slot in the list.

Is this a perfect solution over integer ordering? No.

One issue with this implementation is you eventually run out of precision to calculate a new order between two items. If you have an item with the order 0.002 and another item with the order 0.003, and you only have a few digits of precision, you may not be able to create a number between them.

If you go with a float ordering, you may need to regularly rebalance your table. This may require temporarily locking the rows to rewrite the order column, bringing the values closer to lower-precision values while still retaining their overall order.

This largely depends on your use case and how much precision you give to your order column. If items move around rarely and you can allocate enough space, you may never need to worry about rebalancing. If items move around frequently and you’re constrained on space, you may need to rebalance more often.

Can we do better?

Improved Implementation: Alphabetical Ordering

The issue we ran into with float ordering occurred because we used a fixed-size data type. So what if we use a data type that can have an unlimited size?

Many databases have a variable character data type, allowing you to store strings of arbitrary (and unlimited) length. In Postgres, this is the text type. If we store the order as a string instead of a numeric value, we can take advantage of alphabetical ordering combined with “unlimited precision” (though there is a caveat here).

Let’s see what this may look like:

Data sorted by Order
IDNameOrder
01Orangea
02Grapeb
03Bananac
04Cherryd
05Strawberrye
06Raspberryf
07Lemong
08Limeh
09Pineapplei
10Mangoj

Our formula for calculating a new order is far more complicated with this method, and there are some edge cases we’ll need to address. This formula is complicated enough that we could describe it as an algorithm.

You can find a fully functional version of this algorithm in Python, with tests, here: https://github.com/fletcheaston/lexical-center.

The fundamental approach is to make decisions at each character position, starting from the leftmost character. If we can resolve the positioning at the first character level (by finding a character that falls between the first characters of left and right), we do so and return immediately. Only when we can’t resolve at the first level do we recurse deeper into the remaining portions of the strings.

import string
from typing import Sequence


def lexical_center(
    *,
    left: str,
    right: str,
    characters: Sequence[str],
) -> str:
    """
    Generates a new string that sorts lexically between the left and right bounds,
    excluding a few edge cases.
    All characters in 'left' and 'right' must be in 'characters'.

    Edge cases:

    - 'left' == "" and 'right' == "": returns ~center of 'characters'
    - 'right' endswith 'characters[0]': raises 'ValueError'
    """

    # Edge cases
    if right.endswith(characters[0]):
        raise ValueError(
            "Right string cannot end with first character in the character set."
        )

    # Actual logic
    if left == "" and right == "":
        return characters[len(characters) // 2]

    if left == "" and right != "":
        if right[0] in characters[0:2]:
            return characters[0] + lexical_center(
                left="",
                right=right[1:],
                characters=characters,
            )

        return characters[characters.index(right[0]) // 2]

    if left[0] == characters[-1] and right == "":
        z_index = 0
        while z_index < len(left) and left[z_index] == characters[-1]:
            z_index += 1

        left_index = characters.index(
            left[z_index] if z_index < len(left) else characters[0]
        )

        return left[0:z_index] + characters[(left_index + len(characters)) // 2]

    left_index = characters.index(left[0])

    if right == "":
        return characters[(left_index + len(characters)) // 2]

    right_index = characters.index(right[0])

    if left[0] == right[0]:
        return left[0] + lexical_center(
            left=left[1:],
            right=right[1:],
            characters=characters,
        )

    if left[0] == characters[-1]:
        return left[0] + lexical_center(
            left=left[1:],
            right=right,
            characters=characters,
        )

    if left_index + 1 == right_index:
        return left[0] + lexical_center(
            left=left[1:],
            right="",
            characters=characters,
        )

    return characters[(left_index + right_index) // 2]

This code is very complicated, but it works well! Some examples using lowercase characters:

LeftRightResult
aban
aadab
abcdb
dhf
dge
hithn
hsithw
hzithzn
hzsithzw
hzzithzzn
dztedzw
vzuwvzx
lzymlzz

One edge case we’ll need to contend with is moving an item to the top of the list. When this happens, we’ll need to update the order of the item directly below it. While this does involve an additional write operation, it’s only a single write, not a write for every row. This has far less of an impact than rewriting {N} rows, like we did with integer ordering.

Let’s walk through the same example that we did with floats.

Data sorted by Order
IDNameOrder
01Orangea
02Grapeb
03Bananac
04Cherryd
05Strawberrye
06Raspberryf
07Lemong
08Limeh
09Pineapplei
10Mangoj
→

Lime
to first

Data sorted by Order
IDNameOrder
08Limea
01Orangean
02Grapeb
03Bananac
04Cherryd
05Strawberrye
06Raspberryf
07Lemong
09Pineappleh
10Mangoi
→

Lemon
to second

Data sorted by Order
IDNameOrder
08Limea
07Lemonag
01Orangean
02Grapeb
03Bananac
04Cherryd
05Strawberrye
06Raspberryf
09Pineappleh
10Mangoi
→

Grape
to last

Data sorted by Order
IDNameOrder
08Limea
07Lemonag
01Orangean
03Bananac
04Cherryd
05Strawberrye
06Raspberryf
09Pineappleh
10Mangoi
02Grapej

Your strings will grow in size with enough rearranging. But because strings can have unlimited length in many databases, you aren’t going to run into the same limits of precision as with floats or other numeric types.

One limitation with this approach: many databases, Postgres included, limit how large an indexed value can be. If you have a large enough string, Postgres won’t be able to index your value, and may block your write. This size constraint is fairly large (~2kb), but it is something to keep in mind. Some queries may benefit from indexing the order column, and if you find yourself running into this issue, you’ll need to rebalance your table (similarly to the float ordering method).

No Silver Bullet

Engineering is all about making trade-offs. Do lists only have a handful of items? Maybe skip the complexity and go with integer ordering. Is storage limited but compute (i.e. rebalancing) cheap? Maybe a float ordering will work. You’ll need to consider how users interact with your system to determine the best solution.

Furthermore, none of these approaches consider how to enable concurrent reordering. There are many approaches you can take to address this problem, but the best option depends on the needs of your application. This is left as an exercise for the reader :)