I am trying to query a column of type (int) into a string of format (000). For example: If the column value was 1 then the output of the query should be 001
Asked
Active
Viewed 1,514 times
0
-
1How are you doing it? Which DBMS? Post your attempt please. – shree.pat18 Jan 06 '15 at 10:25
-
I apply it on SQL 2000 and SQL 2012 – Ala Jan 06 '15 at 10:36
2 Answers
1
Depends on which database engine you use.
In SQL Server 2012 and higher:
SELECT FORMAT(7, 'D3')
The result is this string:
007
For older versions of SQL Server, see the accepted answer by shree.pat18
For MySQL, look here: Adding a leading zero to some values in column
For PostgreSQL, look here: Padding zeros to the left in postgreSQL

Community
- 1
- 1

Ruud Helderman
- 10,563
- 1
- 26
- 45
-
You are right. I edited my answer accordingly. Thanks for your comment. – Ruud Helderman Jan 06 '15 at 13:22
0
Try this:
select right('000' + convert(varchar(3), intcolumn), 3) from yourtable
Note that the output is of type varchar
. If you will need this output as a number somewhere else, I would suggest doing the formatting in your UI code and keeping it as a number in the query.

shree.pat18
- 21,449
- 3
- 43
- 63