I am new to queries that include declaring variables in MySQL. I saw different styles, and I donβt quite understand what they really do. I have questions about what they actually do.
1)
set @row:=0; SELECT name, @row: =@row + 1 AS rownum FROM animal
2)
SELECT name, @row: =@row + 1 AS rownum FROM (SELECT @row:= 0) c, animal
Both return the same:
name rownum || cat || 1 || || cat || 2 || || dog || 3 || || dog || 4 || || dog || 5 || || ant || 6 ||
What are the differences in the above two queries, and which of them regarding their volume, efficiency, coding habits, use cases?
3) Now, if I do this:
set @row:=0; SELECT name, @row: =@row + 1 AS rownum FROM (SELECT @row:= 123) c, animal
I get
name rownum || cat || 124 || || cat || 125 || || dog || 126 || || dog || 127 || || dog || 128 || || ant || 129 ||
Therefore, this does not mean that the internal initialization of variables overrides the external initialization and, therefore, leaves it redundant (and, therefore, is it always better to use it for initialization in SELECT ?
4) If I just do:
SELECT name, @row: =@row + 1 AS rownum FROM animal
I get
name rownum || cat || NULL || || cat || NULL || || dog || NULL || || dog || NULL || || dog || NULL || || ant || NULL ||
I understand that since row not initialized. But if I run any of the other queries (can the row variable be initialized?), I see that the row variable is incremented every time I run the above query. That is, this gives me the result the first time I run:
name rownum || cat || 1 || || cat || 2 || || dog || 3 || || dog || 4 || || dog || 5 || || ant || 6 ||
and then when you restart it gives in
name rownum || cat || 7 || || cat || 8 || || dog || 9 || || dog || 10 || || dog || 11 || || ant || 12 ||
So row is stored somewhere? And what is its scope and life expectancy?
5) If I have a request like this:
SELECT (CASE WHEN @name <> name THEN @row:=1 ELSE @row: =@row + 1 END) AS rownum, @name:=name AS name FROM animal
This always gives the correct result:
rownum name || 1 || cat || || 2 || cat || || 1 || dog || || 2 || dog || || 3 || dog || || 1 || ant ||
So this does not mean that it is not always necessary to initialize a variable at the top or in SELECT depending on the query?