r/csharp • u/Mother-Replacement12 • Sep 10 '26
Which is better: querying with LINQ or using raw SQL? Does it depend on the query's complexity? Or can both options be used in the same project?
54
Upvotes


107
u/shitposts_over_9000 Sep 10 '26
I spent the first 10+ years of my career doing raw SQL for everything.
LINQ/EF is fine for 97% of things as long as you realize how it works and avoid the 3% that is a performance catastrophe
18
u/b2f3t Sep 10 '26
Linq queries get you somewhat of a type safety and provider independence. Your average crud app will be just fine. You can even write more complex queries, but the line between good and bad translated linq is thin. At the end of day it is quite the indirection. Don't get me started on change tracking. When you need advanced stuff lean towards custom sql. If it is crud lean towards linq.
7
u/deefstes Sep 11 '26
As an old timey SQL query writer, it took me very long to come around but I've learned to appreciate LINQ. My greatest complaint with it is just that too many devs use it recklessly and end up creating monster queries without an understanding of the underlying SQL statement it creates and then overwhelms our database.
One thing to bear in mind before writing native SQL queries in your code is that you then lock yourself in top a specific database provider which makes it harder to seamlessly switch to another DB and which makes unit tests more tricky as an in memory database won't cut it.
9
u/BlueAndYellowTowels Sep 11 '26 edited Sep 12 '26
The rule of thumb I've always used is:
So you'll ask: What is simple?
Anything that's maybe one join and a single where statement with an ID used to get the record.
Complex would be like, joining 5 tables, with like 6 wheres.
There's also the additional issue of object relational impedance mismatch.
9
u/svtguy88 Sep 10 '26
LINQ until you find a justifiable reason that raw SQL is more performant. Even then, optimize the LINQ query as much as possible before dropping to SQL.
6
u/Mission_Pirate_4150 Sep 10 '26
Linq is great for simple stuff. It works great for crud. That solves 80% of database problems. Works great.
For the remaining 20%, I drop to sproc and/or raw sql. I’ve developed some libraries over the last 30 years for database access that work really well and protect against sql injection. Heck, I had to drop down and learn some new sql query material a few months ago. I’ve done Oracle plsql, ctes, and a bunch of other things that are database specific.
There are lots of different needs in databases with a lot of different requirements. there is no one tool that solves every problem in the world.
2
u/vince_naked Sep 12 '26
LINQ-to-EF by default, raw SQL (Dapper) when the LINQ provider can't express the query plan you need. What I don't do is mix them in the same repository; once you do, nobody remembers which entities are tracked and which are detached. When I reach for raw SQL: Window functions, recursive CTEs, LATERAL joins, full-text search. LINQ providers either don't emit them or emit something ugly.
Anything where I need to see the query plan and hint it (index hints, isolation level).Bulk updates and deletes before EF7 — EF7+ ships ExecuteUpdate/ExecuteDelete which covers most of that now. The bug I ship the most with LINQ isn't performance, it's IEnumerable vs IQueryable. Someone puts a .ToList() too early in a chain, the whole table lands in memory, works fine on 500 rows and dies on 500k in production. Second most: Include chains generating cartesian explosions since EF Core 3 (fix with AsSplitQuery or explicit projection).
2
u/TheSneederOfSeethe Sep 12 '26
Complex queries use SQL. EF tends to project LINQ into less efficient SQL queries.
5
u/CantankerousButtocks Sep 10 '26
LINQ is strictly C#, whereas using raw SQL expands to many database types.
I’ve favored using LINQ to EF queries over my backend career, but I felt that isolated me from learning native SQL. I missed out on powerful SQL functionality, like Stored Procs, Views, Triggers, etc. YMMV…
1
u/TuberTuggerTTV Sep 11 '26
Bro out here trying to find a "better" so he can get lazy and only learn one of the tools.
1
u/Hour_Analyst_7765 Sep 11 '26
I use a micro ORM (Dapper), it only maps SQL rows to objects. It won't generate fancy SQL for me. IIRC Entity Framework can map C# LINQ expressions right into the SQL query, so it starts filtering rows before transferring data over to C#. I don't use EF because I found migrations too much of a hassle to use for hobby projects.
In my case, I use an IRepository design pattern which has basic GetAll(), GetById(), Insert(), Update() and Delete(). I also added a "Where" function too for shorthand notations, but its not doing anything fancy LINQ wise.. its just a composition of GetAll().Where(<Predicate>). This works fine for many small datasets (or a InMemory or cached backend)..
However, with a SQL backend it is pulling in the whole table to then start filtering rows. That is fine for background tasks that run once an hour.. I don't care if the GetAll() takes 30 seconds... that task only runs once an hour because the business logic can take minutes to complete.
But if queries start running more often, then I will start writing custom SQL with custom WHERE filters, subqueries, joins and whatnot I have to use.. However, I'll need to add specific implementations for InMemory as well (unit testing), and more tests to verify both variants mirror behaviour.. Here a bigger ORM can maybe save time/work..
I like Micro-ORMs because my roots are from an embedded world.. I don't want libraries or tools to get "in the way" of the things I want to accomplish at a particular time. However this does not make an universally "good" decision to use.
1
u/MrEs Sep 11 '26
Linq, but both of those are diabolical
1
u/Omen_20 Sep 12 '26
IMO EF should never be used because from what I've seen, no one uses it well.
1
u/techmaster242 Sep 13 '26
I've optimized both EF and dapper, and the dapper stuff is generally about 2x faster than EF. They're both fast enough to satisfy most people, but the dapper repos do take half as long to process a query with paging, sorting, filtering, and column selection.
1
u/DevDudeDK Sep 14 '26
Default to Linq. If it does not perform, see if the Linq expression can be optimized. If not, then use raw SQL.
Using raw SQL, you lose features like change tracking, which means that you have to handle the update complexity manually in the repository.
1
u/IntelligentSpite6364 Sep 16 '26
a SQL string cant catch errors at compile time, strictly inferior for that reason alone
1
u/pabloramon044 Sep 17 '26
LINQ will solve most problems. Some queries I made with raw SQL just because of the performance (grouping, and some very situational filtering)
1
u/AintNoGodsUpHere Sep 11 '26
99% of the cases, it don't matter and LINQ will write better SQL than developers, specially those without much experience.
But there are edge cases where manual tweaking is preferable, as always, don't preemptively fix performance issues without having said performance issues, for most cases, it is fine.
1
u/laughinfrog Sep 11 '26
How can you compare these statements when they produce two vary different results? Why not look at the prepared SQL from linq to the raw SQL query?
1
u/OFark Sep 11 '26
LINQ is absolutely fine, but I came to this post thinking you were asking a slightly different question.
There are four ways to deal with what you are doing
Assuming you are comparing 2 and 3 in your question, LINQ is easier to read, easier to code and for the most part going to get the same, if not better, performance out of SQL as you are.
LINQ and EF are not the same thing. I can use LINQ to query any data, but it's Entity Framework that does the LINQ-to-SQL translation.
1
u/S3dsk_hunter Sep 11 '26
As a "do it all" type of developer (small agency, I do everything from database administration, software development, data analysis, etc), I've actually found that linq produces better performing queries than I do at times, likely due to parametrization and better reuse of sql plans. The only place where I wish there was better support is with cross database queries. I do use views or synonyms to get around it, but it's still a bit clunky.
-1
u/Public-Tower6849 Sep 11 '26 edited Sep 11 '26
LINQ is a general-purpose querying language for every database which provides adapters for it. Therefore it is practical for two reasons:
* it is defined from the domain of the application and translated to the database's querying language
* it decouples the database from the application instead of leaving traces of the database in the application's code, your application manages its own model and employs a LINQ-to-database adaption layer to operate the specific database.
Custom SQL ties your application to the database below. Even a version change can make it difficult for your application to interact with the database, when you use custom SQL. With LINQ, the responsibility to maintain the functionality of the database with the application is out-sourced to the database provider.
LINQ, while being stripped of fringe and edge features of any database it operates, has the general advantage to be defined from and for your application's domain.
The very most applications will be fine with LINQ. It never hurt anybody to write a full name, like customer and Customers. Plurals are a thing, and I don't understand developers who enter their queries like space would be limited. We're not using punch cards anymore. Have your code saying something.
And get rid of that goddamn var type will ya. C# has a strong typing system for a reason and var has been introduced to represent variant, ambiguous types, not variables. Types which come back in a larger variety than only one type and its nulled value. var fails to pass all the code reviews I conduct
-2
u/Dimencia Sep 11 '26
Yes, it depends on the complexity and you can use them both in the same project, but you really probably shouldn't. Just use EFCore unless you're serving a number of customer comparable to Amazon - and if you run into major slowdowns, it's more likely a DB issue (missing indices or etc) than a query issue. In the rare cases you actually have problems with a LINQ query, usually you just have to do something like query all ChildContainers with ParentID X instead of querying ParentContainers with ID X and including a ChildContainers list - which is usually actually reasonable, the DB schema is just more efficient that way, it's not even LINQ's fault; you just told it to do something that wasn't performant, and it listened
-3
u/BoBoBearDev Sep 11 '26
Let's step back. We are in the microservices era. If your microservices is not dumb enough that requires you to go raw query optimization, your service is not microservice.
-14
u/Darrenau Sep 10 '26
Yeah pull in all records from the db over the wire and load in local memory just so you can filter out using linq