Possible Duplicate:
Difference Between Views and Tables in Performance
What is the main difference between view and table in SQL. Is there any advantage of using views instead of tables.
A table contains data, a view is just a SELECT statement which has been saved in the database (more or less, depending on your database).
The advantage of a view is that it can join data from several tables thus creating a new view of it. Say you have a database with salaries and you need to do some complex statistical queries on it.
Instead of sending the complex query to the database all the time, you can save the query as a view and then SELECT * FROM view
Table:
Table is a preliminary storage for storing data and information in RDBMS.
A table is a collection of related data entries and it consists of columns and rows.
View:
A view is a virtual table whose contents are defined by a query.
Unless indexed, a view does not exist as a stored set of data values in a database.
Advantages over table are
We can combine columns/rows from multiple table or another view and have a consolidated view.
Views can be used as security mechanisms by letting users access data through the view, without granting the users permissions to directly access the underlying base tables of the view
It acts as abstract layer to downstream systems, so any change in schema is not exposed and hence the downstream systems doesn't get affected.
I thought this was best explained by the article "SQL - What is a View" published by 1Keydata:
A view is a virtual table. A view consists of rows and columns just like a table. The difference between a view and a table is that views are definitions built on top of other tables (or views), and do not hold data themselves. If data is changing in the underlying table, the same change is reflected in the view. A view can be built on top of a single table or multiple tables. It can also be built on top of another view. In the SQL Create View page, we will see how a view can be built.
Views offer the following advantages:
Ease of use: A view hides the complexity of the database tables from end users. Essentially we can think of views as a layer of abstraction on top of the database tables.
Space savings: Views takes very little space to store, since they do not store actual data.
Additional data security: Views can include only certain columns in the table so that only the non-sensitive columns are included and exposed to the end user. In addition, some databases allow views to have different security settings, thus hiding sensitive data from prying eyes.
In view there is not any direct or physical relation with the database.
And Modification through a view (e.g. insert, update, delete) is
not permitted.Its just a logical set of tables
A view helps us in get rid of utilizing database space all the time. If you create a table it is stored in database and holds some space throughout its existence. Instead view is utilized when a query runs hence saving the db space. And we cannot create big tables all the time joining different tables though we could but its depends how big the table is to save the space. So view just temporarily create a table with joining different table at the run time. Experts,Please correct me if I am wrong.
SQL Views:
View is a virtual table based on the result-set of an SQL statement and that is Stored in the database with some name.
SQL Table:
SQL table is database instance consists of fields (columns), and rows.
Check following post, author listed around seven differences between views and table
https://codechef4u.com/post/2015/09/03/sql-views-vs-tables
Table:
Table stores the data in database and contains the data.
View:
View is an imaginary table, contains only the fields(columns) and does not contain data(row) which will be framed at run time
Views created from one or more than one table by joins, with selected columns.
Views are created to hide some columns from the user for security reasons, and to hide information exist in the column.
Views reduces the effort for writing queries to access specific columns every time
Instead of hitting the complex query to database every time, we can use view
Related
I have two databases A and B. My application runs on Database A. Now I must retrieve some data from database B. Therefore I created a database link to B.
I am wondering what is faster:
Create a View with the corresponding select on database B and get the data via this view:
select * from myview#B
Select tables directly:
select * from table1#B, table2#B left outer join table3#B...
I think probably they would be just as fast since the execution plan will be identical. But would be easier on you to just do second option.
About Views
A view is a logical representation of another table or combination of tables. A view derives its data from the tables on which it is based. These tables are called base tables. Base tables might in turn be actual tables or might be views themselves. All operations performed on a view actually affect the base table of the view.
You don't get any performance benefits of using view instead of tables. These are simply a stored query, When you submit select * from myview#B, this simply retrieve the view definition from data dictionary and rewrite the query using it.
Please correct me if my understanding is incorrect, but the data within a view is always "up to date" if you query the view because in querying the view, the query used to create the view is also refreshed. The particular view that I'm creating contains millions of records and I am thus wondering if you can keep the "historical" data in the view and only add new stuff to it?
I do not have table-writing privileges on the database.
EDIT: Real-time tracking data is constantly added to the database, and the view is meant to stitch together a lot of disparate information for easier BI analysis. So, the "new data" I am referring to is the constant addition of real-time tracking data.
EDIT: I'm writing this from an efficiency perspective (i.e. because there're millions of records, it would take a long time to recreate the entire view in each query). Maybe what I'm really asking is whether or not SQL Server 2008 would "optimize" this query by only adding the new stuff, would it reload all the data, or is there even a way to "optimize" this in such a way as the first case?
A view is basically a select statement with a name. When you query the view, the query "under the hood" is executed and this is how data fetched is always "fresh".
A solution for your scenario would be to create a different view (or recreate the existent one) where you filter the historical data (exclude rows that are historical, from your point of view by adding an extra condition on a date column). Of course, the other logic should be kept(tables joined, columns, calculations etc etc).
You can also use the existent view and make a new one starting from that. The "body" of the new view should be something like:
select *
from (
select * from existentView -- this should contain an AddedDate (or some sort of date)
) e
where e.AddedDate >= getdate()-30
I have a problem to decide whether to use a view or a temp table.
I have a stored procedure that i call from program. In that SP i store the result of a long query in a temp table, name the columns and make another queries on that table store the results in labels or a gridview or whatever and drop the Temp Table. I could also store the query-result in a view and make queries on that view. So what is better or in what case do i HAVE to use a VIEW/ Temp Table.
According to my research a view has the benefit of: Security, Simplicity and Column Name Specification. My temporary table fulfills all that too (according to my opinion).
If the query is "long" and you are accessing the results from multiple queries, then a temporary table is the better choice.
A view, in general, is just a short-cut for a select statement. If does not imply that the results are ever run and processed. If you use a view, the results will need to be regenerated each time it is used. Although subsequent runs of the view may be more efficient (say because the pages used by the view query are in cache), a temporary table actually stores the results.
In SQL Server, you can also use table variables (declare #t table . . .).
Using a temporary table (or table variable) within a single stored procedure would seem to have few implications in terms of security, simplicity, and column names. Security would be handled by access to the stored procedure. Column names are needed for either solution. Simplicity is hard to judge without more information, but nothing sticks out as being particularly complicated.
depends
A view must replicate the processing of your "long query" each time it is run, while a temp table stores the results.
so do you want to use more processing or more storage?
You can store some view values (persistent index) which could help on processing, but you don't provide enough info to really explore this.
If you are talking about just storing the data for the use within a single procedure call, then a temp table is the way to go.
I'd like to also mention that for temporary table,
You cannot refer to a TEMPORARY table more than once in the same query.
This make temp table inconvenient for the cases where you want to use self join on it.
It is really a situational and operation specific question and answer may vary depending on the requirements of the scenario.
However, a small point that i would like to add is that if you are using a view to store results of a complex query, which are in turn used in operations of a GridView, then it can be troublesome to perform update operations on complex views. On the contrary, Temp Tables can suffice to this perfectly.
Again, There are scenario's where Views may be a better choice [ as in Multiple Database Servers if not handled properly] but it depends on what you want to do.
In general I would use a temporary table when I want to refer multiple times to the same table within a stored procedure, and a view when I want to use the table across different stored procedures.
A view does not persist the data (in principle): each time you reference the view SQL uses the logic from the view to access the original table. So you would not want to build a view on a view on a view, or use multiple references to a view that has complex logic.
I'm building a reporting app, and so I'm crunching an awful lot of data. Part of my approach to creating the app in an agile way is to use SQL views to take the strain off the DB if multiple users are all bashing away.
One example is:
mysql_query("CREATE VIEW view_silverpop_clicks_baby_$email AS SELECT view_email_baby_position.EmailAddress, view_email_baby_position.days, silverpop_campaign_emails.id, silverpop_actions.`Click Name` , silverpop_actions.`Mailing Id`
FROM silverpop_actions
INNER JOIN view_email_baby_position ON (silverpop_actions.Email = view_email_baby_position.EmailAddress ) , silverpop_campaign_emails
WHERE silverpop_campaign_emails.id = $email
AND view_email_baby_position.days
BETWEEN silverpop_campaign_emails.low
AND silverpop_campaign_emails.high
AND silverpop_actions.`Event Type` = 'Click Through'") or die(mysql_error());
And then later in the script this view is used to calculate the number of clicks a particular flavour of this email has had.
$sql = "SELECT count(*) as count FROM `view_silverpop_clicks_baby_$email` WHERE `Click Name` LIKE '$countme%'";
My question is in 2 parts really:
Are views always good? Can you
have too many?
Could I create yet another set of
views to cache the count variable in
the second snippet of code. If so
how could I approach this? I can't
quite make this out yet.
Thanks!
To answer your questions.
1.) I don't know that I can think of an instance where views are BAD in and of themselves, but it would be bad to use them unnecessarily. Whether you can have too many really depends on your situation.
2.) Having another set of views will not cache the count variable so it wouldn't be beneficial from that standpoint.
Having said that, I think you have a misunderstanding on what a view actually does. A view is just a definition of a particular SQL statement and it does not cache data. When you execute a SELECT * FROM myView;, the database is still executing the select statement defined in the CREATE VIEW definition just as it would if a user was executing that statement.
Some database vendors offer a different kind of view called a materialized view. In this case the table data needed to create the view is stored/cached and is usually updated based on a refresh rate specified when you create it. This is "heavy" in the sense that your data is stored twice, but can create better execution plans because the data is already joined, aggregated, etc. Note though, you only see the data based on the last refresh of the materialized view, where with a normal view you see the data as it currently exists in the underlying tables. Currently, MySQL does not support materialized views.
Some useful uses of views are to:
Create easier/cleaner SQL statements for complex queries (which is something you are doing)
Security. If you have tables where you want a user to be able to see some columns or rows, but not other columns/rows, you restrict access to the base table and create a view of the base table that only selects the columns/rows that the user should have access too.
Create aggregations of tables
Views are used by query optimizer so they often help in querying for information more efficiently.
Indexed or materialized views however create a table with the required information which can make quite a difference. Think of it as denormalization of you db scheme without changing existing scheme. You get best of both worlds.
Some views are never used so they represent needles compexity -which is bad.
Indexed views cannot reference other views (mssql) so there's hardly a point in creating such view.
the mysql certification guide suggests that views can be used for:
creating a summary that may involve calculations
selecting a set of rows with a WHERE clause, hide irrelevant information
result of a join or union
allow for changes made to base table via a view that preserve the schema of original table to accommodate other applications
but from how to implement search for 2 different table data?
And maybe you're right that it doesn't
work since mysql views are not good
friends with indexing. But still. Is
there anything to search for in the
shops table?
i learn that views dont work well with indexing so, will it be a big performance hit, for the convenience it may provide?
A view can be simply thought of as a SQL query stored permanently on the server. Whatever indices the query optimizes to will be used. In that sense, there is no difference between the SQL query or a view. It does not affect performance any more negatively than the actual SQL query. If anything, since it is stored on the server, and does not need to be evaluated at run time, it is actually faster.
It does afford you these additional advantages
reusability
a single source for optimization
This mysql-forum-thread about indexing views gives a lot of insight into what mysql views actually are.
Some key points:
A view is really nothing more than a stored select statement
The data of a view is the data of tables referenced by the View.
creating an index on a view will not work as of the current version
If merge algorithm is used, then indexes of underlying tables will be used.
The underlying indices are not visible, however. DESCRIBE on a view will show no indexed columns.
MySQL views, according to the official MySQL documentation, are stored queries that when invoked produce a result set.
A database view is nothing but a virtual table or logical table (commonly consist of SELECT query with joins). Because a database view is similar to a database table, which consists of rows and columns, so you can query data against it.
Views should be used when:
Simplifying complex queries (like IF ELSE and JOIN or working with triggers and such)
Putting extra layer of security and limit or restrict data access (since views are merely virtual tables, can be set to be read-only to specific set of DB users and restrict INSERT )
Backward compatibility and query reusability
Working with computed columns. Computed columns should NOT be on DB tables, because the DB schema would be a bad design.
Views should not be use when:
associate table(s) is/are tentative or subjected to frequent structure change.
According to http://www.mysqltutorial.org/introduction-sql-views.aspx
A database table should not have calculated columns however a database view should.
I tend to use a view when I need to calculate totals, counts etc.
Hope that help!
One more down side of view that doesn't work well with mysql replicator as well as it is causing the master a bit behind of the slave.
http://bugs.mysql.com/bug.php?id=30998