11 ms·
Why LINQ beats SQL
- tracker1 10y agoIn most of the examples, it will still execute the more complex SQL against the database... however, it's somewhat easier to reason about. That said, I tend to prefer to use the collection extension methods, over the LINQ syntax, which make more sense in my mind.
- olmo 10y agoIt's funny how async/await has influenced so many other languages but LINQ, that in my opinion is much more interesting (specially the DB stuff) for solving down to earth problems is sistematically ignored by other languages (Python, Java, JavaScript, etc...)
- ConnorLeet 10y agoArray.reduce(), Array.filter(), Array.map(), in JavaScript are pretty LINQ-ish if you ask me!
- MichaelGG 10y agoThe thing with LINQ is that it can represent itself (reified or 'quoted code), so you can transform it into SQL, GPU instructions, whatever. This isn't a new idea, and F# had it before C# did (and LISP had it before, and others). map/filter/reduce are just basic functional programming elements.
- nightski 10y agoThey are nothing even remotely likely linq. Those functions return the resulting arrays. Linq expressions are not executed until enumerated. This allows you to compose linq expressions without computing intermediate results.
- amyjess 10y agoSounds like Java 8 Streams, then. Streams bear a pretty strong resemblance to translated LINQ.
- louthy 10y agoI guess you can argue that Haskell's do notation is exactly what LINQ (the grammar) is. F#'s computation expressions is a super-charged LINQ also. I would like to see C#'s LINQ get an update. It seems to have been left to rot since Eric Meijer left the team. It doesn't even support the new values tuples where it's been fitted to every other part of the language: from (x,y) in Some((1,2)) // (x,y) will error select x + y; The from x in y, let x = y, where x, select x, and, join x in y on a equals b, could and should be extended. Even better would be to allow custom operators like F#'s computation expressions.
- pbz 10y agoTo be fair, that feature is in the next version of C#; not release yet.
- shitgoose 10y ago.net lambdas are in my opinion cleaner than linq syntax. java 8 implemented lambdas following .net success.
- alkonaut 10y agoLinq is used pretty loosely to include also the equivalent form so dogs .Select(d => d.Id) .Where(d => d.Age > 3) .Skip(4) .Take(2) would be considered just as much "linq" by most c# devs even though this isn't the query language integrated - simply because it's the same exact thing as the regular linq code. I too find the "real" linq form mostly distracting.
- douche 10y agoThe weird SQL-ish query syntax is an abomination. But using the LINQ extension methods, making use of lambdas as you say, is gold. Most of it boils down to plain old functional map/fold/filter/zip constructs under different names.
- amyjess 10y agoIn the case of Python and Java, I think it's because generator expressions and Streams, respectively, accomplish much the same thing. Honestly, if you've seen what LINQ compiles to, it looks an awful lot like a Java 8 Stream. Using Wikipedia's example of LINQ translation (https://en.wikipedia.org/wiki/Language_Integrated_Query#Language_extensions https://en.wikipedia.org/wiki/Language_Integrated_Query#Lang...): Written LINQ is: var results = from c in SomeCollection where c.SomeProperty < 10 select new {c.SomeProperty, c.OtherProperty}; It compiles to: var results = SomeCollection .Where(c => c.SomeProperty < 10) .Select(c => new {c.SomeProperty, c.OtherProperty}); And in Java 8: Stream<> results = someCollection.stream() .filter(c -> c.getSomeProperty() < 10) .map(c -> new AbstractMap.SimpleEntry<>(c.getSomeProperty(), c.getOtherProperty())); (of course, iterating over them is different; you just use a for loop in C#, but in Java you have to either use .forEach() or .collect() to a collection and then for over that) I think Streams have more LINQ in them than most people think. Disclaimer: it's been about a year since I've written Java 8, and this is off the top of my head (and the last time I used it, my employer's codebase had a class for pairs that was better than just SimpleEntry), so the code could be wrong. Edit: and just for completeness... the same in Python generator expressions: results = ((c.some_property, c.other_property) for c in some_collection if c.some_property < 10) Not very LINQ-like, but it serves the same purpose.
- rjbwork 10y agoIn the real world, MOST people are using the "it compiles to" version directly in the code. I certainly don't write the "from x in y select" version, except in the case of multiple hairy joins. Even those have become second nature at this point. It's just more readable, and turns it into an object pipeline/functional programming style instead. The Java 8 streams were pretty much directly taken from LINQ and given their traditional functional names.
- amyjess 10y ago> The Java 8 streams were pretty much directly taken from LINQ and given their traditional functional names. That was my point. I was disagreeing with olmo's suggestion that Java "systematically ignored" LINQ.
- moomin 10y agoFor me, LINQ is fundamentally list comprehensions on steroids. Way better than Pythons, about the same as using list functions in Haskell or F#, Java's finally caught up with its stream library. The LINQ to SQL stuff annoys me, because while it works, it's a painful disaster to implement yourself against your own data stores. Believe me, I've tried.
- koolba 10y ago> And if you need to support older databases (prior to SQL Server 2005), it gets worse: [some bad SQL] If you're stuck using a database version that first came out a decade ago, you've got bigger problems than legacy syntax for pagination. > Not only is this complicated and messy, but it violates the DRY principle (Don't Repeat Yourself). Here's same query in LINQ. The gain in simplicity is clear: var thirdPage = query.Skip(20).Take(10); If you're using OFFSET / LIMIT to do paging then you're doing it wrong. See here for the real way to handle paging for large result sets: http://use-the-index-luke.com/blog/2013-07/pagination-done-the-postgresql-way http://use-the-index-luke.com/blog/2013-07/pagination-done-t...
- pg_is_a_butt 10y agoIf you're using OFFSET / LIMIT to do paging then you might be doing it right. If you're not using OFFSET / LIMIT to do paging then you might be doing it wrong. you're all idiots.
- starik36 10y agoSometimes you have no choice. Like when an employer looks at the license cost of going from SQL Server 2005 to 2016 and figures that if it isn't broken, why fix it.
- pmontra 10y agoGreat link, thanks. Is PostgreSQL still the only db supporting that?
- MarkusWinand 10y agoThe right charts on slide 45 says "X" for SQLite. That changed recently: https://www.sqlite.org/releaselog/3_15_0.html https://www.sqlite.org/releaselog/3_15_0.html DB2 LUW has also decent row-values support: http://use-the-index-luke.com/blog/2014-11/seven-surprising-findings-about-DB2#blog-db2intro-rowvalues http://use-the-index-luke.com/blog/2014-11/seven-surprising-... Need to update the slides...
- NicoJuicy 10y agoWhat i mostly like about LINQ is IQueryable. It's awesome! I just design the IQueryable with if's, switches, ... and when i need to execute it. I use .ToList() The IQueryable is then translated to SQL and executed it.
- NicoJuicy 10y agoFollow up on my usage on Linq ( fyi) Now i design most of my pages through 1 service/method with a lot of if's and else and re-use that method all the time For example, a ecommerce-site i made has one function for querying the products, paging, searching, sorting by X, ...). Although, it get's rather complex lately, i wouldn't have it any other way. ( with complex, i mean i now also grouping them by category and category code, a category order number, a product order number, by product title ( varying by the current language), ... And yes, it' seperated in my service layer ;) and no, i won't change it because this is the fastest way untill now. Alternatively, you could use Extensions on IQueryable and IOrderedQueryable. Then you do something like db.Products.FilterBySearchTerm(searchTerm).OrderAllBy(sortPropertyName); But i like ProductHelper.GetProducts(filterWithSettings,SortOnSettings,GroupBySettings); more, mostly because it's easier when i need to customize all the methods because of some "sudden" Change Request that changes all the internal workings :( Also, if you are new to Linq To Sql. Don't forget DbFunctions / SqlFunctions for built-in SQL Functionality ( depending the EF version you are using). Eg. The LIKE operator has been added in the new EF. Also, you can always using DataContext.Database.Sql() for using standard SQL. ===== Pro Tip: DbContext is already a Repository Pattern if you are using DDD ! ===== PS. If you don't know LINQ. It generates a long SQL query and it's a bit slow, BUT it's very productive in development . Here's an example with both Generated SQL (commented between /* */ ) and Linq in one of my subbmitted issues on EF : https://github.com/NicoJuicy/EF-ContainsAndStartsWith/blob/master/EF-ContainsAndStartsWith.Test/UnitTest1.cs https://github.com/NicoJuicy/EF-ContainsAndStartsWith/blob/m... I like LINQ: Develop fast and improve when something executes slow :)
- OldSchoolJohnny 10y agoAnd then time goes by some guy comes along rips out the LINQ and fixes all that so it's performant under load with hand crafted sql queries.
- OldSchoolJohnny 10y agoIf the title says some piece of tech "beats" some other piece of tech can we just all act like proper engineers and not post it here at all and save us all some time?
- 4bpp 10y agoI was pretty bewildered by the convoluted way they posited for selecting a subrange of rows, but then I googled around and learned that LIMIT is a nonstandard MySQL extension. Huh. (Apparently, while LIMIT n,k is MySQL-only, MySQL, PostgreSQL and sqlite all support LIMIT k OFFSET n. So I assume this blog post is only really relevant for people who live in a Microsoft ecosystem?)
- rjbwork 10y agoWas talking to another person at work who is non technical but starting to dip his toes in the waters. He asked how to do just this and I had to go on a fairly long explanation, prompted by repeated questions, into the SQL standard, how that want added until near 3 decades after SQL's invention, vendor specific extensions and syntaxes etc. It's a pretty bizarre situation.
- Someone 10y agoIt took a while, but SQL Server 2012 introduced OFFSET/FETCH: SELECT * FROM items ORDER BY key OFFSET 100 ROWS FETCH NEXT 10 ROWS ONLY (https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx https://technet.microsoft.com/en-us/library/gg699618(v=sql.1...)
- siddboots 10y agoPart of it may be due to a deep problem with OFFSET in that although it can be convenient, there is no reliably efficient way to implement it. In fact, the only way it can possibly be efficient is if your data is fully ordered, and that ordering is indexed. As a result, I find it's better to just stick to the following pattern: select * from data where data.indexed_column > last_seen order by data.indexed_column desc limit 100
- ericls 10y agoElixir's Ecto is very similar to this. https://hexdocs.pm/ecto/Ecto.Query.html#content https://hexdocs.pm/ecto/Ecto.Query.html#content
- PeterisP 10y agoIt seems like an apples to oranges comparison - it is looking at the readability of code returning similar results, but it doesn't consider how these results are going to be generated, which is a major part of writing queries. Do the LINQ examples, especially the more complex ones, result in the same or better execution plans? Maybe they do, but the article doesn't tell, and without it it's kind of inappropriate to make judgments or even recommendations.
- NicoJuicy 10y agoActually, i think it's more about: - Prototype and use Linq first ( faster to develop and good enough queries in production) - Static Typed LINQ reduces mistakes ( a domain object changes, an error appears in your code), definatly later on the road when changing the domain. - Iterate and improve when i goes slow. Try to keep LINQ, but off course, SQL is faster.
- Someone 10y agoIn my experience, the SQL that LINQ generates typically is good, but LINQ may run part of the query or, rarely, even all of it client-side. For example, if you want the top N items ordered by f(x), and LINQ doesn't know how to map f(x) to a SQL Server built-in, it has to pull the entire set over the wire, and find the top N client-side. Obviously, if your table is huge, performance won't be good. That can even affect more than performance. For example, SQL Server orders GUIDs differently than .NET, and SQL Server's decimal isn't quite a IEEE float (https://msdn.microsoft.com/en-us/library/bb738633(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/bb738633(v=vs.110)....)
- godshatter 10y agoThis was my concern as well. When I saw the "query.Skip(20).Take(10)" syntax, I was wondering if the previous line that built the query variable downloaded all 15 bajillion rows in my Customers table of people whose names started with 'A' so it could get rows 21 through 30. If it actually only ends up creating some complex sql behind the scenes to get those ten rows, how horribly convoluted did it become and wouldn't it be better to write a straight SQL query to do the same thing, even if it's a little more complicated than the pseudo code? I guess I prefer more control. If my SQL query turns out to be slow, then I can learn from that and fix it. If the generated query from LINQ is slow, I have no recourse over it.
- fnovd 10y agoI couldn't help by roll my eyes at that title. ORMs and the like are great, but they still end up using SQL under the hood. LINQ is by no means the most aesthetic ORM, either (and half of the article is about much better LINQ looks than SQL). The headlines may as well read: "Why [interpreted language] beats assembly".
- __jal 10y agoSomeone seems to write one of these every few years about whatever the flavor of the month is. I recall reading one from sometime in the early 2000s about Hibernate that read the same way. And another one for one of the Perl ORMs before that. Yet somehow, dirty, ugly, hard-to-write SQL is still here while ORMs keep coming and going. And I have yet to see one without an escape hatch allowing raw SQL.
- ZenoArrow 10y ago>"And I have yet to see one without an escape hatch allowing raw SQL." I don't know where you've been looking, but from what I've seen it's an easy to find feature. To give two examples: https://docs.djangoproject.com/en/1.10/topics/db/sql/ https://docs.djangoproject.com/en/1.10/topics/db/sql/ https://github.com/StackExchange/Dapper https://github.com/StackExchange/Dapper
- __jal 10y agoUnless my reading ability is broken, we seem to be agreeing. I said I have never seen one that doesn't have one. My point being that ORMs can't fully replace SQL, and the proof is they all provide an escape hatch.
- Daishiman 10y agoThey provide an escape hatch because the language has support for features such as temporary tables, native DB functions and transaction control that are nonstandard and have a hundred gotchas, and are therefore not amenable to implement in an ORM. I have 30k lines of business logic written for Django that does not use that hatch even once.
- moomin 10y agoOnly it doesn't. The examples given _compile_ to SQL. So you're not comparing LINQ with SQL but LINQ-to-SQL (or the entity stuff) with SqlCommand. SQL's a pretty grim language, but it's the only language the database understands as a first-class citizen. Until someone designs a new foundation (like WebASM is doing), the rest is just syntactic sugar.
- skissane 10y ago> SQL's a pretty grim language, but it's the only language the database understands as a first-class citizen. Until someone designs a new foundation (like WebASM is doing), the rest is just syntactic sugar. SQL is an ugly COBOLesque veneer over an elegant relational calculus core. But the "new foundation" you speak of already exists, and has for decades. Competing query languages based on relational calculus are less ugly – QUEL, D, etc. Sadly, those better looking query languages have failed in the marketplace–ugly SQL won.
- rrdharan 10y agoI'm kind of curious why there aren't wrappers / APIs / libraries for these other query languages that convert them to SQL at execution time. Arguably that is what LINQ is anyway.. Perhaps these options exist and I've just never encountered them? It's surprising that what I most often seem to encounter in casual discussion is this sophie's choice dichotomy between using SQL directly versus an ORM.
- cwyers 10y agoI have looked at D, and read some of CJ Date's books. As far as I can tell, D doesn't solve any of the actual problems with SQL, like composibility and code reuse, and just solves Date's imagined problems about not following relational theory close enough.
- emmelaich 10y agoYeah, in my db class at Uni we learnt QUEL before we touched on SQL. It was clear then that QUEL was better in a number of ways. https://en.wikipedia.org/wiki/QUEL_query_languages https://en.wikipedia.org/wiki/QUEL_query_languages
- throwawasiudy 10y agoThere's one BIG problem with LINQ. I'll agree that the syntax is marvelous, a game changer. The problem is performance. It's gotten slightly better over the years but compared to an ORM with less abstraction like Hibernate it's still dog slow. Every MS project I've worked on was mostly LINQ...then a folder called "dirty SQL" for the heavy stuff. I'm not sure if it's due to the highly abstracted nature or just not making performance a priority but in my experience sane Hibernate queries are about 1/2 the speed of native SQL and LINQ is closer to 1/50. I hope and pray they can make the performance at least within an order of magnitude of raw SQL or even Hibernate so I can say goodbye to SQL forever.
- NicoJuicy 10y agoUse LINQ for development and production, when you need performance use Dapper. It shouldn' be too hard if you follow the DDD pattern. You can always use DataContext.Database.SQL(query) ofc
- throwawasiudy 10y ago> You can always use DataContext.Database.SQL(query) ofc that's pretty much our MO :) . Never used Dapper, how reliable is it? I ask because we use StackExchanges' Redis client for C# and it mysteriously crashes even after untold hours of debugging
- NicoJuicy 10y agoActually, haven't had any issues with it. So, it's safe to say that i find it very stable.
- deleted 10y ago[deleted]
- WorldMaker 10y agoAt a previous job I worked hard to prove that I could make LINQ queries perform within small tolerance of the window of hand-written SQL alternatives. Performance tuning LINQ is a science that I think escapes far too many people. Often it seemed to simply be mistakes that they wouldn't make in hand-written SQL, but they were writing LINQ too much like C# instead of enough like SQL.
- agentgt 10y agoI know many are going to disagree but I have come to despise almost all SQL generators unless they are as close to 1-1 as possible (aka Lukas Eder's jOOQ is acceptable in my book). Even more controversial... I don't want to make it any easier for developers to interact with the database unless it is absolutely correct and transparent. I know.. I know... how could I say such I thing! But you see I want every interaction with the our data repository... our precious data repository... that is usually the bottleneck... I want you to know WTF you are doing when you touch it. We (my company and probably others) are past the days of monolithic rapid prototype apps with ORMs. Now you pick a database and you learn the hell out of it because you can stick to it. Back in the day one of the reasons ORMs were so popular because companies would have to ship on premise ware that would have to work with multiple databases. With the cloud that is no longer the case. However I still think a lot of .NET shops come from the on premise mentality. Thus performance is less of concern (speed of release is more desired).
- NicoJuicy 10y agoHere's a linq to Lukas Eder's JOOQ https://www.jooq.org/ https://www.jooq.org/ I do like the syntax also though.
- alkonaut 10y agoHow many apps even deploy to the larger web and not just some intranet? It would surprise me if 99% of database backed applications weren't tiny-to-medium intranet and LOB type apps with very modest performance requirements. Hell, a pretty large number of Db apps are single user!
- brightball 10y agoI half agree with you and half totally disagree with you. The happy medium is a flexible ORM that automates the repetitive stuff but let's you call out to the higher level stuff...because if you don't have that your developers are going to end up building their own awful ORM-ish layer to automate the repetitive stuff anyway.
- agentgt 10y ago
- yellowstuff 10y agoI agree with the article and try to use write my queries with Linq instead of SQL almost always. The article says to avoid using Linq for bulk inserts, but for years I've been using an extension method to translate Linq to a bulk insert and it works fine. I forget where I found it. public static class DataContextExtension { public static void BulkInsertAll<T>(this DataContext dc, IEnumerable<T> entities) { using (var conn = new SqlConnection(dc.Connection.ConnectionString)) { conn.Open(); Type t = typeof(T); var tableAttribute = (TableAttribute)t.GetCustomAttributes( typeof(TableAttribute), false).Single(); var bulkCopy = new SqlBulkCopy(conn) { BulkCopyTimeout = 1200, DestinationTableName = tableAttribute.Name }; var properties = t.GetProperties().Where(EventTypeFilter).ToArray(); var table = new DataTable(); foreach (var property in properties) { Type propertyType = property.PropertyType; if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { propertyType = Nullable.GetUnderlyingType(propertyType); } table.Columns.Add(new DataColumn(property.Name, propertyType)); } foreach (var entity in entities) { table.Rows.Add( properties.Select( property => property.GetValue(entity, null) ?? DBNull.Value ).ToArray()); } bulkCopy.WriteToServer(table); } } private static bool EventTypeFilter(System.Reflection.PropertyInfo p) { var attribute = Attribute.GetCustomAttribute(p, typeof(AssociationAttribute)) as AssociationAttribute; if (attribute == null) return true; if (attribute.IsForeignKey == false) return true; return false; } }
- NicoJuicy 10y agoI'm actually doing something else when updating a webshop from a remote source.. I convert all objects that i import to a big SQL Query. Something like First query: UPDATE table SET active=0; Second ( big ) query: UPDATE table SET properties=values IF ROWCOUNT =0 INSER INTO table(properties)VALUES(values)
- deleted 10y ago[deleted]
- siddboots 10y agoI currently use a bit of LINQ, SQLAlchemy, Blaze/Odo, and a few other tools, depending on the project. However, primarily I'm still writing SQL in 2017 despite want of a prettier alternative. Here's the main reasons: * In pretty much every project I've ever worked on, there's a small, un-standardised set of database functions I rely on. I need to parse strings and dates, round to the start or end of the month or week, group and categorise values in order to build a dimension table. I've never found a SQL generator that can provide this, although I believe SQLAlchemy Core folks are working on it. * Planners are still not so good that you can ignore them altogether. I often rely on EXPLAIN to see why things are taking seconds instead of milliseconds, and I often end up looking for ways to trick the planner. If I'm using a SQL generator, I'm now trying to trick both the planner and the generator, neither of which I have direct control over. * If you're building a lot of complicated queries, setting up indexes and views, and so on, it's hard to get past the advantages of an IDE. Currently, the best tools are pretty much all database specific. Even just being able to quickly see your data in a tabular format is huge.
- jsd1982 10y agoTo your first point, LINQ-to-SQL can bind database functions for use directly in LINQ queries. I've used this first hand for parsing comma delimited string parameters into table values and joining from there in LINQ. I haven't used entity framework or any newer tech beyond LINQ to SQL but I'd have to believe such a trivial feature is present in them.
- siddboots 10y agoYou are right, and just about every ORM product gives you some way to get at raw database functions. It would be great, however, if they also offered a small RDBMS-agnostic library of functionality that would generate the correct database functions.
- jedberg 10y agoSo I'll admit I'm not at all familiar with LINQ and MSSQL, but from reading this, it looks like LINQ is just an ORM? And if that's the case, then of course it is easier and looks nicer than SQL -- that's kind of the point of an ORM. But I could show you a whole bunch of articles about Python and Ruby and Go ORMs too. Seems like an Apples to Oranges comparison.
- jordanlev 10y agoIt's not an ORM, more like an alternate way to write queries that's kind of embedded in the language itself (as opposed to SQL where you're putting together a string). If you're familiar with the Rails world, I'd say it's more like "Arel" than "ActiveRecord".
- jedberg 10y agoBut Linq literally generates SQL before sending it to the server: https://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.getcommand.aspx https://msdn.microsoft.com/en-us/library/system.data.linq.da... Doesn't that make it an ORM?
- contextfree 10y agoThat link is about LINQ to SQL, not LINQ proper * LINQ is a set of language features and libraries that help enable better ORMs, among other things * LINQ to SQL and Entity Framework are examples of ORMs that use the LINQ features
- recursive 10y agoNo, because you can use linq without even having a server or even a database. ORMs are one application of linq, but it's a more general concept.
- ungzd 10y agoAs I understand, it's ORM, but without 'mapper'. Every ORM has querying DSL, some of them are not producing objects at all. I think LINQ is that part of ORM. Some ORMs have poor querying ability: Rails, Django (more OOP approach), but some have powerful: Sequel, Sqlalchemy (more data processing approach). For example, that's Sequel querying DSL: http://sequel.jeremyevans.net/rdoc/files/doc/querying_rdoc.html http://sequel.jeremyevans.net/rdoc/files/doc/querying_rdoc.h... And I think LINQ is "language integrated" because C#, like Java, has poor DSL building possibilities. So they're added ORM-specific syntax right into language.
- skywhopper 10y ago"SQL is a very old language—invented in 1974." Not a good start. SQL is still in widespread use 43 years later because of how good it is. It's not a legacy weighing us down. Rather it has consistently proven its usefulness over and over again. Some of the constructs can feel awkward to be sure. But part of our impression of awkwardness is really just due to SQL's declarative nature, which makes the structure of queries look a lot different than the procedural languages we spend most of our time in. But it's not clear to me from this article that LINQ is even anything different that what already exists in most every modern application platform. It provides a cleaner syntax for some subset of common query patterns. Okay. There's a ton of SQL generators out there. Is LINQ doing something _else_ for us? This article doesn't say. I don't know, and I didn't learn that from this article. If you use C# or VB to write apps against relational databases, then by all means, use this to write your SQL. But don't pretend the SQL isn't there or isn't important. LINQ just places you one more potentially leaky abstraction away from your dataset.
- eeperson 10y ago> SQL is still in widespread use 43 years later because of how good it is. It's not a legacy weighing us down. I'm rather dubious of this claim. This is kind of like claiming the reason we use Javascript is because of how good it is. The awkwardness of SQL is not because it is declarative, otherwise LINQ would have the same awkwardness because it is also declarative. I think the real reason SQL is because database vendors have not made an effort to add support for other languages.
- Daishiman 10y agoBS. It's a language that can barely express subqueries and query aliases. Every ORM has shorthand syntax for expressing filters and order by statements that's way better than the SQL equivalents. It's barely composable. Do you want to build a query dynamically based on a set of conditions. Tough luck, use a query builder that's prettier anyway. Its syntax is not amenable to autocompletion. Join syntax is ugly on the eyes and hard to indent. Seriously, let's kill the love for SQL. I'd rather read queries written in EF Codd's original relational algebra syntax (https://en.wikipedia.org/wiki/Relational_algebra https://en.wikipedia.org/wiki/Relational_algebra) rather than embedding the abortion that is SQL in my code.
- ww2 10y agoBut LINQ is too slow comparing to vanilla SQL.
- gigatexal 10y agoSO LINQ is more terse but there were no performance metrics given. Given the same RDBMS with proper indexes, statistics, etc., all functioning properly which is quicker? I think it'd be murky if LINQ just pulls raw data to the client and then does the transformation there vs. on the server with SQL.
- douche 10y agoThere is a bit of an art to writing LINQ queries, but if you know what you're doing (i.e. spend a little time experimenting, with the traces turned on in EF or Linq to SQL that output the generated SQL, or a good profiler), you can write queries that are exactly the same as hand-tuned SQL. There's a little reflection overhead mapping results to types, but, you either make use of that, or have to write all that boilerplate yourself, so that's the tradeoff. Of course, if you don't know what you're doing, you can write some monstrous Linq queries that will be dog slow and exhibit all the worst n+1 behavior, pretty easily.
- spion 10y agoThe outer join example is not what I'd want LINQ to do. Most of the time it would be preferable to send two queries, one to retreive customers, the other to retreive high value purchases, then do the "joining" locally. Otherwise we're potentially fetching the customer data N times per customer (depending on the average number of high value purchases)
- quizotic 10y agoSigh. It's hard to know where to begin critiquing this. I guess the TL;DR would be something like: "For constrained but not atypical data models (no N:M relationships, foreign keys explicit in the schema, etc), it's possible to have a more concise syntax than SQL, with less impedance mismatch." But even that underwhelming statement is generous. In the 1980s, the object database claim to fame was less impedance mismatch, and ODI's "coding by deletion", but at least ODBs coupled that with claims to superior performance for network data models. Maybe it's just the grandiose title "LINQ beats SQL" that's so annoying. Simpler syntax would certainly be welcome for the relatively rare cases of humans generating SQL (I think most SQL is machine generated these days)... but only with a host of etceteris parabis conditions, prominently including performance.
- quizotic 10y agoIn the 70s, when I was all bushy-tailed, I cornered Gerry Sussman at MIT to tell him about "this new relational data model and SQL language". About two minutes into the conversation I saw him looking at me like "God, why have you chosen to torture me with this idiot." Or maybe it was the look you have when you are SURE that someone is telling you an elaborate joke and suddenly realize that no punch line is coming. LINQ: I'm looking at YOU :-/
- proyb2 10y agoI guess not many came across this guide. For LINQ to other languages: Swift Java Kotlin Clojure Dart Elixir https://github.com/mythz/swift-linq-examples https://github.com/mythz/swift-linq-examples
- lukaseder 10y agoThere will always be 1-2 queries that can be proven to work better in an alternative query language, other than SQL. For instance, I can surely find a couple of awesome graph queries in the Cypher query language (Neo4j). Or some JSON queries in N1QL (CouchBase). Back in the days, they tried to advocate that QUEL was a BetterThing™. Where's QUEL now? Same will be said of LINQ in a decade. Whereas SQL will still be there.