176 points · by pseudolus · 2y ago · 138 comments
It’s been 30+ years and the expressiveness of SQL DDL constraints for data-modelling is completely unchanged. So far, only Postgres has extended it with EXCLUDE constraints; what I’d love to have is a “Non-unique foreign key” constraint and its inverse: a “NOT EXISTS” constraint - these alone would go far.
Another huge need is for safe-and-sound data-structure invariants - it’s almost impossible to correctly store a linked-list on a table without running until concurrency issues.
I appreciate that eschewing RDBMS-provided data-integrity features makes sense when it makes sense to - especially when it’s your application code, and yours alone, that guards access to the underlying store.
But such-as-it-is, my current industry (think: incredibly unappealing on-prem CRMs) is all about treating the RDBMS as canon; reason 1 is because there’s a dozen companies all offering value-add services and systems that all integrate into each other solely by having an on-prem agent daemon that just logs-in to the first Oracle box it sees on the LAN and execs its raw SQL, not just SELECT, but plenty of UPDATE and ALTER - all without the decency of a TRANSACTION.
So having even only the most rudimentary of FK and CHECK constraints is what keeps hundreds of thousands of small-to-medium-sized business from imploding from a hosed production DB. They pay for themselves.
…but ifs not enough. There’s still plenty of data-anomalies even in the most well-designed aspirational 6th Normal Form DB you could make today simply because the RDBMSs are awkwardly rigid and inflexible in that regard. I wouldn’t be complaining about the lack of (cheap, high-perf!) EXISTS/NOT-EXISTS constraints in MSSQL/Oracle/MariaDb if those RDBMS were feasibly extendible in that regard. Postgres is the exception here, but unfortunately for me absolutely zero of the systems I work with use it; instead they’re more likely to run on Progress AS/400 or some proprietary xBase derivative.
Incremental View Maintenance engines might be the solution we've been waiting for here.
…and the lack of a LEFT OUTER JOIN also kills it for a lot of things too.
One problem is that a Txn won’t commit until all secondary indexes are updated, but I’d prefer it if there was a way for a Txn to unblock its caller once the base-table update is saved; updates to secondary indexes could then continue asynchronously. (I know this is hardly an original idea, but I haven’t read why this can’t be done)
One corollary of this is that you need to look at the problem you want to solve and decide. I don't think SQL is obsolete but I think it is not the iption for every kind of problem. Specially in HN there are a lot of discussions about "big data", "data science", AI.
I've done some high scale stuff off mysql with 10s of billions of operations a day across sharded clusters with some nodes holding terabytes of data -- fks, triggers, cascading deletes and such tended to be too expensive. I've not had the opportunity to use something like neo4j, which supposedly has a great horizontal scaling story.
edit: not that my downvoters will see, but, seriously? I'm asking a question to understand if I'm following. What are you downvoting? And yes, I've heard you are not supposed to question downvotes; I'm honestly perplexed.
• Docs: https://docs.janusgraph.org/storage-backend/scylladb/
• Detailed use case: https://www.scylladb.com/2019/05/14/powering-a-graph-data-sy...
• Video: https://www.youtube.com/watch?v=7WZyVUTwYJ4
Note this was a few years ago. I haven't seen a TigerGraph vs. JanusGraph head-to-head. The TigerGraph people are pretty sharp. If anyone has deeper knowledge would love to see comparative benchmarks.
Both JanusGraph and TigerGraph are rated about the same in terms of popularity on DB-engines.com (between 100-150 rankings). Neo4j is still far more popular/well-known, at rank #21 this past month. But there are other options you can explore.
https://docs.oracle.com/en/database/oracle/oracle-database/2...
Even the HMTL5 tools where bad. Creating a table via the UI caused a right pop-out modal that did not properly utilize the web browsers view. Typing in the column name would cause the data type field to be partial visible and selecting the data type caused the column name to be partial visible.
My take, expensive solution with inferior tooling based on competition.
For more complex cases, one could write (or autogenerate) triggers, but that will likely cause performance and maintenance issues... so the other option is to standardize any important data validation & logic into application code - and that part of application code can be stored procedures if it needs to be close to the database.
Edit: Sometimes it's easier to sell the idea of using stored procedures for (data) logic to non-database developers when you call them database APIs instead of stored procedures :-)
And if you're building an app you usually want the validation of input to be done as close to the user as possible (like in the UI), not relying on a round trip to the database and handling an exception. And some might say 'well have validation in both places' but then you've got a load of complex stuff to keep in sync which will be a pain in the arse if it gets out of sync (if your db rules differ slightly from your ui rules)
Of course you have to be careful because constraints can really slow things down.
When your RDBMS says that a particular CHECK constraint is enabled, then that’s a hard-and-fast guarantee that every row in that table satisfies that constraint. As a concrete example: if I have a simple CHECK constraint that ensures the Users.EmailAddress column matches a regex like “^\S+?@[\w\.\_\-]$”, then my ETL code that reads those records out from the DB doesn’t need to handle the case when “@“ is missing, thus greatly simplifying software design.
Put another way: consider how refinement-types (or dependent-types) in OOP exist to declare and enforce hard guarantees about the state or shape of an object or data in-memory, and they also provide effectively zero-cost compile-time precondition checks; then you can appreciate how constraints in a databases do the same, except for persisted data on-disk.
But a trigger, on the other-hand, needs some qualification as there are many kinds - we can ignore triggers which simply audit (I.e. log or alert) when some action is taken, but there are DML triggers which perform some test on data affected by the DML and either block the DML from continuing or committing, or allow it to happen. This kind of trigger is functionally identical to a CHECK constraint - but unlike a CHECK it doesn’t provide any guarantees. While he third kind of trigger won’t block DML, but it instead applies some transformation to the data affected by the DML before the change is committed; this has the advantage of allowing otherwise-invalid data to be corrected and accepted instead of blocking the operation; all of this is good stuff, honestly.
…the problem is that the presence and enabled/disabled statue of the trigger tells you absolutely nothing about the state of the data at-rest - but a CHECK, FK, or UNIQUE CONSTRAINT does.
Consider that if I removed that e-mail address regex CHECK and moved it into a block/allow TRUGGER then anyone who reads from my Users table now no-longer has any guarantees about the contents of the Email column; Now also let’s suppose that some other DBA, or perhaps an automated process, might need to legitimately disable the TRIGGER temporarily while they perform data cleanup work and then re-enable it; in the event that the cleanup job was botched then the invalid email addresses will lie there undiscovered until the ETL loader crashes the next time it runs because it was never written to handle malformed email addresses.
So in truth, TRIGGERs and CONSTRAINTS are complementary to each other: a DML trigger that transforms data to satisfy a CONSTRAINT is a good example.
————
Now consider an abort/allow trigger that performs something “non-trivial” (as far as the DBMS is concerned) DML validation check, such as a cross-table, or even cross-database query; obviously that won’t scale and it also introduces more points of failure (ext. DB connections) - but hang on: for limited kinds of cross-table validation checks we use FK CONSTRAINTS as that’s what they’re designed for - and they work great because we know how to optimise for them (usually by adding FK indexes).
So my argument is that there exist many other classes of validation rules which today can only be implemented as TRIGGERs but could instead be better implemented as a declared CONSTRAINT because of the hard guarantees that only declarative constraints can give (when enabled, of course).
For example, a “non-unique FK” constraint would not be any more expensive to enforce than an FK because it reduces down to the same (indexed!) set-membership test as a normal FK constraint. The exact same applies to an “anti-foreign-key” constraint (except the set-membership test is inverted). It’s so trivial to implement - which means its so maddening that it doesn’t exist in SQL.
My position is thus: if you can express a desired constraint as a deterministic function of a single row and the set of all indexes which runs within at-most O( n log n ) time proportional to the initiating DML’s time complexity then we should be allowed to do it ourselves.
It is kinda crazy the contortions you have to do to make some dynamic queries with the existing tooling.
I have found Malloy[1] to be easier to read and write, even for really complex queries. Malloy complies to SQL. As an example check out [2].
Malloy can query .csv files directly (enabled by duckdb). You can also join .csv files. This makes getting started a breeze for beginners, and is a boon for data scientists. Much easier than Pandas in many cases.
With the visualization capabilities it has built in, Malloy sort-of competes with Tableau and PowerBI.
Most people only write SQL to get data out of databases, for these people, Malloy is an interesting tool to consider.
[1] https://www.malloydata.dev/ [2] https://docs.malloydata.dev/blog/2023-10-26-malloy-bump-char...
Not affiliated with Malloy, I've just played with it for a while and been impressed. It's also MIT licensed.
For starters, according to that link it only left "experimental status" in Oct 2023; it's pretty new. Although their GitHub still describes it as "an experimental language". That doesn't exactly inspire confidence for long-term production use.
The second problem is that while imperfect, everyone and their dog knows at least the SQL basics. There's a lot of value in that.
Thirdly it's written in TypeScript, so anyone not using TypeScript will either have to run some sort of "generate" step, or have to rewrite it in $language_of_choice. Both are painful. This is not a TypeScript problem: you will have that with any language (although with languages that compile to a binary it's a bit less painful, albeit still painful).
Lastly, it doesn't work for all SQL flavours: just BigQuery and PostgreSQL. That's pretty limited.
All of that is assuming the SQL it generates performs as well as "native" SQL, and that all of this can be reasonably debugged if something goes wrong.
With Malloy you can do the analysis on your data lake directly for 80% of your questions.
https://docs.malloydata.dev/documentation/
"Malloy currently works with SQL databases BigQuery, Postgres, and querying Parquet and CSV via DuckDB."
I'm guessing most people would rather spend effort in solving their immediate problems with SQL rather than bet on a newer and less known technology, even if has a lot of promise.
- it's hard to start tinkering unless you have a database to write queries against. most tutorials never really get past the most rudimentary hello-world-esque stuff because they're limited by the size and complexity of the example data.
- imperative programming teaches you to be very precise and explicit about what exactly should happen, so it feels very weird to start working with something declarative where you can just trust the computer to figure it out and do things well automatically.
Another example of this I saw recently using SQLite (compiled to Wasm) in the browser: https://docs.sqlitecloud.io/docs/sqlite
And if you ever want something similar for more general backend APIs (without relying on Wasm or the browser to run the software), https://codapi.org/ looks very slick e.g. as demonstrated in https://antonz.org/sql-upsert/ - discussed on HN previously [0]
Inspired by https://www.db-fiddle.com/ my colleagues ended up building a fairly bespoke setup for XTDB's docs (XTDB doesn't yet compile to Wasm) shortly before I came across Codapi, although our requirements were even more particular, e.g. see https://docs.xtdb.com/tutorials/financial-usecase/time-in-fi... - the backend here is https://github.com/xtdb/xt-fiddle which runs purely on top of Lambda Snapstart, and embedded within docs based on Astro's Starlight [1] and Web Components
Also, it's very easy to make queries that complete and look correct but give wrong or incomplete results. You've not going to notice that from just running queries in self-directed practice.
Maybe this just isn't something you really want to dive into. That's ok!
SQL has changed very little over the past 25 years, and while there are some syntax variations across different databases, the most important 80+% is universal. Even if the book is for SQL Server the vast majority will work on Postgres, SQLite, etc.
IMO the biggest issue of SQL is that it brings bread and butter for the BI/DA people, who are so close to the business that they usually don't care about code quality and such. It's not the fault of the language, but the fault of erroneous team structure.
Imperative programming is a strong habit to kick. You just have to let go. And once you have you will see things from a very different perspective.
Also in other programming you'll start seeing the map/fold/groupby/dict patterns everywhere.
- that just means that I'm bored and would rather be writing out the logic to handle a more general/abstract representation of the problem
- whenever I come across a DSL that somebody else made to "make a really simple declarative-like interface", i hate it and wish that they didn't do it
One nifty thing with SQL is that you get all the threading/remote processing for free without having to think about it. That can be pretty hairy to write yourself.
If you find yourself looping over a rows with a cursor you are probably doing it wrong, or at least suboptimally.
2) I'm not sure about your personal experience, but having worked with make files during C programming days, I think you get used to declarative state stuff pretty fast!
I hate it, but there's little point in complaining because it's so ubiquitous.
More robust criticism is provided here (https://carlineng.com/?postid=sql-critique#blog), which pulls on an interview here (https://www.red-gate.com/simple-talk/opinion/opinion-pieces/...) The quote I usually drag out is from Chris Date, who helped pioneer relational DBs:
"At the same time, I have to say too that we didn’t realize how truly awful SQL was or would turn out to be (note that it’s much worse now than it was then, though it was pretty bad right from the outset)."
As an example of a language that does it better, I think kusto-query-language (KQL, https://learn.microsoft.com/en-us/azure/data-explorer/kusto/...) has been a dream to work with. (disclaimer, Kusto is a Microsoft product, and I'm a Microsoft employee).
I feel like rational database querying is effectively solved and there's little point in re-litigating it. But still I'd be happy to switch to the perfect replacement if someone develops it.
Sql might be ok for trivial things, as in OLTP that programmers tend to work with.
But anything even slightly more advanced is... not nice.
And the standard is unique in its uselessness.
The underlying relational algebra model is brilliant thought.
Examples?
> SQL might be OK for trivial things, as in OLTP...
What is the threshold for triviality? I've seen understandable fairly complex queries, but they're not mind-twisters by any means; if you know what you need, and understand your data, >>and are not a layperson regarding databases<< it's doable without much sweat.
> But anything even slightly more advanced is ... not nice
Again, what is the threshold, or at least what is your threshold, for triviality vs. non-trivial?
You say it's "unique in its uselessness" but "the underlying relational algebra model is brilliant", can you explain a bit further what you mean by that?
The worst SQL I've ever seen is when someone attempts to program it imperatively. It takes a different mentality to write SQL then to write imperative code.
"Being ok for trivial things... that programmers tend to work" with is precisely why SQL has won over the years. SQL has never been a great general-purpose language, but is fantastic at the things programmers tend to work with. That SQL (and associated databases) keeps getting extended to meet new data storage/retrieval problems has really helped SQL stick with us.
Sure, there are some languages which can compile down to SQL, but like Typescript, every once and a while, you find some edge case where the transpilation fails you and you might as well be an expert in SQL.
I love all of the ideas of PRQL, but I do not know if I would be painting myself into a corner adopting something that will go the way of CoffeeScript.
The critiques in that link show a fundamental lack of understanding, eg. it poses that the following query should be allowed and wonders why sql complains about fetching more than one row since avg requires more than one row, but the reality is that what they are describing is avg(rows of rows) rather than avg(rows) which obviously doesn't make sense:
SELECT
AVG(
SELECT SUM(amount) FROM purchases GROUP BY customer
)
But even worse, the article says that the only solution is using a CTE(!?) and doesn't mention the obvious use of a subquery: SELECT
AVG(total)
FROM (
SELECT
SUM(amount) total_per_customer
FROM
purchases
GROUP BY customer
);
In my experience I've seen that usually the people that find it difficult to understand SQL are also the people that will be writing .fetch_by_id functions instead of .fetch_by_filters, ie. they consider database tables and data in general as 1d arrays in imperative programming and only think in those terms rather than the 2d sets they are. I'd wonder how their mind would melt if they'd tried to understand querying for 3d data, eg. temporal databases.Also I fail to see how KQL is any different to SQL, it's pretty much the same thing with the exception that the selection comes afterwards, is that the factor that makes you hate SQL?
From the link you posted:
StormEvents
| where StartTime between (datetime(2007-11-01) .. datetime(2007-12-01))
| where State == "FLORIDA"
| count
vs FROM StormEvents
WHERE StartTime BETWEEN '2007-11-01' AND '2007-12-01'
AND State = 'FLORIDA'
SELECT count(*)
and StormEvents
| where DamageCrops > 0
| summarize
MaxCropDamage=max(DamageCrops),
MinCropDamage=min(DamageCrops),
AvgCropDamage=avg(DamageCrops)
by EventType
| sort by AvgCropDamage
vs FROM StormEvents
WHERE DamageCrops > 0
SELECT max(DamageCrops) MaxCropDamage,
min(DamageCrops) MinCropDamage,
avg(DamageCrops) AvgCropDamage
GROUP BY EventType
ORDER BY AvgCropDamagefor example, here's the KQL equivalent to the 'average of sums' query:
purchases
| summarize total_per_customer=sum(amount) by customer
| summarize avg(total_per_customer)
I find this more elegant, and I'd prefer authoring it over any of the equivalent SQL solutions previously mentioned.My most recent favorite KQL trick for debugging from logs is `autocluster`. Maybe you'll also find it useful when you're in trouble :)
I think SQL as a language could also be improved a lot to make it easier to understand. It looks and feels like FORTRAN 77.
> managing the database source in the repository, integrate the database into tests easier
These are much easier problems to solve. Many people have already solved it.
Otherwise, jooq is a fine addition to the Java world, as it generates a type-safe DSL from your ddl file where every statically correct jooq/Java statement is also a statically correct SQL query.
https://gist.github.com/cpursley/c8fb81fe8a7e5df038158bdfe0f...
One way to eliminate the Java-SQL impedance (for example) mismatch is to delete Java altogether, along with JOOQ, Hibernate, and Spring (for example).
Do you feel the same about HTML, CSS, JavaScript, REST APIs, etc?
I'm not sure what else you need. This seems like a basic tooling problem.
Bad enough that their flaws are evident even to novice practitioners.
Good enough, entrenched enough, that they will be around for the next 50 years too.
Not sure about SQL and Javascript though; successor options are way less clear.
also remember that sql is a query language not a programming language, so the main target are not programmers
also think of it this way, it might help, you start with that you really want
select firstname, lastname, hobby
so you start by saying you want a table (a relation, a relvar)
that have first name , last name etc ... this is what you want
then you tell me where to get it from from users
so the order is not bad , it like saying, get me a a drink from the box
you wont say, from the box get me a drinkselect first resembles more natural language, and is more declarative
from first, is more procedural
what i want first, then how --> declarative
how to find what i want, then what i really want --> procedural
Well, I never...
I know the intent was to write a declarative language where you just specify what you want and the system figures out how to get it- but I consider that project to have definitely failed considering that in order to get the sql interpreter to behave in a sane fashion you must use explicit JOIN statements everywhere and fetch table rows and index them to other table rows in a specific order using specific keys that the programmer chooses. It’s exactly the same as writing while loops, though the syntax is admittedly quite nice.
I’ve seen people try to interact with the interpreter with a great big god query like SELECT FROM A,B,C,D,E WHERE A.id=B.id and B.id2=C.id2 and so on, and that would be a declarative way to do it, but the performance of the interpreter in such scenarios is absolutely, universally, perplexingly dismal and in practice you can’t use sql that way. It was a nice idea though.
SQL was designed for a purpose it never fulfilled and never will: end user queries. The promise was that users would write their queries so IT staff would have to write reports. But the only users of SQL today are those same programmers, many resentfully or disdainfully. Every online database discussion is rife with misinformation or silly advice ("write SQL sentences"); rare is any discussion about the relational model or first order predicate logic.
And that brings us to the user-led stagnation, as it were. If more programmers using SQL understood the fundamentals, perhaps there would be some innovation. Instead we live through the constant reinvention and rediscovery of what SQL can do, and a perennial effort to make it "easier" with ORMs and such. Actual ease, using a better language, is never discussed.
The right language to express relational algebra IMO is Lisp. I don’t mean Lisp-over-SQL. I mean Lisp over data, where tables are fundamental Lisp objects, and modifying those objects updates the database. Lisp solves all of SQL’s deficiencies: verbosity, orthogonality, composability.
The would-be inventor of a better database query language faces a daunting problem, however: there is no free relational engine. No C library implementing relational algebra over a data store. So, not only does the language need invention, but the database engine itself needs to be engineered. Nothing has happened in this area since Berkeley DB, which is barely a start and has anyway been hijacked by Oracle.
The nearest thing to a free modular database framework isn’t very close. The original Berkeley Ingres DBMS is nominally free software. But it hasn’t been portable to, say, OpenBSD for decades, and the proprietary owners are understandably not motivated to make their product a toolbox for tinkerers.
So, it seems we’re doomed to another 50 years of SQL. We have met the enemy, and he is us.
> The LLM will write the SQL query for your end users!
We are doomed to repeat the same mistakes forever.
"Standard SQL is good and portable and worth spending enormous resources supporting" -- statements dreamed up by the utterly deranged
There are tons of popular programming languages and they share paradigms, good ideas and syntactic similarities. Query languages ought to be the same.
Dialects work in natural language because interpretability, syntax and semantics are all fuzzy.
Dialects in computer languages is an anti-pattern because syntax and grammar must be precise and deterministic. You are either writing Java or gibberish, the Java toolchain will never charitably interpret your syntax errors as "close enough to understand".
SQL-the-standard birthed a bunch of different dialects of SQL that ought to be de-jure separate query languages.
So much human effort is wasted dealing with the standard SQL abstraction layer. If someone is migrating from Oracle to Postgres, the fact that their query languages are eerily similar is far down the list of practical concerns.