views:

372

answers:

6

I'm in the process of creating a table and it made me wonder.

If I store, say cars that has a make (fx BMW, Audi ect.), will it make any difference on the query speed if I store the make as an int or varchar.

So is

SELECT * FROM table WHERE make = 5 AND ...;

Faster/slower than

SELECT * FROM table WHERE make = 'audi' AND ...;

or will the speed be more or less the same?

A: 

If you turn on indexing on either of the fields, it will be faster. As for your question, i think intis faster than varchar.

Sarfraz
+1  A: 

In general the int will be faster. The longer is the varchar the slower it gets

anthares
+1  A: 

Hint: If the possible values for the field make will never (or rarely) change, you can use ENUM as a compromise. It combines good speed with good readability.

Larry_Croft
Interesting, How will the speed difference be between ENUM and int?
googletorp
Does PostgresSQL have an `enum` data type? I though it was MySQL specific.
Robert Munteanu
Postgres has ENUM, but I don't think it's implemented quite the same way as MySQL. http://www.postgresql.org/docs/current/static/datatype-enum.html
googletorp
Performance wise, ENUM should perform more or less the same as int in the search field, but as varchar in the target list (because it has to transfer the whole string to the client for matched rows, not just the int)
Magnus Hagander
+4  A: 

Int comparisons are faster than varchar comparisons, for the simple fact that ints take up much less space than varchars.

This holds true both for unindexed and indexed access. The fastest way to go is an indexed int column.


As I see you've tagged the question postgreql, you might be interested in the space usage of different date types:

Robert Munteanu
You are referring to pg 7.4. In modern versions, they take up 1byte+length if you have <126 bytes. Also note that the reason strings are much slower is often that collation-sensitive comparison is hugely expensive - not that the string takes more space. But the end result is the same, of course.
Magnus Hagander
@Magnus - thanks for the heads-up. Feel free to edit my answer as I see you have enough rep points.
Robert Munteanu
+3  A: 

It will be a bit faster using an int instead of a varchar. More important for speed is to have an index on the field that the query can use to find the records.

There is another reason to use an int, and that is to normalise the database. Instead of having the text 'Mercedes-Benz' stored thousands of times in the table, you should store it's id and have the brand name stored once in a separate table.

Guffa
+1  A: 

Index or not, int is a lot faster (the longer the varchar, the slower it gets).

Another reason: index on varchar field will be much larger than on int. For larger tables it may mean hundreds of megabytes (and thousands of pages). That makes the performance much worse as reading the index alone requires many disk reads.

Konrad Garus