18

What's the best way to store tags for a record? Just use a varchar field? What about when selecting rows that contains tag x? Use the like operator?

thanks!

1

3 Answers 3

16

Depends on two things:
1) The amount of tags/tagged records
2) Whether or not you have a religious opinion on normalization :-)

Unless dealing with very large volumes of data, I'd suggest having a 'Tags' table mapping varchar values to integer identifiers then second table mapping tagged records to their tag ids. I'd suggest implementing this first, then check if it doesn't meet your performance needs. In that case, keep a single table with a id for the tagged row and the actual text of the tag, but in this I'd suggest you use a char column as it will kill your query if the optimizer does a full table scan against a large table with a varchar column.

2
  • agree, then you can rename tags easily. Sep 28, 2008 at 4:40
  • 3
    Use NVARCHAR or NCHAR column for unicode support else you want only support ASCII charters in the tags.
    – Horcrux7
    Sep 28, 2008 at 13:53
5

No, it is generally a bad idea to put multiple pieces of data in a single field. Instead, use a separate Tags table (perhaps with just a TagID and TagName) and then, for each record, indicate the TagID associated with it. If a record is associated with multiple tags, you will have duplicate records with the only difference being TagID.

The advantage here is that you can easily query by tag, by record, and maintain the Tags table separately (i.e. what if a tag name changes?).

1
  • 3
    You don't want duplicate records either, you want a TagRecord table matching TagIds to RecordIds in this case. Mar 15, 2009 at 22:58
4

Use a tags table with the smallest allowable primary key. If there are less than 255 tags use a byte (tinyint) or else a word (smallint). The smaller the key the smaller and faster the index on the foreign key in the main table.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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