| Lesson 5 |
Selecting from a view |
| Objective |
Select from a view in order to refine your results. |
Selecting Data from SQL View
Querying a view isn't a separate skill from querying a table; it's the exact same SELECT statement, aimed at a different name. Oracle's own documentation treats the two identically at the language level: a SELECT statement retrieves data "from a table or view," with no distinction drawn between the two as a query target. Nothing about applying a WHERE clause, an ORDER BY, or any other standard SELECT capability changes just because the FROM clause happens to name a view instead of a table.
This is worth stating plainly up front, since it's easy to expect views to come with their own special querying rules simply because they involve the word "view." They don't. Every technique demonstrated in this lesson, filtering, sorting, aggregating, joining, subquerying, is a technique already covered elsewhere in this course, applied here without modification to a FROM clause that happens to name a view.
Refining a View's Results
Recall MyView from earlier in this module, built on the Utah-filtering query. Querying it directly returns everything the view exposes:
SELECT * FROM MyView;
Adding a WHERE clause narrows that further, exactly as it would against any table:
SELECT * FROM MyView
WHERE Lastname LIKE 'W%';
Breaking this down:
- FROM MyView names the data source. MyView is a virtual table based on a stored query, but as far as this SELECT statement is concerned, it's simply where the rows come from.
- SELECT * projects every column the view exposes into the result set.
- WHERE Lastname LIKE 'W%' filters those rows further. LIKE performs pattern matching rather than exact matching, and % is the wildcard standing in for zero or more characters. 'W%' matches any value starting with the letter W, regardless of what follows it.
Two layers of filtering are stacked here, and it's worth being explicit about what each one is doing. The view itself already narrowed the data down to Utah customers; this SELECT statement narrows that further, down to only the ones whose last name starts with W. Neither layer needs to know about the other: the view doesn't know or care that someone will eventually filter by last name, and this query doesn't need to know or care how the view arrived at "Utah