Friday 29 April 2016

SQL VIEWS


A quick note on SQL views.  “In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.” – this is the definition of a SQL view.  I wish more people would realise the importance of this definition.  It essentially means that, although the view in question may seem like a table when queried through Management Services or something similar, it is just that – it is a result of a SQL query statement.

Too many times I have come across databases that are almost entirely built with views because the person building the queries does not realise this fundamentally important principle.  Don’t get me wrong – views have their place in many databases, especially smaller ones where performance is not a major concern.  The danger is when the database continues to grow and develop and the developer / perpetrator does not change the way the data is being presented.  You will then find that you have a SQL statement that takes longer and longer to run.  The reason? You develop a query that produces the resulting data that you were asked to provide and this queries a view.  In turn, this view may query more views which may also query more, ad infinitum.  Nested queries can be a ticking time bomb if not kept in check and the dangers become apparent very quickly as time goes on. 

If you want a report or query to run properly, my advice is to get rid of your views.  There should never be a complex query run on a view and there are NO exceptions.  Don’t listen to anyone who says different.  These are people who avoid and fall in the realm of Einstein’s advice – “if you can’t explain it simply, you don’t understand it well enough”.  I’ve met many people like this in my time and the only advice worth giving about them is to stay well clear.  This type of person will not help you in your endeavours.

So, my advice?  Use views sparingly and respect your users and servers.