2

How to generate a sequence of SQUARE numbers till 10 in MYSQL? (1^2,2^2, etc)

I was only able to generate a numerical sequence from 1 to 10.

WITH RECURSIVE cte (n) AS
(
  SELECT 1
  UNION ALL
  SELECT (n + 1) FROM cte WHERE n < 10
)
SELECT n FROM cte;

But if I add the POW() function, the result will be

WITH RECURSIVE cte (n) AS
(
  SELECT 1
  UNION ALL
  SELECT POW((n + 1),2) FROM cte WHERE n < 10
)
SELECT n FROM cte;

RESULT: 1 4 25

Ken White
  • 123,280
  • 14
  • 225
  • 444
Mouse12328
  • 23
  • 3

1 Answers1

2

you need to square the resul of the cte

WITH RECURSIVE cte (n) AS
(
  SELECT 1
  UNION ALL
  SELECT (n + 1) FROM cte WHERE n < 10
)
SELECT POW(n,2) FROM cte;
POW(n,2)
1
4
9
16
25
36
49
64
81
100

fiddle

nbk
  • 45,398
  • 8
  • 30
  • 47
  • So the square should be added to the result? not in the WITH construction? – Mouse12328 Feb 11 '23 at 18:42
  • yes as you want the square from the integers 1 till 10, you need first generate then numbers and the square them as you can see in the fiddle. – nbk Feb 11 '23 at 18:43