Things I want in a modern relational query language
sporks.space
sporks.space
https://www.scattered-thoughts.net/writing/against-sql
That particular post ends with a wish-list of items so it's the most similar to the OP. But there are others on the site that I quite enjoy (click on the home icon and search "SQL" on the page).
My personal take is that SQL will continue to reign for a long time because of the how monumental the task of replacing it is due to the inherent complexity of databases. LLMs make this worse because they're really good at translating prose to SQL. Now that it matters less how annoying SQL is to programmers, SQL will become more like assembly over time: something mostly computers write because it's complicated for humans to deal with directly. This is deeply ironic given that SQL was ostensibly designed to read like prose, i.e. to be easy for humans.
Most people reach out towards an ORM or query building engine and otherwise don't really go far beyond the basic CRUD, joins, and some simple aggregations with groups. Since they try to be DB agnostic you'll rarely get an adaptor over CTEs or window functions or partitioning.
An LLM is great at exposing what a database is capable of doing with SQL and might even manage to navigate the most poorly designed of schemas. And it might even manage to design one to an acceptable standard if it has enough domain knowledge in its context.
Personally I think we need ORMs that allow expressing advanced SQL stuff with other high level languages. Or even better: The ORM detects where advanced SQL makes sense and uses it.
I haven't worked in a single setup where raw SQL has been encouraged, because it always requires DB migrations and not all of them are safe. Nobody dares touch the DB server's resources by setting up stored procedures, materialised views, etc. etc. and instead people are blowing money on Redis instances and caching and shit.
I don't have an answer to this but I've hit a lot of issues in my career where I think, "this could have been solved months ago by pivoting a couple of tables or creating a new function." You have been able to 'script' the DB for decades but you lose a lot of what you gain from the traditional SDLC at the app layer.
Passing raw SQL to the database needs very careful attention to the dynamic parts, and it's too easy for user-generated data to be included.
Yes, it's possible to pass user generated text through a sanitizer but now you just have an arms race between the sanitizer and "clever" users.
I’ve never had an issue of raw SQL requiring migrations? Unless you’re talking of changing database engine? In which case I think it’s a bit of folly to imagine changing the database engine will not mean changes to your stack higher up the chain.
Isn't that true of most languages? SQL has pretty simple syntax; I think the only reason it's sometimes seen as arcane is that fewer and fewer people bother to learn it.
1. SQL isn't composable (you can't assign fragments to variables except for CTEs) so you can't easily test out subparts and build them up incrementally without just copy/pasting stuff around.
2. Joins are an unnatural way to dereference pointers.
3. SQL is more than SELECT. Once you get into updates you encounter lots of scary edge cases and traps. How many engineers really understand isolation levels? Why doesn't skipping the column list in an INSERT substitute nulls for the nullable columns that aren't provided? What changes can you make to a schema that are 'safe' for your environment (won't take table locks)? What locks are being taken by the RDBMS behind your back - sometimes it matters!
4. Site outages caused by optimizer plan shifts are scary because people don't feel in control.
Good databases have features to ameliorate these issues, but most people's experience is of databases that are merely OK and not good.
there's a bit of cyclic relationship at play here, the data changes the query plan, and the query plan affects the performance, while the performance is being optimised by the engine. if the architecture is bad then sooner or later the engine runs out of tricks and performance suffers but then nobody never is quite sure whether the current architecture's good enough.
I totally get the whole nosql that was the rage for a while... quick to prototype but I do believe once it's somewhat settled, moving the consolidated parts back to SQL is much easier to manage and optimise
There's gotta be a simple & clear alternative to this obstruction. Maybe it just hasn't been invented yet.
I feel like there’s no excuse for this one. You need to know how your data store will interact with your query and others.
The problem, I think, is what the tail end of that is, and is what you hinted at when discussing locks: RDBMS interaction. I have come around on this recently (quite recently - after reading and re-reading this article, and the comments), so forgive me if any past comments in my history indicate otherwise.
It is unreasonable to expect a developer to administer an RDBMS. If you're a small startup, you kind of have to out of necessity; maybe if you're lucky, you hire a dev who's also done infra work, and if the stars align, they've specifically administered an RDBMS at scale. But what counts as administration? Let's look at adding a secondary index, possibly the most common DDL.
AFAIK, no ORMs / frameworks (I am assuming here that most devs are using some kind of abstraction for RDBMS access) default to "safe" builds - no `CONCURRENTLY` for Postgres, and no reducing `lock_wait_timeout` to something sane for MySQL (I've no idea about MSSQL nor Oracle, though I also assume that if you're running one of those, you probably have a DB team). So already, there is an implicit assumption that they've read the pertinent manual section[s] for their RDBMS, which seems unlikely. Even if they did, there's a chance they would also need to have read and understood the paragraphs on handling invalid index builds (Postgres), or the impact that foreign key constraints can have on metadata locks (MySQL).
Let's say the line gets drawn at "devs should be able to understand that they [probably] need secondary indices," with implementing those being entirely on another team or service. OK - how much do they need to understand? I think it's reasonable to expect a developer to understand B+trees; after all, they're just a data structure. Should they need to be able to internalize that such that they can understand why doing a range scan on a column in the middle of a multi-column index removes everything to the right of it from B+tree filtering? Probably, but now we're significantly deeper into specifics. Should they know that there are different kinds of indices, like GIN? Maybe. What about different operator classes (Postgres) for them? Maybe, maybe not. What about knowing about its `fastupdate` option, and the related `gin_pending_list_limit` configuration item? I'd love to say no, those are squarely in the world of ops, but then why should they be allowed to create the index at all if it's going to increase someone else's operational burden?
For all these reasons, I don't think it's prudent to have dev teams managing their own DBs. But then, you get into the fight that most places seem to be in, where the devs want to do something to the DB that the ops team knows will be a headache later, they push back, product gets mad that they aren't shipping, ops capitulates, and then the headache predictably becomes real months down the road. Rinse and repeat.
I have no clue how to fix this while maintaining the modern trend of velocity dominating everything else.
This is kind of a hot take. Most devs I know know PostGreSQL well. They know how to write complex queries with CTAS, joins, etc, know how to create indexes, views, and add user defined functions.
> My biggest complaint about System R is that the team never stopped to clean up SQL. [...] All the annoying features of the language have endured to this day. SQL will be the COBOL of 2020, a language we are stuck with that everybody will complain about.
> My second biggest complaint is that System R used a subroutine call interface (now ODBC) to couple a client application to the DBMS. I consider ODBC among the worst interfaces on the planet. To issue a single query, one has to open a data base, open a cursor, bind it to a query and then issue individual fetches for data records. It takes a page of fairly inscrutable code just to run one query. [...] Only recently with the advent of Linq and Ruby on Rails are we seeing a resurgence of cleaner language-specific enbeddings (sic).
Ten years ago I was at a startup where we used Datomic, and it was okay, but six months in the sales team was like “ok how do I run SQL queries so I can triage leads”. We had no answer of course.
Today it would simply be: type what you want in natural language and we’ll generate the query with Claude.
I just tried one representative query from that startup against a hypothetical datalog query tool in Rust and it did just fine.
Within a couple of weeks we have totally non-technical folks with very sophisticated queries in their dashboards. It works fine.
It was very cut-and-paste, though, and I'm working (when I get the chance) on doing this via a chat interface where the LLM can interact directly with the database and Grafana to make it smoother.
So I think the answer is not necessarily new languages, just better integration with the final interface. In an ideal world we should be able to ask in chat "what were the sales numbers for last quarter for APAC excluding the three largest customers?" and get an answer near-instantly, and then we don't really need to deal with queries or languages at all.
I have an implicit belief that SQL isn't the most effective low level language we could have and LLMs will free us up to explore that space, similar to asm.js -> WASM. But I'm open to being wrong about that.
The implementations are not high performance, but if you can fit everything in memory or you can organize your data and integrate it through external queries, you should get something workable for a lot of use cases.
I did not set out to replace SQL, and while I don't mind adoption, that is not why I am sharing it here. The open sourcing was motivated by making datalog more widely known. I did some research and found out that I needed a datalog implementation with particular characteristics, I for sure knew I didn't want to use SQL for what I needed.
There are structured types and recursion and being able to name predicates and compose queries... Mangle has some users and there is a few application that take advantage of the queries-as-logic-programming approach.
I think an insight one can draw in this discussion that a query language and the system (DBMS implementation) that it is part of can hardly be separated when it comes to the inevitable performance requirements one has.
I’ve been getting into Postgres recently and I was very surprised how easy it is to introduce new types/operators/etc through C code. I’m not talking about domains. Just write some C and you can have whatever type you want. It really demystified “extensions” for me, I actually think that is an actively harmful name (it sounds clunky, gross, based on my experience dealing with “extension” and “plugins” elsewhere) for what is essentially just custom types/functions. More people should try writing their own postgres extensions. It’s not very difficult at all!
I’ve been cooking in this space for quite a while (HDFS/spark, Apache Pinot, proprietary stuff, an experimental functional ORM over SQLite). The biggest problem, I think, is the interface between the management/admin, application, and “query” layers. I think something like grpc/protoc (or indeed the way Spark used the JVM) is needed to provide non-leaky abstractions and more programmatic/structured interfaces from the DB to its clients. Happy to share more, but basically, the database needs to become capable of general (meta-)parsing with a reflective type system, I think.
Wouldn't it be a lot more efficient to just work that way in the first place?
[1] http://livesql.org/ <--- just a few paragraphs of text from 2011
https://docs.oracle.com/en/database/oracle/oracle-database/2...
You can get callbacks from the driver as query results change, or have notifications be sent to stored procedures, or posted to a message queue (and from there turned into web hooks etc). The notification comes with info about the deltas.
The main issue with it is that the queries it can monitor live are a subset of all queries. It's really more like using SQL to select database cells to watch, than propagating changes through arbitrary query plans. For example, it can't handle a SELECT COUNT(*) FROM statement. Obviously you can use it as a trigger for re-running more advanced queries though.
There are some new interesting players in the field though, eg. https://github.com/feldera/feldera
SQL server has Query Notification.
You can also read from debezium or other cdc, but thats more like table change than query result change.
And many databases have triggers. And with postgres you can combine triggers with NOTIFY to push changes downstream.
But yeah, I feel like most databases are way behind Oracle on this feature and it's so so useful.
but yes, I agree this is quite often what one wants, and would remove a lot of grot from the client
I've been working on a Lean4-based query lang that compiles to substrait, I think the power it has wrt to types and functional programming could improve on SQL ergonomics a good deal
The good thing about having built your own programming language via LLM nowadays is that you don't really have to speculate about a theoretical language when you can just have Codex/Claude implement it and try it out for yourself. I did it yesterday when I wanted to try out this theoretical high-performance database architecture that I had in mind and just added query functionalities to the language I already have.
If anyone is interested about the results, the default naive mode for this new database is ~0.2x the speed of concurrent durable mutation workloads, but if you specialize it to the particular application, you can get ridiculous 50-100x performance increases on filters and maps at the cost of flexibility and more upfront design. Experimental results are promising, definitely not production ready though.
It was only a partial implementation of the relational model, we could have been so much better had it not become the standard
Ask yourself this question, supposedly somebody made the full implementation of the relationship model into a database engine tomorrow, will you use it yourself, and can you convince your company to use it in place of SQL? Again, I wish this wasn't the case, but I'm not sure if there is anything we can do about the adoption problem.
Previously, I've seen it described (including on Wikipedia) that you were hired to embed Scheme, but then they made you change it right before delivery.
Crying about some theoretical relational model doesn’t do anything to further your point.
Old man rant off.
I can trivially handle having to repeatedly bounce to the top-then-to-the-bottom of a query I am writing because I want to change the group-by or sorting order, but that is annoying friction. Since the language does not compose well, you need to keep most of the query in your head and cannot build it up piecemeal as easily as something like PRQL (https://prql-lang.org/)
[0] Although, it would be incredible if I could write timestamp formatting without having to look up the bespoke vendor incantation every time I switch dialects.
I think the “it’s just syntax bro, learn it!” critique is about as ill-fitting as the claim that embedding a scripting language in a larger program is pointless because “assembly/C89 is just syntax bro, learn it!”
It’s literally so damn simple to knock out a database & some crud functions either as a desktop app or a website that the complaints in this thread are hilarious.
The link in the top comment further expands on the cognitive overhead: https://www.scattered-thoughts.net/writing/against-sql
Particularly relevant is the part of that link which discusses having to pervasively refactor queries to add even a simple synthetic join or computed column. That’s a pain in the ass even for experienced DBAs, and is fundamentally not time well spent for row-at-a-time cases that are often, as you said, simple CRUD.
Are you sure you aren’t overfitting based on working on only one small, simple subset of the things people commonly use SQL for?
At least in SQL Server select x2 from foo group by x+1 as x2 you'd use select x+1 as x2 from foo group by x.
I've read your article and it's written well enough, I'm just not sure that's as big a hit piece as you think it is nor do I think here is the place to post a full rebuttal.
>Are you sure you aren’t overfitting based on working on only one small, simple subset of the things people commonly use SQL for?
I think on the contrary that esoteric features not used as commonly utilised deserve to be esoteric to use. The common path should be the easiest. That SQL is used by different professions and not just IT related ones is testament to a good language. You won't find BA's using C to write reports for instance. There's A LOT of value in that.
So, until the ultimate query language is developed, I'll take SQL with pipes. It's an easy sell and good enough to eliminate 90% of my gripes about SQL.
[0] https://courses.cs.duke.edu/spring03/cps216/papers/date-1983...
They might love the relational model concepts that manage to seep through it
I like to say, with zero research basis, that the New Shiny has to be an order of magnitude better than the Old Thing for people to say "Oh yeah, I gotta have that."
First paragraph of preface: “SQL has been the default language of application databases for half a century. That default is now holding application state back. Datalevin is a database built to replace SQL databases at the center of application systems: it stores data as small facts and queries those facts with Datalog”
We don't need a new syntax. SQL, PRQL or whatever else should compile down to the database's machine readable interface, same as language-integrated query builders or libraries like your generated clients.
Did you come across Substrait when working on this? Any thoughts?
This also sounds like what Turso imagine doing with their VDBE:
> Like SQLite, it compiles SQL into bytecode for that machine, the VDBE, and then runs the bytecode. That design is what lets one engine host more than one SQL dialect. SQLite is the first and primary frontend that compiles to it, and Postgres is now a frontend of its own, with its own dialect and wire protocol. More will follow. Our goal is to be for databases what LLVM is to compilers, with one modern and reliable core, and many frontends compiled down onto it.
For error handling I mean things like deprecating a column and allowing a custom error message when someone queries it.
And for schema updates I mean allowing table versions. Same table name but allowing querying an older version of the schema
Since it seems like the quantity of training data dominates AI performance, and AI doesn't yet internalize experience with new tools, it seems like a bad idea to stray from the training set.
Without repeatable benchmarks, it feels like obsessing over a language's syntax and semantics feels a little like debating whether you write assembly using AT&T or Intel syntax.
In my experience it's rather people who have the most trouble with new languages, as the difference between the PL frontier and languages that most people use is quite extreme.
Conversely, AI is adept at staking out a point in the PL design space and developing a grammar and vocabulary around it. Then it writes a parser and interpreter to execute whatever semantics, writes a standard library to support writing programs, and finally writes the compiler in itself.
Because it's so good at doing this you can do a lot of exploration whereas before it would take years now it takes months.
The second area I'm working on now doesn't have a readily available notation, which is state machines. Here, the AI can concoct a very terse state machine representation and write very complex state machines that can be statically analyzed so it has a better time than writing in a plain language without that capability. Now I'm trying to test how it fares against other state machine DSLs.
The next area I will move to after this I think is music, which also has a readily available notation that AI can operationalize. No numbers to report yet but I'll publish my research when it's done.
I once worked on a medical records system (with a pretty well designed but necessarily complex schema) where the primary “patient” data object used by most code was fetched by a query that, depending on what associated data you needed, had between 106 and more than 400 relations (across dozens to hundreds of tables) joined together.
And that was CRUDy data-path code. The OLAP/reporting side added zeros to those numbers. Query texts were often hundreds of kilobytes.
I feel like databases effectively (/literally) add a JIT, which can mostly figure out what to do, even has accurate heuristics on the distribution of the data, but in exchange you get a less deterministic system, and less intuition for how to query or structure things. It's like, you know when to use a list/map/queue, but you want to focus on the business logic, so just use a smart collections which guess at runtime.
I think you can get this with FoundationDB, I should experiment rather than hypothesizing, but it feels like it would be nicer
But why bother? If I have a thousand clients that all want to run a query, why compile the plan a thousand times (and build/distribute the local planner to all of the different clients’ platforms) when I could send a query and have the database plan and cache the query once?
Also, what about views? Let’s say I expose my tables in a convenient non-materialized view. You query that view, bake the query plan into an executable, and ship it. Later, I change the backing schema a bunch, adding/removing/changing tables. I update the view so that it behaves the same way it did before. Your pre-compiled plans are going to be invalid now, right?
Same deal for efficiency: if I make an unindexed table and you ship a plan that copes with that by compiling in a hyper-efficient vectorized full table scan, then later I add an index to the table, do I have to rebuild all my client deployments to start using that index?
If the answer to those is “make the client code aware of the schema, indexes included, at build time”, I think that excludes a lot of cases where multiple codebases (some of which don’t contain the ORM or schema info beyond queries) talk to the same database, and reactive database-side schema changes to e.g. add an index by hand during an outage. I don’t particularly like it, but it’s true that a lot of shops don’t use a database migrator at all, or don’t use one that’s integrated with their client application SDLC in any way, and that’s likely to remain the case in a lot of situations.
Both views-as-query-snippets and reactively adding indices are pretty common, so I’m reluctant to consider SQL alternatives that don’t support those patterns.
Non-materialized views wouldn't be part of the schema, but you could still have stored procedures which change with migrations. A new index would not be used until clients were updated to use it, just like a new API method wouldn't. For better and worse this is the point – changes and improvements are made in the place you write the query, rather than in a dynamic general query runner.
It would probably also increase the places you use an 'application layer' which is tightly coupled to the database and provides a more stable, less general view to various clients. So, the place you write queries can itself be centralized towards what owns the data, but either way there's less happening in between the query and the data.
the drawback is your query patterns have to be known before hand when designing your application. which isn't really a drawback since you're doing it before building the application. & hence not as flexible as SQL.
It speed-runs juniors into thinking they are writing transactional code when they aren't.
And for seniors who are more aware of footguns and try to be careful, they're met with an inability to do so (e.g. upserts).
SPJ is/was working on a lanauge Verse which provides a procedural looking language that is actually either fully unification or region-based under the hood. trivially this is just allowing relations (tables or functions) to implement only a subset of input/output signatures
so yes, I think its a great idea to just smoosh the two together, particularly if its in a host language with sufficient meta programming facilities to extract out the relational parts and evaluate them as streams
so you can certainly float an alternate QL on top of the same base, but its going to be hard to drive uptake. you can translate SQL to your internal variant, but oddities like group by are going to twist your internal model.
at this point I think its more interesting to start to deconstruct these large software systems like OSes and databases and move the composition of systems down a step.
Maybe when they've achieved wide adoption for a better language than SQL, they can work on getting rid of qwerty keyboards...