by noisem4ker · 3y ago · 0 comments
No, it selects a literal integer 1 in all SQL engines.
You can, and do, select any expressions, not only column names.
CategoryId,
CategoryId + 1,
1,
sqrt(CategoryId * ProductId),
Column names alone are expressions too.SQL queries return not columns from table, but a result of relational operations with new columns specified by expressions. What a downvoted user itt cannot accept is that 1 is as meaningful as * or <colname> in general and is an idiom for “columns don’t matter here, only [the number of] rows”. It’s like [[1]].length vs [[id, …]].length. Saying “it’s not my data” is misunderstanding what that data is.
I find this very useful when I need to insert some fixed data alongside some data from the database. I'll then use
insert into TableX(Key, TotalWeight, Name, Category)
select Key, sum(Weight), 'foo', 42 from TableY where Key = 1234 group by Key
or something like that. Usually the source of the fixed data is in a spreadsheet, so I just use Excel to generate the SQL statements.In SQL Server at least, no, it literally means select the integer 1. In the ORDER BY clause, it does mean to order by ordinal position, but that's not a great thing to glorify, since ordinal position is not necessarily stable. I think other dialects like MySQL might allow GROUP BY 1, but that's not a great thing to glorify either.
> SELECT 1 means "select the first column"
interesting.. in postgres this actually gives you a single-column value of 1, in an unnamed column... I haven't used other DBMSes much but expected similar behaviour