I’m working on building a MySQL database and I’m thinking that rather than encode a bunch of complex join queries in the front end I’ll create a view for any queries I need and then have all the front end code do simple SELECT whatever FROM some_view WHERE something=5; queries.
It seems like a great idea as it abstracts away the underlying schema so the front end doesn’t need to know about it and given that MySQL can merge views into queries I’d think this would be no less efficient than the more direct solution.
Now for the question: Is this a stupid idea for some reason I’m not spotting?
Note: This would only go two layers deep, e.i. views would only reference tables, never views.
Views can simplify the amount of text you need to create a query, but layering views on top of one another is a bad practice.
That encapsulation also risks poor performing queries, because the views need to be executed before being able to join to one another–all that logic inside might not apply to what you need for the ultimate result, so being lazy can easily mean a query that doesn’t perform as well as it should.
Because the views are queries that are only run when called, you won’t know about missing references until runtime.
Be aware that when using
SELECT *in a view, the database captures the column list when theCREATE VIEWstatement was run – if the columns change, you need to refresh the view to pick up the changes.There’s also no performance difference between a view and running the query the view is based on. With the exception of materialized views (which MySQL doesn’t support), views are just a prepared statement. If simple enough, WHERE predicates can be pushed from the
FROM view WHERE ....into the inner query, but it means no use of functions and isn’t reliable.Conclusion
OK, but be careful.