Repository navigation
Description
The question is: where should nulls values end up in when sort-ing a relation?
A followup for #2617
This justification was made by dissecting "what sorting is" down to formal mathematical (unwritten) definition of relations and PRQL. So bear with me, it may look like it's getting way to broad and abstract, but I believe that semantics of the language will remain as concise and orthogonal as they are now only if we really know what we are designing.
As a start, I'd suggest that instead of thinking about where the NULLs should be, we design this by figuring out what comparison operation should return for null values and derive the behavior of sort from that.
So, these are the key questions:
1 < 1 -> false (obviously)
1 < 2 -> true (obviously)
1 < null -> ?
2 < 1 -> false (obviously)
2 < 2 -> false (obviously)
2 < null -> ?
null < 1 -> ?
null < 2 -> ?
null < null -> ?
There are three ways of filling this out:
null < xfor every non-null x,x < nullfor every non-null x,falsefor all comparisons to null.
Option 1. and 2. are straight forward: if null is less than every other value, this translates to DESC NULLS LAST and ASC NULLS FIRST. If null is greater than every other value, it's the other way around.
But option 3 is interesting. What happens if null is not less, greater or equal to any number?
This is (of course) well researched in math and it is named a (strict) partial ordering. The < operator (they call it 'relation', but I'm not going to do that to the reader) must be ireflexive, anti-symmetric and transitive. With these properties it makes sense to define that a "sorted sequence" has every pair a < b in such positions that a is before b.
But this partial ordering does not imply that there is a single unique sorted sequence.
For example, take a set of products and a operator "is made from". You can have a chain "wood < wooden board < desk". But there is also "wood < wooden pillar < house". So these are two separate sorted chains with a common predecessor. But there is no relation between desk and house, so they cannot be merged into a single chain. Nevertheless, you can construct a sorted sequence such that every element comes after all its components:
wood, wooden board, desk, wooden pillar, house
The sorted sequence of this ordering is not unique as you could also have:
wood, wooden board, wooden pillar, desk, house
... and the desired property would still hold.
In practice, we are usually dealing with sets where at least one of the following is true: a < b or b < a or a == b. In words this means roughly "you can compare any two elements". Such constructs are called "total ordering" and provide a way to construct a unique sequence of elements where for every two consecutive elements a and b, it holds that a < b.
Fortunately, we don't need to deal with the most general case from the theory of sorting. Our base case are sets that have a total ordering (i.e. ints, strings, bools).
When nulls are added to the set, it becomes a partial ordering, because (using option 3 above) null is not greater, equal or less to any other value. Sequences constructed from this partial ordering could contain nulls at any position, as that would not violate any of the < operators.
When we use NULLS FIRST/LAST in SQL, we extend the < operator to say "nulls are less than any other value" or "nulls are greater than any other value", depending on what we need. The result is a total ordering which has the unique sorted sequence that we want.
So, for the purposes of PRQL, I suggest that we separate the "sorting" from the "extending < operator so partial ordering becomes total ordering":
from tracks
sort (nulls_last billing_state)
Function nulls_last would take any primitive value and map it to something (let's imagine integers) such that nulls will be last and all other values would preserve order from the initial type. But that's formal definition, in practice we'd compile to NULLS FIRST or NULLS LAST. We would also have to make sure that both of these get compiled correctly:
from tracks
sort (nulls_last (-billing_state)) # DESC NULLS LAST
sort (-(nulls_last billing_state)) # DESC NULLS FIRST
What this implies is that using plain sort billing_state is attempting to use a partial order for sorting. We can decide on a behavior here:
- allow it. Partial ordering may have nulls at any position, which means that both NULLS LAST and NULLS FIRST are "correct" because PRQL does not guarantee anything here.
- deny it. We can make a nice error message saying "this may contain nulls, use
nulls_firstornulls_last. A bit less convenient, but much more reproducible.
Activity
max-sixty commentedon May 24, 2023
Thanks for an "@aljazerzen epic"! 😁
An incomplete quick question clarifying one thing, partly because I got confused by reading docs on
NULLS LASTout there:IIUC
NULLS LASTdoesn't imply a general ordering of nulls against other values. In particular, it has opposite orderings forASC&DESC. ForASCthey're bigger than other values, forDESC, they're smaller than other values.(Clearly it implies an ordering conditional on the value of
ASC/DESC— we have to put the nulls somewhere. And in e.g. BigQuery, Nulls are always smaller than other values without specifyingNULLS ...)Is that your understanding too?
From the DuckDB issue:
max-sixty commentedon May 24, 2023
FWIW I think this would be much too restrictive for a language like PRQL. But given the prevalence of columns which a) don't have nulls and b) aren't typed as not having nulls — that would add a bump for users without fairly sparse benefits IMO.
I could imagine it being good for a more precise representation, such as an IR — forcing the higher level representation to make a reasonable default...
eitsupi commentedon May 25, 2023
I think the argument here is that this is related to the fact that a comparison to
NULLalways returnsNULLin SQL.On the other hand, PRQL is expected to always return
trueorfalsein comparison tonull.prql/web/book/src/language-features/null.md
Lines 18 to 28 in 2e03033
aljazerzen commentedon May 25, 2023
Yes, I doesn't imply general ordering, just an ordering for this particular ORDER BY clause. If I had to write down format semantics of ORDER BY in SQL, I would define new
<operator for every combination of type being compared, ASC/DESC and NULLS FIRST/LAST.Oh yes, of course - I didn't mention that, but
<,>,<=,>=and==should always a boolean, otherwise semantics get much more complicated. Fortunately, we vowed not to inherit things like this from SQL, which means that PRQL'snullis quite a different thing than SQL'sNULL.aljazerzen commentedon May 25, 2023
That's true, being strict here does not have much benefit and would be quite inconvenient.
What do you think about defaulting to infer all columns as not-null? In such scenario, the error about "missing nulls_last" would only show up for columns that were explicitly marked as nullable.
I have a feeling that this would still be too inconvenient.
max-sixty commentedon May 26, 2023
I do think this is better — I think it mostly depends on how flexible the assignment of nullable / non-nullable columns is. We can def see how it looks.
Assuming we don't force users to be explicit, which is the design we most prefer? I agree that there's no perfect choice, we should choose something though (which could be "defer to the DB")...
aljazerzen commentedon May 26, 2023
Well, my current idea on how to declare tables looks like this:
Ordering enforcement would look like this:
So the 3 viable options are:
null < xfor every non-null x (this would be DuckDB's option 1),null > xfor every non-null x (this would be DuckDB's option 2),nulls_firstwhen a column is marked as nullableNote that there is no DuckDB's option 3 or 4 on the table, because they have different ordering depending whether you are using DESC or ASC - which is mixing two things that should be orthogonal.
max-sixty commentedon May 27, 2023
Re (3) — at the moment we don't have an ability to specify column types, and even when we add that, most users won't be specifying columns, so we do need to decide some way to proceed without knowing the type of the column. (Or lmk if we disagree there?)
Apart from this, I don't have a particularly strong view. I'm not enamored by (1) or (2) — I don't yet understand why nulls should necessarily always be bigger / smaller than non-null values, vs being treated differently. The DuckDB approach of "nulls always go at the end" seemed reasonable to me.
How would we evaluate
5 < null? If we're not doing three-valued logic at all, then the answer becomes easier, but I'm not sure if that's viable with SQL databases as targets?aljazerzen commentedon May 28, 2023
That is partially true: if we go for option (3), we can delay this decision to when we support column type definitions.
It is not entirely true, because we should think about what happens when users sort by a column that is inferred to be non-null, the compiler figures it doesn't have to bother with "where do null values go" it outputs a query that assumes there will be no null values, and then there are null values.
If we wanted to be precise, we'd compile to a query that validates that the input conforms to the type definitions we inferred (or were defined). If they do not hold, entire query may be invalid / may produce errors somewhere else, which means we should abort as soon as possible.
I really don't want to go down the road of "oh it's fine, let's execute the query anyway", because many guarantees of what a PRQL query will output cannot hold anymore, if it has been compiled for a different scenario than what it is used in. In such case, we cannot formally define where the nulls should go, because formally, there should be no nulls!
Actually, the more I think about it, we probably cannot afford to infer columns non-null by default.
With currently proposed semantics,
5 < nullshould compile toCOALESCE(5 < NULL, FALSE).max-sixty commentedon Jun 4, 2023
As discussed on dev call — we all quite liked "If it's not sortable, it goes at the end".
This would imply
NULLS LASTWe're going to think more about this, if we agree we can re-merge
NULLS LAST. (which is not un-revertable but we should try and avoid...)aljazerzen commentedon Jun 4, 2023
I agree, out of all options,
NULLS LASTis the most convenient, by far. I'll try to find a formulation that would implement that, while also being counted as "format semantics definition".This here is a working draft, I'll update it later and maybe move it into the book.
Definitions
an ordering is expressed as a function with:
a<T> b<T> -> bool(non-null, we use notationa < b),not (a < a)a < bthennot b < aa < b && b < cthena < ca sorting is an array of arrays, where for every pair
a<T>andb<T>it holds that:a < b, thenaandbare placed in same sub-array andais positioned beforeb,not (a < b || b < a),aandbare placed in separate sub-arrays,Note: the types of sorting sub-arrays must be computable statically. Their cardinality is associates with the number of elements in a type.
Theorem: every ordering has a unique sorting, iff each of the sub-arrays has a unique cardinality.
sorttakes an ordering and returns a flattened sorting,mintakes an ordering and returns last element of first sub-array of the sorting,maxtakes an ordering and returns first element of first sub-array of the sorting,Examples:
int
int || null
some weird enum, partially comparable
Notes
There is no such thing as "ascending" or "descending" sorting. You can, however, change the ordering, such that iff
a < bin old sorting then in the new sortingb < a. This will reverse each of the sorting sub-arrays, but will not change the order of the main sorting array.TODO
max-sixty commentedon Jun 8, 2023
I agree with these semantics! In these terms — what defines the ordering of the sub-arrays themselves? Why does the sub-array with nulls go last?
A similar way of formulating this is "There's a hegemonic type for each column. Anything not comparable to that type goes at the end." That accounts for nulls, but not for different incomparable Enums.
max-sixty commentedon Jun 8, 2023
Do we want to merge the
NULLS LAST? Is this refining how we're conceptualizing it or making a decision on whether to proceed?(I'm happy to resuscitate that PR if we are)
aljazerzen commentedon Jun 8, 2023
Yea, that would work. I didn't want to give nulls any special status here. To keep things orthogonal :D
Yes, I think this case is strong enough to justify NULLS LAST.
max-sixty commentedon Jun 12, 2023
FYI because of #2754 (comment), this is no longer urgent / a blocker for 0.9.0...
docs: Remove rolled-back `nulls last` docs
docs: Remove rolled-back `nulls last` docs
lukapeschke commentedon Jan 30, 2025
Hello @max-sixty is there a way today to specify
NULLS LASTwhen usingsort? I have not been able to figure out if there was a way to use an s-string for that