Outdated version of the documentation. Find the latest one here.

16.5. Lesson: Vistas

Cuando se escribe una consulta, debe pasar mucho tiempo y esfuerzo para formularla. Con vistas, se puede guardar la definición de una consulta SQL en una reutilizable ‘tabla virtual’

El objetivo de esta lección: Guardar una consulta como una vista.

16.5.1. Crear una vista

You can treat a view just like a table, but its data is sourced from a query. Let’s make a simple view based on the above:

create view roads_count_v as
  select count(people.name), streets.name
  from people, streets where people.street_id=streets.id
  group by people.street_id, streets.name;

As you can see the only change is the create view roads_count_v as part at the beginning. We can now select data from that view:

select * from roads_count_v;

Result:

 count |    name
-------+-------------
     1 | Main Road
     2 | High street
     1 | Low Street
(3 rows)

16.5.2. Modificar una vista

A view is not fixed, and it contains no ‘real data’. This means you can easily change it without impacting on any data in your database:

CREATE OR REPLACE VIEW roads_count_v AS
  SELECT count(people.name), streets.name
  FROM people, streets WHERE people.street_id=streets.id
  GROUP BY people.street_id, streets.name
  ORDER BY streets.name;

(Este ejemplo muestra también la mejor practica de convención de la utilización UPPER CASE para todas la palabras clave SQL.)

You will see that we have added an ORDER BY clause so that our view rows are nicely sorted:

select * from roads_count_v;

 count |    name
-------+-------------
     2 | High street
     1 | Low Street
     1 | Main Road
(3 rows)

16.5.3. Eliminar una Vista

If you no longer need a view, you can delete it like this:

drop view roads_count_v;

16.5.4. In Conclusion

Usar vistas, puede guardar una consulta y acceder a los resultados como si fuera una tabla.

16.5.5. What’s Next?

Algunas veces, cuando cambia datos, quiere que los cambios tengan efecto entre otra parte en la base de datos. La siguiente lección mostrará cómo puede hacer esto.