4

Why do linq to sql queries starts with the FROM keyword unlike regular SQL queries?

Glenn
  • 8,932
  • 2
  • 41
  • 54
Joe
  • 145
  • 1
  • 9
  • If you use some intellisense provider while writing an SQL statement (ie: Apex SQL Complete, Redgate SQL prompt, or SSMS with a recent version of SQL server), you would see that the intellisense cannot suggest you something until it gets to the "from" - select * from. If classic SQL began with "from" then you would have intellisense there too. It was not an issue when "intellisense" didn't exist but with .Net intellisense plays a big role in code writing. – Cetin Basoz Sep 19 '15 at 13:19

2 Answers2

8

LINQ mimics Logical Query processing in SQL you have:

8. SELECT
9. DISTINCT
11. TOP
1. FROM
2. ON
3. JOIN
4. WHERE
5. GROUP BY
6. WITH CUBE/ROLLUP
7. HAVING
10. ORDER BY
12. OFFSET/FETCH

But actually it executed like:

1. FROM
2. ON
3. JOIN
4. WHERE
5. GROUP BY
6. WITH CUBE/ROLLUP
7. HAVING
8. SELECT
9. DISTINCT
10. ORDER BY
11. TOP
12. OFFSET/FETCH

Many people is not aware of it and made simple mistakes like:

SELECT col AS alias_name
FROM tab
WHERE aliass_name > 10;

And ask why it doesn't work. Because they assume that the order is like they write it. LINQ is better at this matter.

See also Logical Query Processing and BOL:

Logical Processing Order of the SELECT statement

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.

FROM

ON

JOIN

WHERE

GROUP BY

WITH CUBE or WITH ROLLUP

HAVING

SELECT

DISTINCT

ORDER BY

TOP
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
  • 1
    There is great explanation about it in book `T-SQL Querying by Itzik Ben-Gan, Adam Machanic, Dejan Sarka, Kevin Farlee` in chapter one why it has to be in that order. – Lukasz Szozda Sep 19 '15 at 13:28
0

Some documentation regarding your question is available here and they says that It is more similar to "foreach". However this is a good place to start and understand what is LINQ and different types of LINQ.

You will commonly find following types of LINQ everywhere. Read here.

  1. LINQ (Linq to Objects)
  2. DLINQ (Linq to SQL)
  3. XLINQ (Linq to XML)
Amnesh Goel
  • 2,617
  • 3
  • 28
  • 47