views:

135

answers:

1

When I create a view I am basically like making a new table that will automatically be transacted upon when data in one of the tables it joins changes?

Also why can't I use subqueries in my view????

+3  A: 

A view works like a table, but it is not a table. It never exists; it is only a prepared SQL statement that is run when you reference the view name. IE:

CREATE VIEW foo AS
  SELECT * FROM bar

SELECT * FROM foo

...is equivalent to running:

SELECT x.* 
  FROM (SELECT * FROM bar) x

A MySQLDump will never contain rows to be inserted into a view...

Also why can't I use subqueries in my view????

That, sadly, is by (albeit questionable) design. There's numerous limitations for MySQL views, which are documented: http://dev.mysql.com/doc/refman/5.0/en/create-view.html

So if it's just an imaginary table/prepared statement does that mean it theoretically has the same performance (or even less) as a normal table/query?


No.
A table can have indexes associated, which can make data retrieval faster (at some cost for insert/update). Some databases support "materialized" views, which are views that can have indexes applied to them - which shouldn't be a surprise that MySQL doesn't support given the limited view functionality (which only began in v5 IIRC, very late to the game).

Because a view is a derived table, the performance of the view is only as good as the query it is built on. If that query sucks, the performance issue will just snowball... That said, when querying a view - if a view column reference in the WHERE clause is not wrapped in a function (IE: WHERE v.column LIKE ..., not WHERE LOWER(t.column) LIKE ...), the optimizer may push the criteria (called a predicate) onto the original query - making it faster.

OMG Ponies
Didn't know that MySQL couldn't do subqueries... Good to know.
Slokun
@Slokun: MySQL views can't use subqueries - subqueries are fine in typical SQL statements.
OMG Ponies
So if it's just an imaginary table/prepared statement does that mean it theoretically has the same performance (or even less) as a normal table/query?
John Nall
@OMG Ponies Yeah, I misphrased that. Done subqueries in MySQL before, but I don't think I've ever had need to make a view in it.
Slokun
@Slokun: No worries - I'm just pedantic cuz there have been misinterpretations in the past.
OMG Ponies
@Hello you all men: Updated the answer to address your follow up question.
OMG Ponies