20 Reusing queries with views and stored procedures

 

Through 19 chapters, we’ve written a lot of SQL queries. We’ve used filters, functions, aggregations, and more to find specific data. We’ve even added, updated, and removed data, and we’ve used variables to enable our scripts to do the same things over and over with different values.

In this chapter, we’ll bring a lot of that work together by moving from executing SQL scripts to saving scripts as objects in the database—scripts that anyone who has the necessary permissions can execute. Depending on the relational database management system (RDBMS) we’re using, we can use a few objects to store these scripts. For now, we’ll focus on two nearly universal objects: views and stored procedures.

A view stores a SELECT statement and provides a single result set that can be used like a table. A stored procedure stores one or more queries that can be executed at the same time to perform nearly any required task in a database.

20.1 Views

Views are database objects we create based on a SELECT statement. Views provide a single result set that resembles a table, which is why they’re often referred to as virtual tables. The term virtual tables indicates that we can use views like tables in our queries.

20.1.1 Creating views

20.1.2 Filtering with views

20.1.3 Joining views

20.1.4 Considerations for views

20.2 Stored procedures

20.2.1 Creating stored procedures

20.2.2 Using variables with stored procedures

20.2.3 Considerations for stored procedures

20.3 Differences between views and stored procedures

20.4 Lab

20.5 Lab answers