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.
Related
I suppose the definition might be different for different databases (I've tagged a few databases in the question), but suppose I have the following (in pseudocode):
CREATE VIEW myview FROM
SELECT * FROM mytable GROUP BY name
And then I can query the view like so:
SELECT * FROM myview WHERE name like 'bob%'
What exactly is the "view" doing in this case? Is it just a short-hand and the same as doing:
SELECT * FROM (
SELECT * FROM mytable GROUP BY name
) myview WHERE name like 'bob%'
Or does creating a view reserve storage (or memory, indexes, whatever else)? In other words, what are the internals of what happens when a view is created and accessed?
A view is a name that refers to a stored SQL query. When referenced, the definition of the query are replaced in the referencing query. It is basically the short-hand that you describe.
A view is defined by the standard and is pretty much the same thing across all databases.
A view does not permanently store data. Each time it is referenced the code is run. One caveat is that -- in some databases -- the view may be pre-compiled, so the pre-compiled code is actually included in the query plan.
By contrast, some databases support materialized views. These are very different beasts and they do store data.
Some other reasons for views:
Not everyone is a SQL expert so the Data Base Administrator might develop views consisting of complex joins on multiple tables to provide users easy access to the data they might need to access but might not know how to best do that.
On some databases you can also create read-only views. Again, a DBA might create these to limit what operations a user can perform on certain tables.
A DBA might also create a view to limit what columns of a table a user can see.
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
how do views act as a mediator between the actual tables and an end user ? what's the internal process which occurs when a view is created. i mean that when a view is created on a table, then does it stands like a wall between the table and the end user or else? how do views protect the actual tables, only with the check option? but if a user inserts directly into the table then how come do i protect the actual tables?
if he/she does not use : insert into **vw** values(), but uses: insert into **table_name** values() , then how is the table protected now?
Non-materialized views are just prepackaged SQL queries. They execute the same as any derived table/inline view. Multiple references to the same view will run the query the view contains for every reference. IE:
CREATE VIEW vw_example AS
SELECT id, column, date_column FROM ITEMS
SELECT x.*, y.*
FROM vw_example x
JOIN vw_example y ON y.id = x.id
...translates into being:
SELECT x.*, y.*
FROM (SELECT id, column, date_column FROM ITEMS) x
JOIN (SELECT id, column, date_column FROM ITEMS) y ON y.id = x.id
Caching
The primary benefit is caching because the query will be identical. Queries are cached, including the execution plan, in order to make the query run faster later on because the execution plan has been generated already. Caching often requires queries to be identical to the point of case sensitivity, and expires eventually.
Predicate Pushing
Another potential benefit is that views often allow "predicate pushing", where criteria specified on the view can be pushed into the query the view represents by the optimizer. This means that the query could scan the table once, rather than scan the table in order to present the resultset to the outer/ultimate query.
SELECT x.*
FROM vw_example x
WHERE x.column = 'y'
...could be interpreted by the optimizer as:
SELECT id, column, date_column
FROM ITEMS
WHERE x.column = 'y'
The decision for predicate pushing lies solely with the optimizer. I'm unaware of any ability for a developer to force the decision, only that it really depends on the query the view uses and what additional criteria is being applied.
Commentary on Typical Use of Non-materialized Views
Sadly, it's very common to see a non-materialized SQL view used for nothing more than encapsulation to simplify writing queries -- simplification which isn't a recommended practice either. SQL is SET based, and doesn't optimize well using procedural approaches. Layering views on top of one another is also not a recommended practice.
Updateable Views
Non-materialized views are also updatable, but there are restrictions because a view can be made of numerous tables joined together. An updatable, non-materialized view will stop a user from being able to insert new records, but could update existing ones. The CHECK OPTION depends on the query used to create the view for enforcing a degree of update restriction, but it's not enough to ensure none will ever happen. This demonstrates that the only reliable means of securing against unwanted add/editing/deletion is to grant proper privileges to the user, preferably via a role.
Views do not protect tables, though they can be used in a permissions-based table-protection scheme. Views simply provide a convenient way to access tables. If you give a user access to views and not tables, then you have probably greatly restricted access.
I am confused about a few points:
What is the difference between a stored procedure and a view?
When should I use stored procedures, and when should I use views, in SQL Server?
Do views allow the creation of dynamic queries where we can pass parameters?
Which one is the fastest, and on what basis is one faster than the other?
Do views or stored procedures allocate memory permanently?
What does it mean if someone says that views create a virtual table, while procedures create a materials table?
Please let me know about more points, if there are any.
A view represents a virtual table. You can join multiple tables in a view and use the view to present the data as if the data were coming from a single table.
A stored procedure uses parameters to do a function... whether it is updating and inserting data, or returning single values or data sets.
Creating Views and Stored Procedures - has some information from Microsoft as to when and why to use each.
Say I have two tables:
tbl_user, with columns: user_id, user_name, user_pw
tbl_profile, with columns: profile_id, user_id, profile_description
So, if I find myself querying from those tables A LOT... instead of doing the join in EVERY piece of SQL, I would define a view like:
CREATE VIEW vw_user_profile
AS
SELECT A.user_id, B.profile_description
FROM tbl_user A LEFT JOIN tbl_profile B ON A.user_id = b.user_id
GO
Thus, if I want to query profile_description by user_id in the future, all I have to do is:
SELECT profile_description FROM vw_user_profile WHERE user_id = #ID
That code could be used in a stored procedure like:
CREATE PROCEDURE dbo.getDesc
#ID int
AS
BEGIN
SELECT profile_description FROM vw_user_profile WHERE user_id = #ID
END
GO
So, later on, I can call:
dbo.getDesc 25
and I will get the description for user_id 25, where the 25 is your parameter.
There is obviously a lot more detail, this is just the basic idea.
Plenty of info available here
Here is a good summary:
A Stored Procedure:
Accepts parameters
Can NOT be used as building block in a larger query
Can contain several statements, loops, IF ELSE, etc.
Can perform modifications to one or several tables
Can NOT be used as the target of an INSERT, UPDATE or DELETE
statement.
A View:
Does NOT accept parameters
Can be used as building block in a larger query
Can contain only one single SELECT query
Can NOT perform modifications to any table
But can (sometimes) be used as the target of an INSERT, UPDATE or
DELETE statement.
A SQL View is a virtual table, which is based on SQL SELECT query. A view references one or more existing database tables or other views. It is the snap shot of the database whereas a stored procedure is a group of Transact-SQL statements compiled into a single execution plan.
View is simple showcasing data stored in the database tables whereas a stored procedure is a group of statements that can be executed.
A view is faster as it displays data from the tables referenced whereas a store procedure executes sql statements.
Check this article : View vs Stored Procedures . Exactly what you are looking for
First you need to understand, that both are different things. Stored Procedures are best used for INSERT-UPDATE-DELETE statements. Whereas Views are used for SELECT statements. You should use both of them.
In views you cannot alter the data. Some databases have updatable Views where you can use INSERT-UPDATE-DELETE on Views.
In addition to the above comments, I would like to add few points about Views.
Views can be used to hide complexity. Imagine a scenario where 5 people are working on a project but only one of them is too good with database stuff like complex joins. In such scenario, he can create Views which can be easily queried by other team members as they are querying any single table.
Security can be easily implemented by Views. Suppose we a Table Employee which contains sensitive columns like Salary, SSN number. These columns are not supposed to be visible to the users who are not authorized to view them. In such case, we can create a View selecting the columns in a table which doesn't require any authorization like Name, Age etc, without exposing sensitive columns (like Salary etc. we mentioned before). Now we can remove permission to directly query the table Employee and just keep the read permission on the View. In this way, we can implement security using Views.
A view is a simple way to save a complex SELECT in the database.
A store procedure is used when simple SQL just isn't enough. Store procedures contain variables, loops and calls to other stored procedures. It's a programming language, not a query language.
Views are static. Think of them as new tables with a certain layout and the data in them is created on the fly using the query you created it with. As with any SQL table, you can sort and filter it with WHERE, GROUP BY and ORDER BY.
The depends on what you do.
The depends on the database. Simple views just run the query and filter the result. But databases like Oracle allow to create a "materialized" view which is basically a table which is updated automatically when the underlying data of the view changes.
A materialized view allows you to create indexes on the columns of the view (especially on the computed columns which don't exist anywhere in the database).
I don't understand what you're talking about.
Mahesh is not quite correct when he suggests that you can't alter the data in a view. So with patrick's view
CREATE View vw_user_profile AS
Select A.user_id, B.profile_description
FROM tbl_user A left join tbl_profile B on A.user_id = b.user_id
I CAN update the data ... as an example I can do either of these ...
Update vw_user_profile Set profile_description='Manager' where user_id=4
or
Update tbl_profile Set profile_description='Manager' where user_id=4
You can't INSERT to this view as not all of the fields in all of the table are present and I'm assuming that PROFILE_ID is the primary key and can't be NULL.
However you can sometimes INSERT into a view ...
I created a view on an existing table using ...
Create View Junk as SELECT * from [TableName]
THEN
Insert into junk (Code,name) values
('glyn','Glyn Roberts'),
('Mary','Maryann Roberts')
and
DELETE from Junk Where ID>4
Both the INSERT and the DELETE worked in this case
Obviously you can't update any fields which are aggregated or calculated but any view which is just a straight view should be updateable.
If the view contains more than one table then you can't insert or delete but if the view is a subset of one table only then you usually can.
A VIEW is a dynamic query where you can use a "WHERE"-Clause
A stored procedure is a fixed data selection, which returns a predefined result
Nor a view, nor a stored procedure allocate memory. Only a materialized view
A TABLE is just one ENTITY, a view can collect data from different ENTITIES or TABLES
Main difference is that when you are querying a view then it's definition is pasted into your query. Procedure could also give results of query, but it is compiled and for so faster. Another option are indexed views..
#Patrick is correct with what he said, but to answer your other questions a View will create itself in Memory, and depending on the type of Joins, Data and if there is any aggregation done, it could be a quite memory hungry View.
Stored procedures do all their processing either using Temp Hash Table e.g #tmpTable1 or in memory using #tmpTable1. Depending on what you want to tell it to do.
A Stored Procedure is like a Function, but is called Directly by its name. instead of Functions which are actually used inside a query itself.
Obviously most of the time Memory tables are faster, if you are not retrieveing alot of data.
Hello I have several databases, such as mytable_2009_11_19_03 where last 2 numbers identify the hour (table for 03:00), now I want to query something from _00 to _23 .
It could be done in such way but it is really clumsy
select * from mytable_2009_11_19_00 where type = 15
UNION
select * from mytable_2009_11_19_01 where type = 15
UNION
...........
select * from mytable_2009_11_19_23 where type = 15
How could I do it easier?
regards
This table structure sounds like it was intended to be part of a data partitioning scheme. This is not bad design. This is a very good thing!
Time based data like this is always being added to in the front and dropped off the back as it expires. Using one huge table would result in large amounts of index fragmentation as the data updates and in very large maintenance times for operations like VACUUM.
If you follow the link I included in the first paragraph and read all about partitioning, you'll be able to use CHECK constraints to make date searches very fast. Any SELECT that includes a WHERE timestamp > x AND timestamp < y will be quick.
Now, if these tables don't include any timestamps then the partitioning with CHECK constraints won't work and you will just have to write scripts to write the clumsy UNION queries for you.
If you know that all the tables generated are always identical in schema, in PostgreSQL you could create a parent table and set the newly created tables to INHERIT from the parent.
CREATE TABLE mytable_2009_11_19 (LIKE mytable_2009_11_19_00);
ALTER TABLE mytable_2009_11_19_00 INHERIT mytable_2009_11_19;
ALTER TABLE mytable_2009_11_19_01 INHERIT mytable_2009_11_19;
.
.
.
ALTER TABLE mytable_2009_11_19_23 INHERIT mytable_2009_11_19;
SELECT * FROM mytable_2009_11_19 where type = 15;
This is similar to using a view, but there are differences (listing the CONs first):
(CON) This method requires you to be able to ALTER the individual tables, which you may not have the rights to do. A VIEW does not require this level of access.
(CON) This method requires the tables to all have the same structure or, at the very least, the parent must have ONLY the common elements between all the children.
(PRO) To add tables to a VIEW, you have to drop and redefine the VIEW (and it's permissions, if necessary). With a parent table, it's easy to add or remove tables by ALTERing each one with INHERIT/NOINHERIT.
(PRO) If your schema contains fields like date and timestamp and the structure rarely changes, you can build a single parent table and use INHERIT/NOINHERIT on a rolling basis to provide a time "window" that you can query against without having to query the entire history.
The easiest solution would likely be to build a view of all of the tables, then you can query them easily. You could easily write a procedure to generate the view. Also, if you use "union all", it will be faster, if the result you want is all of the rows (as opposed to distinct rows) and you can still grab distinct rows by selecting distinct from the view if you need it sometimes.