Hacker News new | ask | show | jobs
by Skeime 20 days ago
It is the language's fault, because SQL offers no good way to get nested results. If you want to avoid the duplication, you can do multiple queries, but then you essentially have to do the join on the receiving end, which kind of defeats the purpose of having joins in SQL.

Alternatively, you might use functions to aggregate in the query, but they're not standard, as far I know, which means that interfaces in programming languages often do not support them. The best bet might be aggregating into JSON, but this removes quite a bit of the type information that values in SQL usually carry. (Also, the aggregation functions are generally less pleasant to write than standard joins.)

3 comments

Couldn't agree more, and I think Postgres and others should be prioritizing support for MULTISET (exactly what you're describing and part of the SQL standard, and yet supported by almost no one).

JSON agg is what Gel does internally, and engines like Reylo[0] can do type inference so you get some type safety in your language of choice. Still quite lossy, as you say.

[0] https://github.com/colinhacks/reylo

> because SQL offers no good way to get nested results

Because you don't need nested results. You can fire off another query.

Although I am venturing to guess that you feel you need nested queries because you're doing doing something stupid like trying to send SQL queries over the network where the cost of firing off another query becomes a great performance burden. But the answer to that is don't do that. SQL was specifically designed to be run on the same machine as your application.

If you need to present the data to network clients where nesting is necessary for performance reasons, turn your application into the network database service that produces nested data (the "API server" as the kids call it). Leave the SQL as an implementation detail hidden behind the scenes.

I do want to be presented with nested results in the end, though!

As I mentioned in the previous post, I am aware that this can be done with multiple queries and post-processing, but then I am implementing what essentially amounts to a join myself (of maybe I have something like an ORM do it for me). In any case, my data processing is now split up in two places.

And the point of Ultorg is that it provides an interface that does this post-processing into a nested representation. Except maybe for Gel (mentioned somewhere else here), I have not seen this in any other general interface for relational databases. If SQL supported nested results, this surely would be different.

> my data processing is now split up in two places.

It is a higher level concern so that isn't a bad thing. SQL is focused on giving you a view of your data. Whereas you want to combine many different views. That is where composing many different queries should be seen as quite natural at the interface point, not a shortcoming of SQL. If that composition isn't natural, you may want to take a closer look at your application's architecture.

> but then I am implementing what essentially amounts to a join myself

Joins and aggregated views are very different concepts. I think this misunderstanding, which is one I've seen many times before, stems from the hacks used to work around the aforementioned problems. Many have come to believe those hacks actually how SQL is designed to be used, not the hacks that they are.

> I have not seen this in any other general interface for relational databases.

Oracle has their thing. Its name escapes me at the moment. Postgres has json_agg/jsonb_agg and similarly SQL itself has array_agg. Lots of options out there.

But it's not only a question of if it can be done, but if it should be done. There are a lot of other advantages to moving query aggregation out into another application. There is a reason why we stopped sticking SQL servers directly in front of the clients and it isn't just because of SQL using a table representation.

I think we will just end up disagreeing here. If I want to get out a presentation combining data from two tables in a one-to-many relationship, potentially filtered by fields in both tables, I see no really convincing option. To be explicit, I'll use "Give me a list of all my customers in Oregon who have made a purchase within the last year together with those purchases" as an example.

I can write a single join in SQL to get this, but then the customer information will be repeated on each purchase line. For my report I will also need to group orders from the same customer together. So now I have asked my database to duplicate the customer information across rows, only to deduplicate the data in my application again.

I can create two SQL queries, one for the customers, one for the purchases. I will still need to use joins (or WHERE-EXISTS clauses), because I do not want to extract all my customers and/or purchases from the database. Then, in the application I need to combine the results of those two queries. This will require me to implement the same join (or at least, its matching logic) yet again.

Neither of these really seem all that great to me. Of course, one can work around these limitations, many database adapters do. But in my opinion, this does not mean that SQL should not have provided a native solution for this. (There are tons of other things it could have left out as well, by that logic.)

The agg functions are probably the closest thing we have. I have mentioned my gripe with the JSON versions before, they lose valuable type information due to JSON's limited data model. The array_agg version is usually not very ergonomic on the receiving end. Both are also more cumbersome to write in SQL than I would like.

For what it's worth, I also think that SQL teaching generally emphasizes joins as the natural way to work with relational databases way to much. The agg functions might appear almost as an afterthought at the very end. (To be fair to the creators of teaching materials, to me, they also appear as an afterthought in SQL itself.)

> To be explicit, I'll use "Give me a list of all my customers in Oregon who have made a purchase within the last year together with those purchases" as an example.

Yes, this maps quite nicely to SQL. Consider this pseudocode[1]:

    for customer in (select distinct c.customer_id, c.name from customers c natural join purchases p natural join addresses a where p.purchased_at >= last_year and a.city = 'Oregon') {
        println(customer.name)
        for purchase in (select date, amount from purchases where customer_id = customer.customer_id and purchased_at >= last_year) {
            println("\t"+purchase.date+": "+purchase.amount)
        }
        println()
    }
I know, you're already recoiling in horror. But that's because you've grown accustomed to having to deal with shitty implementations of SQL. It is recognized that you cannot actually write code like that under those shitty implementations because your program will quickly grind to a halt as soon as you gain a few customers, but the point here is to stop using shitty SQL implementations and embrace SQL as it as it was actually intended to be used.

> But in my opinion, this does not mean that SQL should not have provided a native solution for this.

SQL does provide a native solution. But it seems your argument is, perhaps, that it should formally define a way to hack around shitty implementations? Why not use the right tool for the job instead?

> I also think that SQL teaching generally emphasizes joins as the natural way to work with relational databases way to much.

Agreed, and I am suggesting that is because of the hacks required to work around the reasons why you cannot write the above code under shitty implementations, which has lead to many to conflate joins and view aggregation.

If you want something like the above except using a declarative language instead then you can put something like GraphQL in front of it. What are you really gaining by turning SQL into GraphQL? SQL is not intended for graph databases. It is a different tool for a different job.

[1] The need for distinct here is SQL's actual flaw. If it were truly relational like it likes to pretend to claim to be that would be unnecessary. It brought the relational calculus but not the relational algebra, which leaves a funny impedance mismatch. You can deal with that in the small scale well enough, but as queries become complex they become hard to reason about because they don't behave like the expression suggests. Which serves as a good corollary as to why turning SQL into GraphQL is unwise when it doesn't have a graph foundation. Primitives best match the primitives. You can layer the abstractions on top, where you can take responsibility for the leaks, as your specific needs dictate.

Yeah, ARRAY_AGG being an optional part of the standard is annoying, and in general the array handling functions have been very non-standardized and messy - it's getting better though!
Window functions such as PARTITION BY can accomplish nested results, with headers.. Etc.