Summary

In this chapter, indexes, views, functions, user-defined data types, and rule and trigger systems have been discussed. A view is a named query or a wrapper around a SELECT statement. They can be used as a data access layer, provide an abstraction level, and control data privileges and permissions.

A view in PostgreSQL can be categorized as temporary, materialized, updatable, and recursive. Simple views in PostgreSQL are automatically updatable. To make complex views updatable, one can use the rule and trigger systems. Indexes are physical database objects defined on a table column, a set of columns, and expressions. Indexes are often used to optimize performance or to validate data. There are several techniques for building indexes, including B-tree, hash, GIN, GIST, and BRIN. B-tree is the default indexing method. GIN and GIST are useful for indexing complex data types and for full-text searches. There are several types of indexes; each type can be used for a different use case. For example, partial indexes index only a subset of the data that meets a certain predicate. The unique index is often used to validate data such as the uniqueness of primary keys. Finally, a multi-column index can be used for specific data retrieval scenarios.

The information about indexes can be retrieved from the pg_catalog statistics, and can be used for maintenance purposes. When an index is bloated, one can create a concurrent index instead of re-indexing it. Note that the creation of concurrent indexes will not lock the database table.

PostgreSQL functions provide distinct services, and have usages similar to views. Functions can be written in C, SQL, and PL/pgsql without extra extensions. One important usage of functions is to assist in maintaining a database. This can be done easily without using external scripting, such as Bash, by utilizing anonymous functions.

Specifying the function category as stable, volatile, or immutable is very important because it helps the optimizer to generate the optimal execution plan. Unfortunately, the interdependency between functions is not recorded in the database catalog. This means one should take great care when writing complex logic using functions. User-defined data types can be created using the CREATE DOMAIN and CREATE TYPE commands. Some user-defined data types, such as ENUM, can greatly reduce the number of joins, thus leading to more understandable and efficient SQL code. PostgreSQL triggers and rules are used to execute an action when a certain event occurs. They can be used alternately in several scenarios. One needs to be careful when using rules with volatile functions because they have some side effects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset