When to use a View instead of a Table?
When should a View actually be used over an actual Table? What gains should I expect this to produce?
Overall, what are the advantages of using a view over a table? Shouldn't I design the table in the way the view should look like in the first place?
Solution 1:
Oh there are many differences you will need to consider
Views for selection:
- Views provide abstraction over tables. You can add/remove fields easily in a view without modifying your underlying schema
- Views can model complex joins easily.
- Views can hide database-specific stuff from you. E.g. if you need to do some checks using Oracles SYS_CONTEXT function or many other things
- You can easily manage your GRANTS directly on views, rather than the actual tables. It's easier to manage if you know a certain user may only access a view.
- Views can help you with backwards compatibility. You can change the underlying schema, but the views can hide those facts from a certain client.
Views for insertion/updates:
- You can handle security issues with views by using such functionality as Oracle's "WITH CHECK OPTION" clause directly in the view
Drawbacks
- You lose information about relations (primary keys, foreign keys)
- It's not obvious whether you will be able to insert/update a view, because the view hides its underlying joins from you
Solution 2:
Views can:
- Simplify a complex table structure
- Simplify your security model by allowing you to filter sensitive data and assign permissions in a simpler fashion
- Allow you to change the logic and behavior without changing the output structure (the output remains the same but the underlying SELECT could change significantly)
- Increase performance (Sql Server Indexed Views)
- Offer specific query optimization with the view that might be difficult to glean otherwise
And you should not design tables to match views. Your base model should concern itself with efficient storage and retrieval of the data. Views are partly a tool that mitigates the complexities that arise from an efficient, normalized model by allowing you to abstract that complexity.
Also, asking "what are the advantages of using a view over a table? " is not a great comparison. You can't go without tables, but you can do without views. They each exist for a very different reason. Tables are the concrete model and Views are an abstracted, well, View.