3

I want to know if is possible to transform a numeric return (INT column) in a sequence of symbols direct in a MySQL SELECT.

My table is like below:

| ID        | category |
|-----------|----------|
| product_1 | 5        |
| product_2 | 4        |
| product_3 | 3        |

I want a SQL SELECT like SELECT ID, some_mysql_fancy_func(category,'*') AS symbol_category FROM MyTable that could returns the following:

| ID        | symbol_category |
|-----------|-----------------|
| product_1 | *****           |
| product_2 | ****            |
| product_3 | ***             |

Is it possible?

I can do it programmatically, but this is not my intention, I want some built-in (or even custom) function that can achieve this result direct in the SELECT statement.

5
SELECT ID,
       REPEAT('*', IFNULL(category, 0)) AS SymbolCategory
    FROM ...

This assumes you want NULL to be equivalent to 0.

4

Maybe use LPAD or RPAD?

CREATE TEMPORARY TABLE tt (category INT UNSIGNED);
INSERT INTO tt(category)
VALUES
(5);

select lpad('*',category,'*')
from tt;

Granted, this wouldn't work for 0, or you'd have to replace single * with a NULL value. But an idea at least.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.