I was thinking of starting to utilize views to reduce the complexity of code and queries in our project -- some of them have a few joins, and from what I understand, MySQL views would allow us to reference that data a little easier in multiple places.
There's a lot of stuff being thrown around, where "MySQL doesn't use indexes for views", "You can't have an indexed view", "Only if you use MERGE"... There is no clear-cut answer.
So, to cut to the chase: Do MySQL views use indexes on the tables they are built from? Is it a bad idea to use views at all because performance will be abysmal, or will it use the indexes on the underlying tables when doing its joins? If I sort a view by a column that is indexed in the table, does it still sort as fast as it normally would?
Doing my research seems to indicate that views don't use indexes, but if that was the case nobody would ever use them; obviously people do, so...?
Sorry if this seems kind of absurd.
A view is just a way of abbreviating a subquery. An index is used to optimize matching column data.
MySQL supports views, including updatable views. Views are stored queries that when invoked produce a result set. A view acts as a virtual table. The following discussion describes the syntax for creating and dropping views, and shows some examples of how to use them.
Indexes can only be created on views which have the same owner as the referenced table or tables. This is also called an intact ownership-chain between the view and the table(s). Typically, when table and view reside within the same schema, the same schema-owner applies to all objects within the schema.
An indexed view has a unique clustered index. The unique clustered index is stored in SQL Server and updated like any other clustered index. An indexed view is more significant compared to standard views that involve complex processing of large numbers of rows, such as aggregating lots of data, or joining many rows.
If you query a view, MySQL will consider using indexes on the underlying tables.
However it is not possible to add a new index to a calculated column in the view. I think this is what people meant by MySQL not having indexed views, as opposed to (for example) SQL Server's indexed views.
Do MySQL views use indexes on the tables they are built from?
Yes.
What people probably refer to when they say MySQL doesn't use indexes for views
is of something called materialized views
or indexed views
on which the actual view is physically stored on the file system as regular table would be. Indexes can be created for these views on some DBMS such as Oracle or SQL Server. Essentially, indexed views
become a copy of the original tables that compose it and is kept in sync automatically
, sort of speak.
Read this article regarding Indexed Views on SQL Server, for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With