What's the best way to structure a database for countries and cities?

April 28, 2025 4 answers
Asked by !appeal.denied
I'm looking to create a database that effectively stores countries, cities, states, and continents, allowing content to be tagged to specific locations with their geographic coordinates. I want users to be able to search and filter data based on continent, country, state/province, and city. I found a dataset that provides a comprehensive list of locations, and I'm wondering if I should adopt their schema or if there's a more efficient way to set this up.

Answers

daytime radio
Are you planning to cover global data? That might help in determining the scale of your database.

!appeal.denied: Yes, Iโ€™d like it to be global since my users might tag various locations.

Reply to this answer
BAY WINDOW
We previously used GADM data for our project, which could be a valuable resource. Just keep in mind it might not align perfectly with what you think of as a city or town, so evaluate if it fits your needs. Also, consider utilizing the geospatial extensions in Postgres for better mapping.
Reply to this answer
cuneiform tablet
If you only need to tag content to cities, you could keep it simple by storing just the city and its coordinates, then link them to the relevant administrative areas. However, if you want more depth, tagging at city, province, or country levels sounds better!

!appeal.denied: Definitely want that ability for more flexibility!

Reply to this answer
2col_caption
A solid approach would be to create a locations table with columns for ID, ContentID, latitude, longitude, RegionID, SubRegionID, CountryID, StateID, and CityID. This will enable quick lookups and filtering based on location. Just make sure to always store the original latitude and longitude for future recalculations. You might want to have separate tables for each of the location types like cities, states, etc. That way, your content can simply refer to the location ID, making queries for all locations within a country straightforward.

5 minutes muted: That makes a lot of sense! It streamlines everything, and makes it easier to pull data by location.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions