Waiting for SQL:202y: Group by All

6 days ago (peter.eisentraut.org)

Let me reference fields as I create them:

  select xxxxx as a
       , a * 2 as b

  • SQL needs to have `select` as the _last_ part, not the first. LINQ has had this for 2 decades by now: "from table_a as a, table_b as b where ... select a.blah, b.duh".

    • This is not relevant to GP's point. This is a separate topic, which... I don't really care, but I know a lot of people want to be able to write SQL as you suggest, and it's not hard to implement, so, sure.

      Though, I think it might have to be table sources, then `SELECT`, then `WHERE`, then ... because you might want to refer to output columns in the `WHERE` clause.

      1 reply →

this seems to ignore the fact that you can group by a column that isn't in the select statement.

it's not something that i've found a particular use for, but it IS a thing you can do.

So, why not a SORT BY ALL or a GROUPSORT BY ALL, too? Not always what you want (e.g., when you're ranking on a summarized column), but it often alphabetic order on the GROUP BY columns is just what the doctor ordered! :-)

Also just let me reference the damn alias in a group by, FUCK

  • At least in PostgreSQL, both by alias and ordinal are possible:

      localhost(from SCB-MUSE-BOXX).postgres.scb.5432 [Sun Nov 16 12:02:15 PST 2025]
      > create table test (a_key integer primary key, a_group integer, a_val numeric);
      CREATE TABLE
      Time: 3.102 ms
    
      localhost(from SCB-MUSE-BOXX).postgres.scb.5432 [Sun Nov 16 12:02:25 PST 2025]
      > insert into test (a_key, a_group, a_val) values (1, 1, 5.5), (2, 1, 2.6), (3, 2, 1.1), (4, 2, 6.5);
      INSERT 0 4
      Time: 2.302 ms
    
      localhost(from SCB-MUSE-BOXX).postgres.scb.5432 [Sun Nov 16 12:02:58 PST 2025]
      > select a_group AS my_group, sum(a_val) from test group by my_group;
       my_group | sum
      ----------+-----
              2 | 7.6
              1 | 8.1
      (2 rows)
      
      Time: 4.124 ms
      localhost(from SCB-MUSE-BOXX).postgres.scb.5432 [Sun Nov 16 12:03:15 PST 2025]
      > select a_group AS my_group, sum(a_val) from test group by 1;
       my_group | sum
      ----------+-----
              2 | 7.6
              1 | 8.1
      (2 rows)
      
      Time: 0.360 ms

  • I think it should be not only in GROUP BY, but in every context, e.g., inside expressions in SELECT, WHERE, etc.

  • PostgreSQL and DuckDB support this, which makes MSSQL feel like a dinosaur in context.

  • Some do. It would also be nice to reference by ordinal number similar to order by. Very handy for quick and dirty queries. I can see the issue though that people start to lean on it too much.