views:

369

answers:

3

Consider the tables: (-> denotes a SQL defined relationship)

USER (userid, username, imageid->IMAGE.imageid)
EVENT (eventid, userid->USER.userid, description)
IMAGE (imageid, location)

Say I have a view (let's call it vw_UserInfo) defined as the following query.

SELECT u.*, i.* FROM users u
INNER JOIN images i ON i.imageid = u.imageid

Is SQL aware of the relationship between EVENT.userid and vw_UserInfo.userid? I mean, will the performance benefit of a JOIN operation on related fields still apply? I suppose this could vary depending on which SQL DB you're using.


EDIT: In an attempt to be a bit clearer. I'm asking will

SELECT ui.*, e.* FROM vw_UserInfo ui 
INNER JOIN events e ON ui.userid = e.userid

Benefit from the foreign key defined just as much as

SELECT u.*, i.*, e.* FROM users u
INNER JOIN images i ON i.imageid = u.imageid
INNER JOIN events e ON e.userid = u.userid

would?

A: 

Relationships enforce data integrity, they have nothing to do with quick selection of data. That is the realm of indexes. In general, relationships (especially on tables with many of them) slow down data access (especially writes).

Robert C. Barth
In the Celko article I linked, he says that CHECK constraints are used by the optimizer.
Cade Roux
+2  A: 

No, because views (at least in SQL Server) are not really part of the constraints system (the existence or non-existence of a view should not affect the performance of any query not referencing the view). Indexed views (materialized views), however, might be able to contribute to performance. I'm not sure which, if any, optimizers would use them in execution plans if they aren't explicitly referenced, though.

If you read this article by Celko, you can see that the more metadata you give the database about the constraints and foreign-key relationships between your tables, this can improve the performance of queries.

Cade Roux
A: 

Yes, kinda.

In so much as the optimizer could optimize using the underlying tables indexes, since views are expanded at the compilation step.

But... like Rovert says, relationships don't speed up queries, indexes do.

Allain Lalonde