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?
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.