You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Orthogonal treatment of groups (nee Window functions) #300
Edit — this issue evolved into a much broader discussion of how we do groups. The original message is below, and I've tried to summarize the current state towards the end of the issue so it's easier for others to engage.
More than half the people I speak with about PRQL tell me that window functions are painful in SQL and would be a great feature to add to PRQL. I put window funcitons in the examples in the Readme at first, since I had the same experience in SQL.
For clarity: a window / analytic / analytical function is a function that takes other rows as an input, but instead of aggregating over many rows, it creates a new value for every row. For example, a moving average or lag. In SQL it's represented by the OVER keyword.
I haven't thought about this enough, but wanted to post an issue so we could start thinking about how to do it. A couple of initial options:
A separate pipeline, with the column at the end, and the function (lag in this case) in the pipeline:
from prices
derive price_yesterday:(
window
by sec_id
sort date
lag 1
price
)
A function with lots of named args, with the function lag as a named arg (but how would this work for functions with 0 or >1 parameters?):
from prices
derive price_yesterday:(window by:sec_id sort:date lag:1 price)
Eliminate window — because we have aggregate, we can't get confused about sum(foo) OVER and sum(foo), so possibly we don't need to have window:
from prices
derive price_yesterday:(price | lag rows:1 sort:date by:sec_id)
I don't think this is sufficiently thought through, and I'm sure these examples have inadequacies.
A nice observation that we could use in language design is that we have 3 types of functions:
scalar functions, which map a single value to a single value (e.g. FLOOR). They can be used in select and are applied to the whole column, on each value.
multi-variate functions, which map many values to a single value (e.g. SUM or MIN). They can be used in aggregate and reduce each partition to one value.
vector functions, which map a many values to many values (eg. RANK or LAG)/ They can be used as window functions in select and map column to column.
The problem is that when writing code you don't think about that. Is it advantageous if we force users to think about it?
If we would go this way, we would introduce new transform, let's say compute for lack of a better name:
from employees
compute rank(salary)
and with bounds and order:
from bills
sort issued_at
compute preceding:2 following:2 [
rolling_avg_amount: avg(amount)
]
sort number
Here I've used sort in two places, where the first affects only compute and the second affects the output.
Note that we would be the first languages I know to differentiate between select and compute in this way: dplyr, pandas and polars all have window functions within their selects.
The problem is that when writing code you don't think about that. Is it advantageous if we force users to think about it?
I definitely think there would be some benefits of structuring the language to consider types much more than SQL does — it could have a similar benefit to how your variable scoping now allows for knowing what's available to the language.
Ideally there's a synthesis where users don't need to think about it that much, but the compiler can still be helpful (not always possible :) )
vector functions, which map a many values to many values (eg. RANK or LAG)/ They can be used as window functions in select and map column to column.
Yes great. Notably some, like AVG is both a reduction & vector function.
This is related to #54, which deals with a case similar to the "scalar" and "multi-variate" / (aka "reduction") functions.
Re the compute case, we do need some way to partition the values — see the by terms above. It could be as a transform of a window pipeline (the 1st case), an arg to a window function (2nd case), an arg to the vector function (3rd case), or something else.
Another option would be to make the partition primary, with something like a by arg to a map (still need to think about this more):
from employees
map by:title ( # or `compute`?
sort:salary
rank salary
)
One invariant that I think is important to keep in PRQL is that each transform should leave a valid result. Something like .group_by in pandas or dplyr doesn't do this (and in early discussion on PRQL, Hadley said this was one of his biggest regrets). So we shouldn't have:
from employees
window by:title # Invalid result here
rank salary
Notably some, like AVG is both a reduction & vector function.
Oh, that true, nice catch.
If we go this way, compiler will be able to infer the cardinality of the rows in resulting frame: only one, many or many for a set of keys. So we could actually provide correct typing for cases like #54, which is a huge plus.
Partitions
To me, the most consistent way of specifying partitions in compute/map would be by parameter, same as aggregate. The same as in your example.
For this approach the pro is that you can specify by only once, affecting many columns:
from employees
map by:title [ # or `compute`?
rank salary,
sum working_hours,
min salary,
max salary
]
Sort
I wouldnt mix inline pipelines into transforms, it can get confusing why some things have to be in a new line and some don't. Instead I would also put sort as a parameter to the map/compute:
from employees
map by:title sort:salary [ # or `compute`?
rank salary
]
Or, even better, infer it from the current state of the pipeline:
from employees
sort salary
map by:title [ # or `compute`?
rank salary
]
This way, there is less parameters users have to remember, while still being intuitive.
The downside is that the SQL output would also contain ORDER BY, which could only be avoided with putting another sort null at the end.
Naming
I don't like compute because it does not covey the "many to many" aspect of these functions.
I don't like map because in MapReduce, it means "one value to one value".
I don't like shuffle, because it does not convey that we are adding a new column.
I don't like partition, because in a lot of cases, there will be only one partition.
I don't like window, because it does not make sense for rank, quantile and many other functions.
Maybe something about fully-connected layer of a neural network? Something about vector functions? Something about new column for every row?
... is that each transform should leave a valid result
If we go this way, compiler will be able to infer the cardinality of the rows in resulting frame: only one, many or many for a set of keys. So we could actually provide correct typing for cases like #54, which is a huge plus.
I've been trying to think about what the OVER (PARTITION BY ...)s are doing conceptually. I started down a few paths, and came back to where I started, so there's no need to read the whole thing...
A reduction function is quite simple; it just reduced each group to a single row:
A vector function with a partition / grouping creates a mini-table table for each group. In SQL, because there's generally no nesting (i.e. everything is a flat 2D table) the by field gets "unnested":
An aside: in databases with nesting, the OVER (PARTITION BY foo) function is equivalent to doing:
ARRAY_AGG ... GROUP BY title to get the arrays of engineer -> [50,200], manager -> [120,130,150], etc
Run the vector function over each group (making the middle result)
Unnest the by so title fills down (making the final result)
So one option for this is:
Use something like group or map or nest to mean "build the groups", and it would take a quasi-pipeline to run over each group. A bit like the dplyr / spark / pandas API, but the function would be an argument to this rather than a subsequent transform (consistent with every transform leaving a correct result).
Use something like compute to mean "apply this many-to-many function" (or another term, I know you say you don't like it, and I agree on the specific reason, though overall it seems decent relative to the other choices)
So that would mean we'd have something like:
from employees
group title (
sort title
compute [sum salary])
But if we do that, then we should be doing that for aggregates too:
from employees
group title (
aggregate [sum salary])
I can see the elegance of that. I'm obv hesitant to make a big change to the language at this point, and I'd need to sit on it for a couple of days before having a view. My sense is that the current model of doing aggregate by:title [] rather than than group title (aggregate [...]) is broadly equivalent and possibly easier to scan. The current approach is almost as orthogonal — we have aggregate for the reduction functions and compute (or similar) for the vector functions, not some long list. aggregate will also cover the case of making arrays.
So that brings us back to where we started!
Naming
I'm not sure on the word. I agree compute isn't ideal. calculate is basically the same. map in theory is nice — it is literally a mapping — and it's not always one-to-one. But maybe it has too much baggage. Its synonyms, like morph or functor are too weird. vec is too technical.
Sort
I get that you're less keen on pipelines-in-pipelines. I agree it's some mental overhead in simple cases, and so we shouldn't require them. But it does introduce a nice orthogonality. Say we want to "compute the two best selling items with a price higher than $100". It would be very nice to have:
from orders
{expression}
...for the case of the whole table, and:
from orders
compute by:country ({expression})
...for the case of each group. Which supplying sort:foo or having the sort outside the compute doesn't achieve.
Indeed, note that in the current language, we have
from employees
aggregate [(salary *2| sum) # possible, rather than `sum (salary *2)`
]
...as a mini-pipeline.
BUT that said, I don't have a fully fleshed out proposal, and I'd be happy to go with the sort:foo for the moment. I prefer that to having sort outside the pipeline, since that specifies too much work — sorting the whole table rather than within each group.
The idea behind having sort in the outer pipeline instead of as a param, it that if you have two consecutive sorts, we can use only the last when translating to SQL. But if there is compute between the two sorts, it is affected by the first sort. This way, you reduce the number or params one has to remember. It can also think of the sorts as they have direct effect only the the conceptual model of current pipeline value, while only some of the sorts have to be translated into ORDER BY for SQL statement to produce the same result as the conceptual model.
(I hope that makes sense...)
About the group: I really like it.
As I've written here #9 we have common use-case where it would make sense for take to also have by parameters, because in-effect you want to group by some fields and take only the top row ordered by some other column.
So aggregate, compute and take need by parameter and two of them also need sorting. Unifying them under a group context seems an elegant solution.
But I would propose a few changes to the syntax:
Group:
from employees
group title (
sort salary
derive [r: rank] # compute is the same a derive within group context
select [count - r])
from employees
group title (
aggregate [sum salary])
from employees
group title (
sort salary order:desc
take 1 # this will return all columns, but only the row within a group that contains the highest salary
)
Group essentially introduces a new context where it is allowed to use aggregate, select, derive, sort and take. The normal context can use all transforms, but aggregate will always reduce to a single number and using sum in a select will produce a SELECT SUM(...) OVER ().
Two things:
it would be attentive to the parser if we would replace parenthesis (pipeline) with braces {pipeline}. It would make it much easier to parse inline and frame pipelines.
we should go and start writing queries with this change, before starting to write any code. Maybe rewrite all the examples and add new ones. If it does feel more natural, this is the way to go.
Great, I'm thinking about this. It would be quite a change!
It does seem to be quite nice, in both conceptual elegance and readability. You're right that to really understand we should write some examples.1
Thanks for the examples, they're good. I agree with your points.
Much more narrowly:
The idea behind having sort
I very much understood the point the sort as the prior transformation — I just thought it was less coherent to have an integral part of the transformation outside of the main block. (it does fit with the pipeline notion though)
it would be attentive to the parser if we would replace parenthesis (pipeline) with braces {pipeline}. It would make it much easier to parse inline and frame pipelines.
Would this be so (expression) is an parenthesized expression, but {pipeline} was required for all pipelines? We previously had that anything parenthized expression with line breaks was a pipeline (or more specifically any line break was a pipeline outside of a list or prior to a new statement like table).
Footnotes
Though I am most of the way through a big update to how the documentation works with examples, hopefully I'll get that out so we don't have conflicts... ↩
The main change is to not use group if we're not grouping by anything — my vision of this change was that we could make PRQL even more orthogonal by having functions within a group scope operate on groups exactly the same way that they would operate on a full table without the group scope. But that means that it doesn't make sense to have an empty group.
I also wasn't sure whether I was understanding the intent of the existing query — what does the table look like after the group [order_month] transform? Presumably it's no longer possible to get the previous week's sales at that point. Forgive me if I'm missing something!
(Ironically given the subject of the issue), I'm still not sure how to specify window / analytic functions!
Should we have a specific transform for "functions which use other values in the column" — the definition of window functions — or are they just functions? i.e. is this OK:
derive num_books_last_month: lag num_books 1
or do we need:
window (derive num_books_last_month: lag num_books 1)
or:
derive (
num_books_last_month: window lag num_books 1
)
Where do we define window attributes? On the function? On the window (or whatever name we use?
I don't like window, because it does not make sense for rank, quantile and many other functions.
I'm less averse to the name window after thinking about it — it is a window over the column. It's not a moving window in the case of rank / quantile, but it says "look at the whole column rather than just my row"
We could use designations like rolling or expanding, which would make describing common windows simpler. It would bring us to a synthesis of a pandas / spark specification and a SQL spec.
I definitely think that unifying group by and partition by into a single orthogonal concept would solve one of the existing pain points of SQL window functions.
I made a couple of cosmetic changes / roadmap changes. (Possibly that's a distraction)
from co:cust_order
-join ol:order_line [co.order_id = ol.order_id]+join ol:order_line [order_id]
derive [
- order_month:s"DATE_FORMAT({co.order_date}, '%Y-%m')",- order_day:s"DATE_FORMAT({co.order_date}, '%Y-%m-%d')",+ order_month:f"{co.order_date:%Y-%m}",+ order_day:f"{co.order_date:%Y-%m-%d}",
]
group [order_month, order_day] (
aggregate [
num_orders: s"COUNT(DISTINCT {co.order_id})"
num_books: count ol.book_id
total_price: sum ol.price
]
)
group [order_month] (
sort order_day order:asc
select running_total_num_books: sum num_books
)
-group [] (- sort order_day order:asc- select num_books_last_week:lag num_books 7- )+sort order_day order:asc+derive num_books_last_month: lag num_books 1 # Not sure about this- sort order_day order:asc
Overall I think we're onto something but still need to pin down some of the details :). Your examples are v helpful in that regard.
One concern about the group approach is that it could make doing the simplest queries a bit more verbose. Say we just want to "select the sum of salary by country":
SQL:
SELECT
title,
SUM(salary)
FROM
employees
GROUP BY
title
Existing PRQL:
from employees
aggregate by:title [sum salary]
Proposed PRQL:
from employees
group title (
aggregate [sum salary])
But:
It's not that much more verbose
I generally think we should focus on making the difficult queries much more readable and coherent, rather than making simple queries a bit more concise.
To focus on the orthogonality point, there is a nice orthogonality to both:
Proposed PRQL — aggregation over groups
from employees
group title (
aggregate [sum salary])
Proposed PRQL — no groups:
from employees
aggregate [sum salary] # same transform outside a group, same effect
Proposed PRQL — using groups as partitions:
from employees
group title ( # No need for `GROUPBY` & `PARTITIONBY`, similar to how we consolidate `WHERE` and `HAVING`
window [sum salary])
from employees
group title ( # No need for `GROUPBY` & `PARTITIONBY`, similar to how we consolidate `WHERE` and `HAVING`
select [sum salary] # Or derive, depending on what you want
)
So rules would be as follows:
select/derive
can contain only scalar functions (FLOOR) and window functions (SUM, LAG, RANK)
will not change the number of rows,
when used within a group, they will produce PARTITION BY
order by is determined by last preceding sort (within or outside of group)
window is determined by parameters or select/derive1
aggregate
can contain only aggregation functions (SUM)
will reduce rows to the number of partitions (which is one when not used in a group)
Now:
there is no need for window, compute or map
select/derive/aggregate are completely orthogonal to group
this is OK:
derive num_books_last_month: (lag num_books 1)
the query could be simplified even further, because we can move sort earlier in the pipeline:
...
group [order_month, order_day] (
aggregate [
num_orders: s"COUNT(DISTINCT {co.order_id})"
num_books: count ol.book_id
total_price: sum ol.price
]
)
+sort order_day order:asc
group [order_month] (
- sort order_day order:asc
derive running_total_num_books: sum num_books
)
-sort order_day order:asc
derive num_books_last_month: lag num_books 1
Yes, simple queries will be a bit more verbose, but complex queries will be easier to write and understand. I think that outweighs the cons by a lot.
Footnotes
could be a window context just as group, but what about window functions within group? I think having select/derive params is cleaner. ↩
We could use designations like rolling or expanding
I agree. But I believe that rows / range is quite nice formulation of what is possible. I would convert that to PRQL, by indexing current row with 0, one before with -1, one after with 1 and so on.
rows:-3..0 -> "preceding 3 days, including current day"
rows:-3..-1 -> "preceding 3 days, excluding current day"
rows:-3..3 -> "preceding 3 days, current day and following 3 days" (equivalent to rolling:3?)
rows:..0 -> "expanding" (equivalent to expanding:true?)
I'm a huge fan of the proposed group function. If there's a way to do it on the whole table, then that approach absolutely should be how you do it for a group. It just twigged as well that you could (running with the above example) have custom functions within group, so I think the following should be valid...
func take_first x = sort x order:dec | take 1from employees
group title (
salary | take_first
)
So I think we get the benefit of increasing reusability, readability, and orthogonality in one go!
For syntax, I'm loath to use a syntax that bears any connotation of assignment. As I understand it, we aren't assigning anything. Rather, we are providing a key word that moves the "operate on the previous line's results" scope down a level - from the table to group and then back when closed. This feels much more like {} in rust and go to me. So I'll put forward...
from employees
- group title (+ group title {
sort salary order:desc
take 1
- )+ }
Commenting on the concerns about nested pipelines @aljazerzen and @max-sixty - my comment about scope above is why this doesn't bother me personally. I see this as not a nested pipeline, but a change in the level we operate at (ie down to group).
I'm not sure what the best way to handle window is though. The improvement for orthogonality (ie with derive and filter in a window clause) is strong to me. Or, at least I think it would be hypocritical to make it a motivating factor for group and not give it the same concern for window. I'll think on that a bit more...
I was quite reluctant to also introducing Window as a Pipeline™, because it can only contain derive or select. But seeing that that is not true because it can contain filter, I'm keen on the idea.
It is true, that with this you won't be able to scan first words of each line and know what's happening, but the same goes for group. And anyway, you can see derive a line below, in colored as a keyword.
In short, I would go with:
from employees
sort salary
window ..current {
derive cumulative_salary:[sum salary]}
What I'm not sure about is how to formulate the parameters (rows & range / rolling / expanding). See my comment above for a proposal.
How do we think about () now?
I like { } very much. It is used very similarly in C-style syntax, representing a code block that has conditional or repeated execution, which is on-point with what we are trying to express.
Arrays
Can't we just add a new transform to_array to the end of group by block? Would that be equivalent?
Transform functions
i.e.:
func take_first x = sort x order:dec | take 1from employees
group title (
salary | take_first
)
While that would make sense, we would have to revisit the definition of what our functions are able to do and quite a few changes to the parser... I'm guessing that's a 0.3 or 0.4 feature :D
I was quite reluctant to also introducing Window as a Pipeline™, because it can only contain derive or select.
I hadn't really synthesized this fact for myself. I am less keen on the idea than I was, after you said that! But I'm probably still marginally pro, partly for the same reason as you re QUALIFY.
I like { } very much. It is used very similarly in C-style syntax, representing a code block that has conditional or repeated execution, which is on-point with what we are trying to express.
I'm still a bit bearish on it.
I was hoping to avoid curly brackets, since I think many people associate them with a "real programming language" — I don't know any other field which uses them. And I was hoping to have PRQL be friendly — both for people like us, but also the 50x as many people who use Excel and would like to do more work with data1. While the "natural English" of SQL has arguably been a failure, its simple syntax does make it more approachable.
And also: do we need them? Isn't the existing approach with parentheses unambiguous? e.g. we already have:
table top_salary_by_title =(
from employees
group title (
sort salary order:desc
take 1))
Would that have { } rather than ( ) for the table definition?
I basically think of group taking a scalar/list for the groupby, and then a pipeline.
(TBC, as ever, I'm open to it)
While that would make sense, we would have to revisit the definition of what our functions are able to do and quite a few changes to the parser... I'm guessing that's a 0.3 or 0.4 feature :D
Agree, this would be great and theoretically possible, even if it's not that easy atm.
Can't we just add a new transform to_array to the end of group by block? Would that be equivalent?
Yes, you're right. I think it can be helpful to see the structural elements of the query in the outer definitions — I do think Malloy does this quite well; it's very easy to imagine the shape of the result by seeing the query. But on reflection there's maybe no need to have another transform.
Footnotes
Obviously adding curly brackets is not going to have a huge impact here! ↩
I realize this thread is getting very wide already, but to add something into the mix as we think through nested pipelines, I can imagine using nested pipelines to calculate a result and bring it back to the main pipeline, without needing functions & table. This currently impossible with SQL. For example:
from employees
derive [
us_salary:(
filter [country = 'US',type = 'full_time']
aggregate [average salary]),
uk_salary:(
filter [country = 'UK',type = 'full'] # type is encoded differently for UK employees apparently
aggregate [average salary]))select salary_diff: us_salary - uk_salary
Now, maybe this is taken account of by #82. And maybe it's a bad idea — I'm not proposing this as a great idea — rather another case to ensure as we think through the principles, we have as many cases as possible.
I believe this is equivalent to what you are trying to do:
from employees
filter (country = 'US' and type = 'full_time') or (country = 'UK' and type = 'full')group country [
aggregate [salary: average salary])pivot_wide country
select [salary_diff: salary_US - salary_UK]
(take 1) would be just a function call and not an inline pipeline.
(this will also happen if you put aggregate on the same line as group)
We can go this way, but then we have to parse transforms as normal functions that just take a dataframe and return a dataframe. In such scenario, we would resolve take to our internal function, realize that an argument is missing and return a function curry. So type of (take 1) would be Fn(Frame) -> Frame.
(just for reference, type of take would be Fn(u32, Frame) -> Frame)
This would be possible to make, it's a step-up on the ladder of functional languages, but it would take quite some time.
Other two options are:
require line breaks in pipelines,
replace ( ) for pipelines with { }
To be honest, I am really excited about the first option of "transforms are functions". It would also allow "Transform functions" that @rbpatt2019 suggested.
That's a great case, I agree. People will confused as to why removing the line-breaks suddenly breaks it — PRQL would be the only language I know of where this changes the semantics:
from employees
-group last_name (take 1)+group last_name (+ take 1+)
I wasn't really thinking that it would be practical to fit a whole pipeline on the same line there — but in some cases it is.
So I am fine to acquiesce on { } given I can't think of a better option. I still think it's a bit "programmy" — I worry that someone is going to see our "simplest example" and think "woah that's a lot of punctuation! I thought this was supposed to be simpler than SQL??". One nice thing about our old examples is that anyone who'd used SQL could pretty much look at the example and see what was happening; I'm not sure that's the case any longer1.
from employees
derive monthly_total_salary:(total_salary /12)group title {
aggregate [total_monthly_salary: sum monthly_total_salary]}
We can go this way, but then we have to parse transforms as normal functions that just take a dataframe and return a dataframe. In such scenario, we would resolve take to our internal function, realize that an argument is missing and return a function curry. So type of (take 1) would be Fn(Frame) -> Frame.
This would be possible to make, it's a step-up on the ladder of functional languages, but it would take quite some time.
Yes, I agree on both counts. Thanks for giving the detail on the types.
A couple of options I thought of, but don't think are great:
A pipe character to the pipeline:
from employees
-group last_name (take 1)+group last_name | (take 1)
...or inside the parentheses:
from employees
-group last_name (take 1)+group last_name ( | take 1)
Indentation 😱
from employees
-group last_name (take 1)+group last_name + (take 1)
Make group part of the syntax, so that group foo X (and window...) parses a pipeline in X. I don't think this is terrible; it could be a reasonable place until the full currying that @aljazerzen describes above could be implemented. But it's really pushing the limits of "context free"..., and it seems consensus is for the { }. I would probably vote for this option, but quite weakly, and without having really thought through the pain it would cause in the parser.
Either way, I don't think this is irreversible — we don't want churn, but a future release saying "now we can use ( ) would be OK.
Footnotes
But OTOH I do think that making the difficult queries much easier is more important than making the easy queries perfect. ↩
I think the { } is very reasonable. I wish it were a bit more approachable, but it it very coherent.
One option, which may stimulate both love and hate: indentation. It actually works quite well! But I understand that most programmers are at best ambivalent (though I think most python users rather like it?). Indentation is very information dense, but it hijacks the formatting as a source of information. It has the disadvantage that parsing is not technically context-free.
Here, the indented pipeline is mapped over the groups:
from employees
group title
sort salary
derive cumulative_salary:[sum salary]
Again, the take 1 pipeline is mapped over the groups, even if it looks a bit lonely with only one transform:
from employees
group last_name
take 1
And boss level, with QUALIFY1, where the pipelines are mapped over the groups and then again over the windows:
from employees
group title
sort salary
window ..current
derive cumulative_salary:(sum salary)
filter (cumulative_salary <>0)aggregate max_cumul_salary:(max cumulative_salary)
...clearly the elm formatting doesn't work so well here, though.
I would be happy to proceed with { } if that's the consensus choice.
from employees
filter (country = 'US' and type = 'full_time') or (country = 'UK' and type = 'full')group country (
aggregate [salary: average salary])pivot_wide country
select [salary_diff: salary_US - salary_UK]
What's the aggregate doing here? Is the below the same?
from employees
filter (country = 'US' and type = 'full_time') or (country = 'UK' and type = 'full')
group country [
- aggregate [salary: average salary]+ derive [salary: average salary]
)
pivot_wide country
select [salary_diff: salary_US - salary_UK]
Onto the discussion:
One option, which may stimulate both love and hate: indentation. It actually works quite well! But I understand that most programmers are at best ambivalent (though I think most python users rather like it?).
As a Python programmer, it's one of my biggest annoyances with the language. I've always found it a bit odd, and at times (in complex nested statements) a bit unintuitive that the formatting of the file impacts parsing. It certainly is the simplest option to read visually - I know initially, when I was a biologist looking to not be a biologist, it was exactly this lack of punctuation that helped attract me to python first instead of investing in a language like c/rust/go up front.
I'm actually a big fan of the parentheses. Feels consistent, a certainly moves towards a more functional style. Am I correct in understanding that the challenge is the amount of work required to parse the functions vs pipeline properly, given the existing context of parentheses? If so, why not group country( | take 1)? Make the bit inside the parentheses a pipeline, consistent with a current parser. Also, I think starting this way would make adapting to "transform functions" easier in the future. Once we add the capacity to parse functions in parentheses, the leading pipe simply ceases to be necessary. And existing code would continue to run (I think), while electing to use {} now would mean that any future changes to () would be breaking. Obviously, not an end all be all, but if we expect this feature to evolve over time, I'd lean towards a grammar that wouldn't be breaking if we change it.
I think the above has a limit in that it's not clear what exactly we are piping into take 1. In the short term, we could add a symbol to indicate that the groups are in the pipes (say maybe group country ( * | take 1) but I think that would likely be to much churn.
So TLDR: I think group country ( | take 1) is a good short term option. It get's the point across currently and (assuming we evolve towards the functional style proposed by @aljazerzen, we won't introduce a breaking change when group country (take 1) becomes valid.
But I like ( | take 1) much better! It unifies pipelines and inline-pipelines. It's a bit odd, but we can add a note in the reference that says:
You can put the nested pipeline in a single line, by using ( | take 1 ) instead of ( take 1 )
I think this is quite a good balance.
Even if this isn't one of those moments where we find the perfect synthesis that eliminates all the tradeoffs, this does seem very reasonable. And it's also fairly "close" to where we are now — it's a gradual change that we can adjust around as we learn more. I really appreciate the quality of the discussion, thank you @aljazerzen & @rbpatt2019
I like your diagram a lot @aljazerzen , and kudos on the colors :)
I very much agree with the aggregate one. What's the SQL for the select though? OVER (PARTITION BY a ROWS UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) (approx)? Should that require a window transform / map in PRQL?
Valiantly closed by @aljazerzen in #398. I'll open a new issue for implementing window functions — much of the compiler infrastructure is already set up in that PR though!
Activity
aljazerzen commentedon Apr 10, 2022
For anyone new to window functions (like I just was): good tutorial with illustrations
A nice observation that we could use in language design is that we have 3 types of functions:
FLOOR). They can be used in select and are applied to the whole column, on each value.SUMorMIN). They can be used in aggregate and reduce each partition to one value.RANKorLAG)/ They can be used as window functions in select and map column to column.The problem is that when writing code you don't think about that. Is it advantageous if we force users to think about it?
If we would go this way, we would introduce new transform, let's say
computefor lack of a better name:and with bounds and order:
Here I've used sort in two places, where the first affects only
computeand the second affects the output.Note that we would be the first languages I know to differentiate between select and compute in this way: dplyr, pandas and polars all have window functions within their selects.
max-sixty commentedon Apr 11, 2022
I definitely think there would be some benefits of structuring the language to consider types much more than SQL does — it could have a similar benefit to how your variable scoping now allows for knowing what's available to the language.
Ideally there's a synthesis where users don't need to think about it that much, but the compiler can still be helpful (not always possible :) )
Yes great. Notably some, like
AVGis both a reduction & vector function.This is related to #54, which deals with a case similar to the "scalar" and "multi-variate" / (aka "reduction") functions.
Re the
computecase, we do need some way to partition the values — see thebyterms above. It could be as a transform of a window pipeline (the 1st case), an arg to a window function (2nd case), an arg to the vector function (3rd case), or something else.Another option would be to make the partition primary, with something like a
byarg to amap(still need to think about this more):One invariant that I think is important to keep in PRQL is that each transform should leave a valid result. Something like
.group_byin pandas or dplyr doesn't do this (and in early discussion on PRQL, Hadley said this was one of his biggest regrets). So we shouldn't have:aljazerzen commentedon Apr 11, 2022
Oh, that true, nice catch.
If we go this way, compiler will be able to infer the cardinality of the rows in resulting frame: only one, many or many for a set of keys. So we could actually provide correct typing for cases like #54, which is a huge plus.
Partitions
To me, the most consistent way of specifying partitions in
compute/mapwould bebyparameter, same as aggregate. The same as in your example.For this approach the pro is that you can specify by only once, affecting many columns:
Sort
I wouldnt mix inline pipelines into transforms, it can get confusing why some things have to be in a new line and some don't. Instead I would also put
sortas a parameter to themap/compute:Or, even better, infer it from the current state of the pipeline:
This way, there is less parameters users have to remember, while still being intuitive.
The downside is that the SQL output would also contain ORDER BY, which could only be avoided with putting another
sort nullat the end.Naming
I don't like
computebecause it does not covey the "many to many" aspect of these functions.I don't like
mapbecause in MapReduce, it means "one value to one value".I don't like
shuffle, because it does not convey that we are adding a new column.I don't like
partition, because in a lot of cases, there will be only one partition.I don't like
window, because it does not make sense forrank,quantileand many other functions.Maybe something about fully-connected layer of a neural network? Something about vector functions? Something about new column for every row?
Fully agree.
max-sixty commentedon Apr 12, 2022
I strongly agree, this could be really good
max-sixty commentedon Apr 12, 2022
I've been trying to think about what the
OVER (PARTITION BY ...)s are doing conceptually. I started down a few paths, and came back to where I started, so there's no need to read the whole thing...A reduction function is quite simple; it just reduced each group to a single row:
A vector function with a partition / grouping creates a mini-table table for each group. In SQL, because there's generally no nesting (i.e. everything is a flat 2D table) the
byfield gets "unnested":An aside: in databases with nesting, the
OVER (PARTITION BY foo)function is equivalent to doing:ARRAY_AGG ... GROUP BY titleto get the arrays ofengineer -> [50,200], manager -> [120,130,150], etcbysotitlefills down (making the final result)So one option for this is:
groupormapornestto mean "build the groups", and it would take a quasi-pipeline to run over each group. A bit like thedplyr/spark/pandasAPI, but the function would be an argument to this rather than a subsequent transform (consistent with every transform leaving a correct result).computeto mean "apply this many-to-many function" (or another term, I know you say you don't like it, and I agree on the specific reason, though overall it seems decent relative to the other choices)So that would mean we'd have something like:
But if we do that, then we should be doing that for aggregates too:
I can see the elegance of that. I'm obv hesitant to make a big change to the language at this point, and I'd need to sit on it for a couple of days before having a view. My sense is that the current model of doing
aggregate by:title []rather than thangroup title (aggregate [...])is broadly equivalent and possibly easier to scan. The current approach is almost as orthogonal — we haveaggregatefor the reduction functions andcompute(or similar) for the vector functions, not some long list.aggregatewill also cover the case of making arrays.So that brings us back to where we started!
Naming
I'm not sure on the word. I agree
computeisn't ideal.calculateis basically the same.mapin theory is nice — it is literally a mapping — and it's not always one-to-one. But maybe it has too much baggage. Its synonyms, likemorphorfunctorare too weird.vecis too technical.Sort
I get that you're less keen on pipelines-in-pipelines. I agree it's some mental overhead in simple cases, and so we shouldn't require them. But it does introduce a nice orthogonality. Say we want to "compute the two best selling items with a price higher than $100". It would be very nice to have:
...for the case of the whole table, and:
...for the case of each group. Which supplying
sort:fooor having the sort outside thecomputedoesn't achieve.Indeed, note that in the current language, we have
...as a mini-pipeline.
BUT that said, I don't have a fully fleshed out proposal, and I'd be happy to go with the
sort:foofor the moment. I prefer that to havingsortoutside the pipeline, since that specifies too much work — sorting the whole table rather than within each group.aljazerzen commentedon Apr 12, 2022
The idea behind having sort in the outer pipeline instead of as a param, it that if you have two consecutive sorts, we can use only the last when translating to SQL. But if there is compute between the two sorts, it is affected by the first sort. This way, you reduce the number or params one has to remember. It can also think of the sorts as they have direct effect only the the conceptual model of current pipeline value, while only some of the sorts have to be translated into ORDER BY for SQL statement to produce the same result as the conceptual model.
(I hope that makes sense...)
About the
group: I really like it.As I've written here #9 we have common use-case where it would make sense for
taketo also havebyparameters, because in-effect you want to group by some fields and take only the top row ordered by some other column.So
aggregate,computeandtakeneedbyparameter and two of them also need sorting. Unifying them under agroupcontext seems an elegant solution.But I would propose a few changes to the syntax:
Group:
Group essentially introduces a new context where it is allowed to use
aggregate,select,derive,sortandtake. The normal context can use all transforms, butaggregatewill always reduce to a single number and usingsumin a select will produce aSELECT SUM(...) OVER ().Two things:
(pipeline)with braces{pipeline}. It would make it much easier to parse inline and frame pipelines.max-sixty commentedon Apr 13, 2022
Great, I'm thinking about this. It would be quite a change!
It does seem to be quite nice, in both conceptual elegance and readability. You're right that to really understand we should write some examples.1
Thanks for the examples, they're good. I agree with your points.
Much more narrowly:
I very much understood the point the
sortas the prior transformation — I just thought it was less coherent to have an integral part of the transformation outside of the main block. (it does fit with the pipeline notion though)Would this be so
(expression)is an parenthesized expression, but{pipeline}was required for all pipelines? We previously had that anything parenthized expression with line breaks was a pipeline (or more specifically any line break was a pipeline outside of a list or prior to a new statement liketable).Footnotes
Though I am most of the way through a big update to how the documentation works with examples, hopefully I'll get that out so we don't have conflicts... ↩
aljazerzen commentedon Apr 13, 2022
How does it look?
max-sixty commentedon Apr 13, 2022
Here's one pass:
groupif we're not grouping by anything — my vision of this change was that we could make PRQL even more orthogonal by having functions within agroupscope operate on groups exactly the same way that they would operate on a full table without thegroupscope. But that means that it doesn't make sense to have an empty group.group [order_month]transform? Presumably it's no longer possible to get the previous week's sales at that point. Forgive me if I'm missing something!Should we have a specific transform for "functions which use other values in the column" — the definition of window functions — or are they just functions? i.e. is this OK:
or do we need:
or:
Where do we define window attributes? On the function? On the
window(or whatever name we use?I'm less averse to the name
windowafter thinking about it — it is a window over the column. It's not a moving window in the case of rank / quantile, but it says "look at the whole column rather than just my row"We could use designations like
rollingorexpanding, which would make describing common windows simpler. It would bring us to a synthesis of a pandas / spark specification and a SQL spec.I definitely think that unifying
group byandpartition byinto a single orthogonal concept would solve one of the existing pain points of SQL window functions.Overall I think we're onto something but still need to pin down some of the details :). Your examples are v helpful in that regard.
max-sixty commentedon Apr 13, 2022
One concern about the
groupapproach is that it could make doing the simplest queries a bit more verbose. Say we just want to "select the sum of salary by country":SQL:
Existing PRQL:
Proposed PRQL:
But:
To focus on the orthogonality point, there is a nice orthogonality to both:
Proposed PRQL — aggregation over groups
Proposed PRQL — no groups:
Proposed PRQL — using groups as partitions:
aljazerzen commentedon Apr 13, 2022
Oh, yeah I made a mistake:
from co:cust_order join ol:order_line [order_id] derive [ order_month:f"{co.order_date:%Y-%m}", order_day:f"{co.order_date:%Y-%m-%d}", ] group [order_month, order_day] ( aggregate [ num_orders: s"COUNT(DISTINCT {co.order_id})" num_books: count ol.book_id total_price: sum ol.price ] ) group [order_month] ( sort order_day order:asc - select running_total_num_books: sum num_books + derive running_total_num_books: sum num_books ) sort order_day order:asc derive num_books_last_month: lag num_books 1aljazerzen commentedon Apr 13, 2022
I would change only your last example:
So rules would be as follows:
Now:
there is no need for
window,computeormapselect/derive/aggregateare completely orthogonal togroupthis is OK:
the query could be simplified even further, because we can move sort earlier in the pipeline:
... group [order_month, order_day] ( aggregate [ num_orders: s"COUNT(DISTINCT {co.order_id})" num_books: count ol.book_id total_price: sum ol.price ] ) +sort order_day order:asc group [order_month] ( - sort order_day order:asc derive running_total_num_books: sum num_books ) -sort order_day order:asc derive num_books_last_month: lag num_books 1Yes, simple queries will be a bit more verbose, but complex queries will be easier to write and understand. I think that outweighs the cons by a lot.
Footnotes
could be a window context just as group, but what about window functions within group? I think having select/derive params is cleaner. ↩
aljazerzen commentedon Apr 13, 2022
I agree. But I believe that rows / range is quite nice formulation of what is possible. I would convert that to PRQL, by indexing current row with 0, one before with -1, one after with 1 and so on.
rows:-3..0-> "preceding 3 days, including current day"rows:-3..-1-> "preceding 3 days, excluding current day"rows:-3..3-> "preceding 3 days, current day and following 3 days" (equivalent torolling:3?)rows:..0-> "expanding" (equivalent toexpanding:true?)8 remaining items
rbpatt2019 commentedon Apr 17, 2022
I'm a huge fan of the proposed
groupfunction. If there's a way to do it on the whole table, then that approach absolutely should be how you do it for a group. It just twigged as well that you could (running with the above example) have custom functions withingroup, so I think the following should be valid...So I think we get the benefit of increasing reusability, readability, and orthogonality in one go!
For syntax, I'm loath to use a syntax that bears any connotation of assignment. As I understand it, we aren't assigning anything. Rather, we are providing a key word that moves the "operate on the previous line's results" scope down a level - from the table to group and then back when closed. This feels much more like
{}in rust and go to me. So I'll put forward...Commenting on the concerns about nested pipelines @aljazerzen and @max-sixty - my comment about scope above is why this doesn't bother me personally. I see this as not a nested pipeline, but a change in the level we operate at (ie down to group).
I'm not sure what the best way to handle
windowis though. The improvement for orthogonality (ie withderiveandfilterin awindowclause) is strong to me. Or, at least I think it would be hypocritical to make it a motivating factor forgroupand not give it the same concern forwindow. I'll think on that a bit more...aljazerzen commentedon Apr 17, 2022
Windows
I was quite reluctant to also introducing Window as a Pipeline™, because it can only contain
deriveorselect. But seeing that that is not true because it can contain filter, I'm keen on the idea.It is true, that with this you won't be able to scan first words of each line and know what's happening, but the same goes for group. And anyway, you can see
derivea line below, in colored as a keyword.In short, I would go with:
What I'm not sure about is how to formulate the parameters (rows & range / rolling / expanding). See my comment above for a proposal.
How do we think about () now?
I like
{ }very much. It is used very similarly in C-style syntax, representing a code block that has conditional or repeated execution, which is on-point with what we are trying to express.Arrays
Can't we just add a new transform
to_arrayto the end of group by block? Would that be equivalent?Transform functions
i.e.:
While that would make sense, we would have to revisit the definition of what our functions are able to do and quite a few changes to the parser... I'm guessing that's a 0.3 or 0.4 feature :D
max-sixty commentedon Apr 18, 2022
I hadn't really synthesized this fact for myself. I am less keen on the idea than I was, after you said that! But I'm probably still marginally pro, partly for the same reason as you re
QUALIFY.I'm still a bit bearish on it.
I was hoping to avoid curly brackets, since I think many people associate them with a "real programming language" — I don't know any other field which uses them. And I was hoping to have PRQL be friendly — both for people like us, but also the 50x as many people who use Excel and would like to do more work with data1. While the "natural English" of SQL has arguably been a failure, its simple syntax does make it more approachable.
And also: do we need them? Isn't the existing approach with parentheses unambiguous? e.g. we already have:
Would that have
{ }rather than( )for the table definition?I basically think of
grouptaking a scalar/list for the groupby, and then a pipeline.(TBC, as ever, I'm open to it)
Agree, this would be great and theoretically possible, even if it's not that easy atm.
Yes, you're right. I think it can be helpful to see the structural elements of the query in the outer definitions — I do think Malloy does this quite well; it's very easy to imagine the shape of the result by seeing the query. But on reflection there's maybe no need to have another transform.
Footnotes
Obviously adding curly brackets is not going to have a huge impact here! ↩
max-sixty commentedon Apr 18, 2022
I realize this thread is getting very wide already, but to add something into the mix as we think through nested pipelines, I can imagine using nested pipelines to calculate a result and bring it back to the main pipeline, without needing functions &
table. This currently impossible with SQL. For example:Now, maybe this is taken account of by #82. And maybe it's a bad idea — I'm not proposing this as a great idea — rather another case to ensure as we think through the principles, we have as many cases as possible.
aljazerzen commentedon Apr 18, 2022
I believe this is equivalent to what you are trying to do:
where
pivot_wide countryconverts:to
... but that is a topic for another issue.
max-sixty commentedon Apr 18, 2022
(yes, if there's a pivot func!)
Also it's worth syncing on the current rules for interpreting
( ):pipe— a|character or a linebreak — it's treated like parentheses in any language — representing a single item whose contents have priority in precedence https://github.com/prql/prql/blob/df55b3bf7eae155492cfb3ca1d5e58e9712f52c5/prql-compiler/src/prql.pest#L76pipe, it's treated as an inline pipeline: https://github.com/prql/prql/blob/df55b3bf7eae155492cfb3ca1d5e58e9712f52c5/prql-compiler/src/prql.pest#L37This is a good example of the difference; my initial post was wrong, because it was a pipeline, whereas it should have just been an expr: #376
aljazerzen commentedon Apr 18, 2022
What about this case:
(take 1)would be just a function call and not an inline pipeline.(this will also happen if you put aggregate on the same line as group)
We can go this way, but then we have to parse transforms as normal functions that just take a dataframe and return a dataframe. In such scenario, we would resolve
taketo our internal function, realize that an argument is missing and return a function curry. So type of(take 1)would beFn(Frame) -> Frame.(just for reference, type of
takewould beFn(u32, Frame) -> Frame)This would be possible to make, it's a step-up on the ladder of functional languages, but it would take quite some time.
Other two options are:
( )for pipelines with{ }To be honest, I am really excited about the first option of "transforms are functions". It would also allow "Transform functions" that @rbpatt2019 suggested.
max-sixty commentedon Apr 19, 2022
That's a great case, I agree. People will confused as to why removing the line-breaks suddenly breaks it — PRQL would be the only language I know of where this changes the semantics:
I wasn't really thinking that it would be practical to fit a whole pipeline on the same line there — but in some cases it is.
So I am fine to acquiesce on
{ }given I can't think of a better option. I still think it's a bit "programmy" — I worry that someone is going to see our "simplest example" and think "woah that's a lot of punctuation! I thought this was supposed to be simpler than SQL??". One nice thing about our old examples is that anyone who'd used SQL could pretty much look at the example and see what was happening; I'm not sure that's the case any longer1.Yes, I agree on both counts. Thanks for giving the detail on the types.
A couple of options I thought of, but don't think are great:
A pipe character to the pipeline:
...or inside the parentheses:
Indentation 😱
Make
grouppart of the syntax, so thatgroup foo X(andwindow...) parses a pipeline inX. I don't think this is terrible; it could be a reasonable place until the full currying that @aljazerzen describes above could be implemented. But it's really pushing the limits of "context free"..., and it seems consensus is for the{ }. I would probably vote for this option, but quite weakly, and without having really thought through the pain it would cause in the parser.Either way, I don't think this is irreversible — we don't want churn, but a future release saying "now we can use
( )would be OK.Footnotes
But OTOH I do think that making the difficult queries much easier is more important than making the easy queries perfect. ↩
max-sixty commentedon Apr 19, 2022
I've been thinking about this a lot!
I think the
{ }is very reasonable. I wish it were a bit more approachable, but it it very coherent.One option, which may stimulate both love and hate: indentation. It actually works quite well! But I understand that most programmers are at best ambivalent (though I think most python users rather like it?). Indentation is very information dense, but it hijacks the formatting as a source of information. It has the disadvantage that parsing is not technically context-free.
Here, the indented pipeline is mapped over the groups:
Again, the
take 1pipeline is mapped over the groups, even if it looks a bit lonely with only one transform:And boss level, with
QUALIFY1, where the pipelines are mapped over the groups and then again over the windows:...clearly the
elmformatting doesn't work so well here, though.I would be happy to proceed with
{ }if that's the consensus choice.Footnotes
Good qualify examples here FYI (which I actually think we should be using more, I should refresh the examples I'm using to think through these): https://docs.snowflake.com/en/sql-reference/constructs/qualify.html ↩
rbpatt2019 commentedon Apr 19, 2022
Question about this query...
What's the aggregate doing here? Is the below the same?
Onto the discussion:
As a Python programmer, it's one of my biggest annoyances with the language. I've always found it a bit odd, and at times (in complex nested statements) a bit unintuitive that the formatting of the file impacts parsing. It certainly is the simplest option to read visually - I know initially, when I was a biologist looking to not be a biologist, it was exactly this lack of punctuation that helped attract me to python first instead of investing in a language like c/rust/go up front.
I'm actually a big fan of the parentheses. Feels consistent, a certainly moves towards a more functional style. Am I correct in understanding that the challenge is the amount of work required to parse the functions vs pipeline properly, given the existing context of parentheses? If so, why not
group country( | take 1)? Make the bit inside the parentheses a pipeline, consistent with a current parser. Also, I think starting this way would make adapting to "transform functions" easier in the future. Once we add the capacity to parse functions in parentheses, the leading pipe simply ceases to be necessary. And existing code would continue to run (I think), while electing to use{}now would mean that any future changes to()would be breaking. Obviously, not an end all be all, but if we expect this feature to evolve over time, I'd lean towards a grammar that wouldn't be breaking if we change it.I think the above has a limit in that it's not clear what exactly we are piping into take 1. In the short term, we could add a symbol to indicate that the groups are in the pipes (say maybe
group country ( * | take 1)but I think that would likely be to much churn.So TLDR: I think
group country ( | take 1)is a good short term option. It get's the point across currently and (assuming we evolve towards the functional style proposed by @aljazerzen, we won't introduce a breaking change whengroup country (take 1)becomes valid.aljazerzen commentedon Apr 19, 2022
No they are not the same. Derive in a group is a window function, which does not affect number or rows.
I did a cheatsheet-style illustration we can use in the docs:
We could go with
{ }now and when currying is implemented just allow to use()as well, which would not be breaking.But I like
( | take 1)much better! It unifies pipelines and inline-pipelines. It's a bit odd, but we can add a note in the reference that says:Or just instruct that they always use
( | ... )for pipelines.The
*already has a use, so instead I would just present(|as the opening parenthesis of the pipeline. Is this reasonable?max-sixty commentedon Apr 19, 2022
I think this is quite a good balance.
Even if this isn't one of those moments where we find the perfect synthesis that eliminates all the tradeoffs, this does seem very reasonable. And it's also fairly "close" to where we are now — it's a gradual change that we can adjust around as we learn more. I really appreciate the quality of the discussion, thank you @aljazerzen & @rbpatt2019
max-sixty commentedon Apr 19, 2022
I like your diagram a lot @aljazerzen , and kudos on the colors :)
I very much agree with the
aggregateone. What's the SQL for theselectthough?OVER (PARTITION BY a ROWS UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)(approx)? Should that require awindowtransform / map in PRQL?max-sixty commentedon Apr 25, 2022
Valiantly closed by @aljazerzen in #398. I'll open a new issue for implementing window functions — much of the compiler infrastructure is already set up in that PR though!