Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any advantages to use varchar over decimal for Price and Value

I was arguing with my friend against his suggestion to store price, value and other similar informations in varchar.

My point of view are on the basis of

  1. Calculations will become difficult as we need to cast back and forth.
  2. Integrity of the data will be lost.
  3. Poor performance of Indexes
  4. Sorting and aggregate functions will also need casting

etc. etc.

But he was saying that in his previous employement everybody used to store such values in varchar, because the communication between DB and the APP will be very effective in this approach. (I still cant accept this)

Are there really some advantages in storing such values in varchar ?

Note : I'm not talking about columns like PhoneNo, IDs, ZIP Code, SSN etc. I know varchar is best suited for those. The columns are value based, and will for sure be involved in calculations some way or other.

like image 385
The King Avatar asked Aug 03 '10 13:08

The King


People also ask

Which datatype is the best suitable for item price?

The best type for price column should be DECIMAL. The type DECIMAL stores the value precisely. For Example - DECIMAL(10,2) can be used to store price value. It means the total digit will be 10 and two digits will be after decimal point.

Can VARCHAR store decimal values?

The short answer is: No, it will hurt performance. The longer answer: VARCHAR fields are variable length, meaning, that the formatting of the database blocks cannot pre-account for the size of the data filling in there.

Which data type is best for currency amounts in SQL Server?

If you need the highest precision, a DECIMAL can use up to 17 bytes for each value. Generally though, I like using DECIMAL(19,4) for currency, which needs 9 bytes and can store numbers 19 digits wide, where the last four digits are after the decimal place.

Can I use VARCHAR for numbers?

VARCHAR the variable-length character data typeThey can store characters, numbers, and special characters just like a CHAR column and can support strings up to 8000 bytes in size. A variable-length column only takes up the space it needs to store a string of characters, with no spaces added to pad out the column.


1 Answers

None at all.

Try casting a values back and too and see how much data you lose.

DECLARE @foo TABLE (bar varchar(30))
INSERT @foo VALUES (11.2222222222)
INSERT @foo VALUES (22.3333333333)
INSERT @foo VALUES (33.1111111111)
SELECT CAST(CAST(bar AS float) AS varchar(30)) FROM @foo

I would also mention that his current employment does things differently... he isn't at his previous employment any more....

like image 106
gbn Avatar answered Nov 15 '22 11:11

gbn