r/SQL • u/yughiro_destroyer • Jul 06 '26
Discussion Why do we need abstractions over SQL?
When I mean abstractions, I mainly mean OOP and ORMs.
SQL is so simple and beautiful. Tables with rows and columns are easy to understand. And once you pick up the SQL syntax, you can pretty much achieve anything with queries. Not to mention that SQL is universal and works everywhere and anytime.
Then you have the software development world... where you're asked to constantly use ORMs or map records as OOP objects. Why? ORMs are limited and do not have the flexibility of simple queries. Also mapping records as objects increases bloat, reduces performance that can hurt if the application grows and is overall not as straightforward to work with.
The only good things that ORMs are doing by default are to provide data safety and prevent SQL injection. But with some minimum and basic knowledge and discipline, you can write pure queries without having those problems. Any ideas?
39
u/Sharp-Echo1797 Jul 06 '26
Developers love ORMs because they write lousy SQL. They all want to use SQLAlchemy or Django. I'm sorry learn to write stored procedures and performant SQL.
24
u/throwthewaybruddah Jul 06 '26
Why would anybody use Wordpress or shopify?
Web development is so easy and elegant
Why would anyone use typescript?
HTML is so easy and elegant
Why does anyone even need a User interfact? Command line is so easy and elegant.
The answer to your question is that people don't have the time or resources to do everything all the time. If I can insert things in my database using mappings to types and objects, saving me hours upon hours of writing plain SQL, i am going to do it.
3
u/Lumethys Jul 06 '26
Architecture is more important than "sql elegant"
An advance search page has an export button and a bulk update button
3 actions. List, export, bulk update. They should operate on the same data set, or in order words, the same WHERE
Sql queries are just plain string, you cant reuse the WHERE part unless doing some string concatenation gymnastics. And as soon as you take steps to make it safer and easier to reuse parts of your queries, you are building an ORM.
All in all, database is just a small part of a system. It is secondary concern. The important part is the business logic. Database must conform to the rules laid by the business, not the other way around.
14
u/jshine13371 Jul 06 '26 edited Jul 06 '26
Preference. Lack of experience. Lack of teaching SQL properly in academia.
Edit: Note my answer is on why it happens, not an argument for that it should happen. A lot of other comments by developers in here are proving my second and third point. 🫤
6
u/amayle1 Jul 06 '26
You don’t. SQL is itself an abstraction, and a really good one.
5
u/raphired Jul 07 '26
From my perspective using EF core in C#:
The performance differences are negligible for the vast majority of the code base, so we only use SQL where Linq is hard to read, the SQL it generates doesn’t perform well, or I need an operation that EF doesn’t support. The ability to see most (if not all) uses of a column via the IDE’s refactoring tools is terrifically useful. EF handles writing the insert/update statements minimally, so I don’t have to check whether any values have actually changed. Being able to add an interceptor that handles auditing changes or updating last-modified columns that someone thought was a great idea to put everywhere reduces a lot of cognitive load. Query filters for tenant IDs or soft delete tomfoolery likewise reduces cognitive load and stops a few easy to miss bugs.
I love writing elegant SQL statements, but they’re edge cases rather than the norm.
16
u/thatOMoment Jul 06 '26 edited Jul 07 '26
It is neither simple nor beautiful, you just haven't gone over all the edge cases yet.
The most aggregious off the top of my head.
COUNT and other aggregates with no GROUP BY returns 0 when there are no rows, adding a GROUP BY removes the 0 and returns empty set instead, this is the only case where this is true.
NULL is not equal to itself which is correct... unless you use it in DISTINCT, UNION, INTERSECT, EXCEPT OR GROUP BY.
Then it is
FROM should have been the first part of statements for autocomplete, SELECT is first and tooling is terrible now as a result.
You cannot put a primary key on 0 columns to assert only 1 row at most can exist in a table, you need check constraint hacks to pull that off.
Edit: Fixed "Group By with no columns returns 0 when there are no rows"
1
u/deusaquilus Jul 07 '26
Simple! I need ORM so that I can do:
So that peopleSomewhere, companiesSomewhere, and productsSomewhere can be abstract things that I can define later, someRelationship and someOtherRelationship can be complex things that have nasty business-specific logic, and rowsThatAreUseful has 50 different implementations.
So instead of having a nasty 200-line query I call usefulStuff(p, c, pr) and define it's pieces elsewhere.
1
u/Big_Pianist_2826 Jul 10 '26
> SQL is universal and works everywhere and anytime
This is a nice idea but it’s not true in practice, and makes shifting DB software an enormous pain if you’re writing bare queries
Most projects are small and don’t need to think about this. But I’ve been involved in an enterprise project which shifted backend from MS SQL to Postgres and if we weren’t using an abstraction over SQL it simply wouldn’t have been possible…
3
u/Outrageous_Let5743 Jul 06 '26
People dont understand joins so they rather do loops to iterate over te rows. That is why the n+1 problem is bs because you can use a join if the people could actually write sql.
3
u/reditandfirgetit Jul 07 '26
ORMs are for entities for an application. They are to make tge development easier. For simple things it B works fine and most ORMs, provided the entities are well designed, will write decent SQL. Where it causes problems is when the logic starts to get complicated and the devs refuse to wrap a stored procedure into an entity
5
u/sixtyhurtz Jul 06 '26
It really depends. EF Core in C# / dotnet world is kind of nice these days, mainly because it can help you generate migrations. It also has OK syntax for just mapping an SQL statement to a POCO so you can just write SQL when you need something specific.
I feel using an ORM for basic CRUD and raw SQL for everything else is fine. Mapping from DB -> Entity class -> DTO is obviously a little slower than just mapping straight to a DTO, but are you Google? It's not that big a deal for most use cases.
2
u/Eleventhousand Jul 06 '26
You don't need it from an ORM perspective I guess.
It can be useful in Business Intelligence though, when you have a semantic layer on top of a schema, because otherwise it can be difficult to enforce how different columns are aggregated.
2
u/patrickthunnus Jul 06 '26 edited Jul 06 '26
My experience in the field is generally that many Java developers aren't happy or skilled enough writing SQL, especially if you use offshore resources; you have to pay a lot more for that skill.
ORMs, SPs and DB Views abstract all that, flatten and simplify app & DB interactions, design - especially for large organizations that chase lower costs.
2
u/spergilkal Jul 06 '26
I think you might be blind to the faults. For example, the ordering in .NET LINQ query syntax of FROM WHERE SELECT is way better than the SQL SELECT FROM WHERE. An IDE can't help you with autocomplete until you know the tables you are querying.
1
u/read_at_own_risk Jul 06 '26
SQL has many flaws and I'd love a good abstraction, but ORMs are absolutely not it. ORMs are a throwback to the pre-relational navigational models.
1
u/dbxp Jul 06 '26
Off the top of my head:
1
u/vbilopav89 Jul 07 '26
We don't. I built an entire tool for myself around that idea: https://npgsqlrest.github.io/
1
u/TheSodesa Jul 07 '26
You are going to need at least some representation in a language interfacing with any external tool and that is necessarily an abstraction, even if the mapping was 1-to-1. But you already have things like Python and Julia dataframes which are pretty much just this.
1
u/titpetric Jul 07 '26
SQL is an abstraction, but in programming, objects are the native type and there is always a translation into sql. CRUD operations can be easily modelled with code, but general selects can be complex and I favour writing the sql for those.
The problem as I see it, ORM for CRUD works out, and for everything else I write a select. There is nothing to abtract from a basic select query, but some search or analytics queries can be tedious to write/proof, i don't see ORMs making my life easier for those.
1
u/lmarcantonio Jul 07 '26
...but OOP is fundamentally incompatible with "true" relational data; it's also called impedance mismatching. And most of the time (unless you are doing crud) you don't have objects related to a single entity but the shebang related to the query output. What if an attribute isn't pulled in the query and you access it?
In my experience ORMs do a lot of queries by rowid (and that is not bad by itself) and work well when filtering on a table. When you have huge/complex joins they tend to have…issues.
Also OOP is really not a lot useful in many typical SQL use cases.
1
u/RandomiseUsr0 Jul 07 '26
Every single orm or “easy” (with outstanding exception of old school MTS) has been and all are (looking at you GraphQL) utter shit, literal dog shit - here’s why, you can see I have opinions…
Performance is (mostly) secondary to business intent. SQL helps business intent, it is an almost, very nearly, complete computation language (some implementations are) which should handoff to a good optimiser (I’m an old oracle hand, of course I hint the optimiser) - every single thing that assumes or worries about my actual data structure and then FORCES ITS OPINION can do one - this shit isn’t helpful, it’s never going to be helpful, it’s always a trade off, it’s always based on some imagined “Time Machine” of knowing your data’s purpose - they don’t.
Any fad that claims to solve that is magical thinking
1
u/DaOgDuneamouse Jul 07 '26
I've always said, right tool in the right hand for the right job. Data engineers write stored procedures, and software folks write POCO objects and loaders. Seems simple enough to me.
1
u/Anxious-Insurance-91 Jul 09 '26
Depends on the ORM. Some ORMs have select sintax very closely to SQL with a few extra specific methods for helpers or for loading relations without joins(Laravel eloquent), others like c# Linq make me feel like I need to write separate queries one after the other with whereins because it just so damn illogical the order of execution or the fact that I can't just select what I need. In the end for end to end solutions you need to know raw SQL and how to create the database. The oop just adds more interaction with the data that can't be done via queries without writing store procedures
1
u/tmptmp666 Jul 10 '26
What happens when client switches database because of various reasons? We did that three times on two different projects. It took us 2 days for our backend team to do it, not including QA testing ofc. Abstractions exist for a reason.
1
u/No_Resolution_9252 Jul 11 '26
SQL is really not that simple when it needs to be written both cleanly, safely and performant. Almost no one can do all three. there are people that think you can use CTEs for everything out there
For most apps, ORMs and tools like Dapper provide better compositionality, reduce bugs and better future proof the application code and writing raw SQL provides no value but incurs higher cost. In reporting queries, optional parameters can easily be faster than they are with native SQL. (setting dynamic SQL aside) When there are performance problems it isn't that big a deal to switch that bit of code to SQL instead of imposing greatly higher development costs on a project from day one to not make a performance difference in the vast majority of queries.
0
u/Difficult-Report-524 Jul 07 '26
One word:
ENTERPRISE
-1
u/serverhorror Jul 06 '26
Autocomplete - most IDEs treat(Ed) SQL as just text so people wanted to type
.and get the options. Also: type safety in the programming language of the application (even if it just looks like that)-1
u/zmitic Jul 06 '26
They are not, it is just a myth. And a pretty bad one, I heard much worse ones like that somehow magically ORMs can't work with big tables.
If your query to fetch 100 rows takes 2ms on average, mapping that to 100 objects takes <0.1ms. And that is in PHP, not in C# or faster. So who cares?
Bonus: not all ORMs have it but in Doctrine there is second level cache. Check it out: you would get DB results even without executing a query. Given that at least 90% of queries are SELECT, it is a massive boost in performance: Doctrine takes care of cache invalidation.
Not true. As the app grows, ORM shows its power more and more. Especially because of identity-map pattern, which is the most important thing in big apps.
There are no problems with ORMs, that is being said only by people who never learned how to use it. But modern one with data mapper, identity-map pattern, UoW, repository pattern... like Hibernate, Doctrine TypeORM...
It is much easier to understand objects, have auto-complete, static analysis will work, adding aggregate column is easy and ORM will handle race condition issues... None of that is easy to do in vanilla SQL.
Reference: I make only really big multi-tenant apps (single DB), with tables having millions of rows. Common feature is to have data export: speeds are typically from 8,000-20,000 CSV rows per second.
Data import: depending on how many DB tables it touches, the speed is from 500-10,000 rows per second and more. This one was always hard to measure because no one ever uploaded some really big CSV.
All statistics is aggregated so I never run slow aggregate functions. Not even for pagination, they are strictly forbidden in my code just like JOIN. This is why things are almost instant, no matter how big the table is.
-2
u/BarelyAirborne Jul 06 '26
Validation. SQL types need to be enforced by constructing JSON schemas or using an ORM. Pick your poison.
0
u/[deleted] Jul 06 '26
[deleted] — view deleted comment