Murco
Murco

Reputation: 193

Join vs text search on suburb list

Working with MySQL database.

I have a store table. The store table has at least 80,000 records. A user can search the store table by selecting a suburb from a drop down list. Would I be better off creating a suburb table (see below) and searching the store table for the suburb id or keeping it as a text match on the store table?

Store
- id
- name
- suburb_id

Suburb
- id
- name

I am guessing that using the store_id foreign key, I can create and index?

Upvotes: 2

Views: 74

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270727

You are likely better off to create the suburb table as you have suggested. Database normalization best practice here would be to store the suburb_id with the store record. If it is an integer id, you are likely to get much better performance out of it than relying on a text match even if the CHAR()/VARCHAR() column containing is indexed.

Normalizing your suburb table will give you some added benefits when querying as well. If you ever added additional columns (besides just id, name) to the suburb table, you could, by way of a JOIN query for stores having different suburb attributes or aggregates. (Not that your end users would need this necessarily, but you could use it)

For example, how many stores per suburb? (you could do this with a text field as well)

SELECT
 Suburb.name,
 count(*) as numstores 
FROM Store LEFT JOIN Suburb ON Store.suburb_id = Suburb.id
GROUP BY Suburb.name

Or if you added the population to your Suburb table, which stores are in suburbs with popultaion > 40000. You could not do this with a text field alone in your Store table.

SELECT 
  Store.id, 
  Store.name
From Store JOIN Suburb ON Store.suburb_id = Suburb.id
WHERE Suburb.population >= 40000

Normalization will also help if you wish to store a user's suburb preference for later use. Hypothetically, in your Users table, you would add a column as a foreign key reference to Suburb.id. Making use of the ON DELETE SET NULL foreign key actions, if a suburb is removed from the database that change could be immediately reflected in your user's preference.

Upvotes: 1

Sico
Sico

Reputation: 1183

first option is better for normalisation as you won't have to update many records if a suburb name changes

Upvotes: 0

Related Questions