1

To test -

CREATE TABLE shop (
 article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,
 dealer CHAR(20) DEFAULT '' NOT NULL,
 price DOUBLE(16,2) DEFAULT '0.00' NOT NULL,
 PRIMARY KEY(article, dealer));
INSERT INTO shop VALUES
 (1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,'B',1.45),
 (3,'C',1.69),(3,'D',1.25),(4,'D',19.95);

My Query -

SELECT MAX( article ) AS article
FROM shop

It outputs -

+---------+
| article |
+---------+
| 4 |
+---------+

However I was expecting -

+---------+
| article |
+---------+
| 0004 |
+---------+

I tried to CAST but no luck.

Let me know how could I handle this.

FYI- I tried to create SQL Fiddle for this but fiddle is not filling Zeros http://sqlfiddle.com/#!2/4abbe/24 when executed SELECT * FROM shop

However in phpmyadmin its working correctly with ooo's fill.

MySQL setting - Server version: 5.5.16 PHPMYADMIN setting - Version information: 3.4.5

My table data representation -

table data

asked Apr 19, 2013 at 6:22
2
  • If leading 0s are significant for your data, it doesn't sound like INT is the right data type to use. Commented Apr 19, 2013 at 6:27
  • @Damien_The_Unbeliever then should i store it in VARCHAR or any other for leading zeros? your suggestion ? Commented Apr 19, 2013 at 6:30

3 Answers 3

2
SELECT LPAD(MAX( article ), 4, '0') AS article FROM shop; 

;-)

answered Apr 19, 2013 at 6:27
Sign up to request clarification or add additional context in comments.

1 Comment

Hey, mate. I know that you mean. =/
2

You can use LPAD().

SELECT LPAD(article, 4, 0) FROM table_name;
answered Apr 19, 2013 at 6:27

Comments

1

When you are using ZEROFILL it is actually storing it in database in that form but while retrieving it truncates the zero. So you should use:-

SELECT LPAD(MAX( article ), 4, '0') AS article FROM shop; 
answered Apr 19, 2013 at 6:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.