sqlparser-rs / sqlparser-rs

Extensible SQL Lexer and Parser for Rust
Apache License 2.0
2.7k stars 508 forks source link

`FROM` first in `SELECT` statements #1400

Open samuelcolvin opened 2 weeks ago

samuelcolvin commented 2 weeks ago

I've had (what I think is) a very clever idea to improve SQL (bare with me, I know that sounds mad 😱).

It's as simple as this: we move the "FROM" clause to the start of select statements, so:

This has two big advantages:

  1. It's mean SQL language servers can be much much more helpful — it becomes possible to suggest column names in the SELECT clause because the user has already provided the table name — e.g. we can make sensible suggestions at FROM my_table SELECT a[CURSOR]
  2. It's (arguably) easier to read - example: "We got roads, concrete, plumbing and calendars from the Romans" is quite hard to interpret the first time you read it because you need to keep all the things in your head without knowing the context, while "From the Romans we got roads, concrete, plumbing and calendars" is much easier to understand because you already have the context of the Romans when you read/hear the list. The same goes for FROM users SELECT id, name, created_at. The point is that SELECT ... FROM ... syntax follows some natural language which only puts the "from" at the end to developer suspense, at the cost of less easy understanding, we don't want suspense, we want ease

I also think it would make CTEs read much better: with t as (select 1 as a) from t select a since using t is directly after the CTE.

Unlike alternatives to SQL like PRQL and EdgeQL:


So here's my feature request: an optional flag (allow_leading_from) which allows the FROM clause to come before SELECT. It can even be a feature so it's compiled out for those who don't want it.

WDYT?

adriangb commented 2 weeks ago

See https://duckdb.org/2023/08/23/even-friendlier-sql.html#from-first-in-select-statements

samuelcolvin commented 2 weeks ago

Oh nice, I had no idea.

samuelcolvin commented 2 weeks ago

Thanks @adriangb, now I can just make the feature request "support duckdb 'from first' syntax".

samuelcolvin commented 2 weeks ago

I have a branch that supports this, I'll create a PR when I have time.

Some related link