Could someone explain me why this code creates automatic 20 lines?

Hello everyone! I was trying to solve some internet exercises these days, and got some doubts on this one here.

represents a pattern drawn by Julia in R rows. The following pattern represents P(5) :

* * * * * 
* * * * 
* * * 
* * 
*

Write a query to print the pattern P(20) .

I found on internet the solution

SELECT REPEAT(’* ', @NUMBER := @NUMBER - 1) FROM information_schema.tables, (SELECT @NUMBER:=21) t LIMIT 20

But I really didn`t understand this code. Can someone explain me this code, and how is this code able to create 20 new lines?

Thankss.

@text5047161651,

Excellent question!

In SQL, when you just SELECT a number or string with no FROM clause, the query will return one row with that value. However, when you SELECT a number or string FROM a certain table, the query will return that value once per row for every row in the table.

In this query…

SELECT REPEAT('* ', @NUMBER := @NUMBER - 1) 
FROM 
  information_schema.tables, 
  (SELECT @NUMBER:=21) t 
LIMIT 20;

…you are selecting FROM the table called information_schema.tables, which generally has more than 20 rows. Thus, the number or string you select from that table will appear in the same number of rows that information_schema.tables contains.

Now, because the SELECT statement decreases @NUMBER by 1 every time, each row shows one less star. So, technically, after 20 rows, each following row contain '* ' less than one time (@NUMBER will be less than one). This will show up as empty rows, which is why you limit the query to the 20 rows that actually contain something.

Hope this helps!

Happy coding.

1 Like