While learning about Database Fundamentals, I've been trying to understand the difference between Tables and Views and why and when we should choose one over the other. Here is what I've found out so far...
Structured data is stored in databases. Within these are schemas, which each contain database objects. These objects can include Tables, Views or Materialised views.
Tables:
The main thing to know about Tables is that they store data. They will remain static until modified, which can be done manually or by setting up automation within the pipeline. Because of this, they have excellent query speed. Tables have storage costs but lower query costs.
Views:
Unlike tables, Views store queries, not physical data. This means they will only be as fast as the query itself. Unlike tables they are dynamic, so will always show the real-time changes in the underlying tables, but they will have to re-run the query each time they are used. Views have compute costs but no storage costs.
Materialised Views:
Just to throw in another type of object, in some warehouses we can also choose to use Materialised Views. These are essentially a hybrid of the two, running a query like a view, while saving the resulting data like a table, refreshing on a schedule. They are stored like a table, but fresher like a view. While this can be a positive, it also means they do take up storage space.
That's pretty much it, but how do we know when to use each one?
There is no precise answer as to when which is better at which stage of a pipeline, and there will be different justifications for each. Ultimately it comes down to what is going to be most cost efficient. If the data is going to be used a lot, but doesn't change often, then maybe a table. If the query is simple but there is a large amount of underlying data, maybe we want a view. As ever, the way to choose the best option is to have a strong contextual understanding, knowing the structure of the data and the requirements of the end point. By establishing these, you'll be able to work backwards and determine what fits best at each step of your pipeline.
The answer is... it depends.
