Search code examples
sqlmysqlrecursive-cte

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?


Solution

  • 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