Skip to content

Orthogonal treatment of groups (nee Window functions) #300

Closed

Description

@max-sixty

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.

Here are some example queries we can use as cases: https://cloud.google.com/bigquery/docs/reference/standard-sql/analytic-function-concepts#get_the_most_popular_item_in_each_category

Activity

  1. added
    language-design
    on Apr 2, 2022
  2. aljazerzen commented on Apr 10, 2022

    @aljazerzen
    Member

    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:

    • 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.

  3. max-sixty commented on Apr 11, 2022

    @max-sixty
    MemberAuthor

    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
  4. aljazerzen commented on Apr 11, 2022

    @aljazerzen
    Member

    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

    Fully agree.

  5. max-sixty commented on Apr 12, 2022

    @max-sixty
    MemberAuthor

    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 strongly agree, this could be really good

  6. max-sixty commented on Apr 12, 2022

    @max-sixty
    MemberAuthor

    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:

    image

    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":

    image


    An aside: in databases with nesting, the OVER (PARTITION BY foo) function is equivalent to doing:

    1. ARRAY_AGG ... GROUP BY title to get the arrays of engineer -> [50,200], manager -> [120,130,150], etc
    2. Run the vector function over each group (making the middle result)
    3. 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.

  7. aljazerzen commented on Apr 12, 2022

    @aljazerzen
    Member

    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.
  8. max-sixty commented on Apr 13, 2022

    @max-sixty
    MemberAuthor

    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

    1. 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... ↩

  9. aljazerzen commented on Apr 13, 2022

    @aljazerzen
    Member
    # https://www.databasestar.com/complex-sql-query-example
    # https://www.databasestar.com/sample-bookstore-database/
    
    from co:cust_order
    join ol:order_line [co.order_id = ol.order_id]
    derive [
      order_month:s"DATE_FORMAT({co.order_date}, '%Y-%m')",
      order_day:s"DATE_FORMAT({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

    How does it look?

  10. max-sixty commented on Apr 13, 2022

    @max-sixty
    MemberAuthor

    Here's one pass:

    • 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.

  11. max-sixty commented on Apr 13, 2022

    @max-sixty
    MemberAuthor

    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 `GROUP BY` & `PARTITION BY`, similar to how we consolidate `WHERE` and `HAVING`
      window [sum salary]
    )
  12. aljazerzen commented on Apr 13, 2022

    @aljazerzen
    Member

    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 1
  13. aljazerzen commented on Apr 13, 2022

    @aljazerzen
    Member

    I would change only your last example:

    from employees
    group title (        # No need for `GROUP BY` & `PARTITION BY`, 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

    1. could be a window context just as group, but what about window functions within group? I think having select/derive params is cleaner. ↩

  14. aljazerzen commented on Apr 13, 2022

    @aljazerzen
    Member

    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?)
  15. 8 remaining items

  16. rbpatt2019 commented on Apr 17, 2022

    @rbpatt2019
    Contributor

    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 1
    
    from 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...

  17. aljazerzen commented on Apr 17, 2022

    @aljazerzen
    Member

    Windows

    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 1
    
    from 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

  18. max-sixty commented on Apr 18, 2022

    @max-sixty
    MemberAuthor

    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

    1. Obviously adding curly brackets is not going to have a huge impact here! ↩

  19. max-sixty commented on Apr 18, 2022

    @max-sixty
    MemberAuthor

    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.

  20. aljazerzen commented on Apr 18, 2022

    @aljazerzen
    Member

    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]

    where pivot_wide country converts:

    country | salary
    --------|-------
         US |      A
         UK |      B
    

    to

    salary_US | salary_UK
    ----------|----------
            A |         B
    

    ... but that is a topic for another issue.

  21. max-sixty commented on Apr 18, 2022

    @max-sixty
    MemberAuthor

    (yes, if there's a pivot func!)


    Also it's worth syncing on the current rules for interpreting ( ):

    This 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

  22. aljazerzen commented on Apr 18, 2022

    @aljazerzen
    Member

    What about this case:

    from employees
    group last_name (take 1)

    (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.

  23. max-sixty commented on Apr 19, 2022

    @max-sixty
    MemberAuthor

    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

    1. But OTOH I do think that making the difficult queries much easier is more important than making the easy queries perfect. ↩

  24. max-sixty commented on Apr 19, 2022

    @max-sixty
    MemberAuthor

    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:

    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.

    Footnotes

    1. 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 ↩

  25. rbpatt2019 commented on Apr 19, 2022

    @rbpatt2019
    Contributor

    Question about this query...

    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.

  26. aljazerzen commented on Apr 19, 2022

    @aljazerzen
    Member

    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:

    image


    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:

    You can put the nested pipeline in a single line, by using ( | take 1 ) instead of ( take 1 )

    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?

  27. max-sixty commented on Apr 19, 2022

    @max-sixty
    MemberAuthor

    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

  28. max-sixty commented on Apr 19, 2022

    @max-sixty
    MemberAuthor

    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?

  29. max-sixty commented on Apr 25, 2022

    @max-sixty
    MemberAuthor

    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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementlanguage-design

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions