Skip to content
Advertisement

Generate a triangle of stars using mySQL recursive CTE

I’m trying to generate a triangle of stars in MYSQL that looks like this:

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

I’m using the following code to do in MYSQL

with recursive print_star(n) as (
    select '*'
    UNION ALL
    select concat(n,'*')
    from print_star
    where length(n)<5
)
select * from print_star order by length(n) desc

I get the error “Data too long for column ‘n’ at row 1”. Can anybody help me find out what’s wrong?

Advertisement

Answer

I guess MySQL is finicky about types. Try this:

with recursive print_star(n) as (
    select cast('*' as char(255)) n
    union all
    select concat(n, '*')
    from print_star
    where length(n) < 5
)
select *
from print_star
order by length(n) desc
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement