I need to know what is the best practice for storing the following data:
Lets say I have multiple garages, each garage holds different types of vehicles with totally different attributes (e.g. planes, tanks, ships, bikes). I need to query all the vehicles in one garage, including their attributes.
What would be a good practice to store and query this data with one universal query? Store all vehicles in one table, with every possible attribute?
Or create multiple tables, each for a specific type of vehicle? Then, how do I query all the different vehicles of one garage, without knowing which type they are?
Is something like this even possible with a single query? Or do I have to create multiple queries to get the data?
I hope you understand what I am trying to achieve.
This sure is possible, however it involves some planning when creating your datamodel.
There are, as you already mentioned, different ways to implement sub-type-super-type relations (aka Inheritance).
1.) All in one Table
In this case I would model your problem somewhat like this:
For the Type you could give IDs and have a separate table where you relate the IDs to Names or simply write the names there (not a very clean solution!).
Btw.: If you want to have multiple inheritance (which I guess you don’t need for vehicles) you could also make Type a bitmask.
Personally I don’t really like this approach, but it is quite ok to do this. Oracle i.e. suggests this in their study material. Also it’s the simpler solution for your one query problem:
2.) Table for each Subtype
To me, this feels like the cleaner solution, because you have less NULL values, but you need a bit more work to get everything in one query.
This theoretically allows for multiple inheritance and you should write a trigger allowing only subtype.
SQL in this case:
Or if you have more types you could put the ugly stuff into a View:
EDIT:
A word on notation: When I put _PK behind a name it referes to the column being a primary key. _FK to a foreign key.