Views & Sequences
Views#
Views are named queries stored in the database. They act as virtual tables.
1-- Create a view
2CREATE VIEW active_users AS
3SELECT id, name, email FROM users WHERE active = true;
4
5-- Query the view like a table
6SELECT * FROM active_users;
7
8-- Create only if it doesn't exist
9CREATE VIEW IF NOT EXISTS expensive_products AS
10SELECT * FROM products WHERE price > 100;
11
12-- Remove a view
13DROP VIEW active_users;
14DROP VIEW IF EXISTS expensive_products;Views are persisted and survive server restarts.
Sequences#
Sequences generate auto-incrementing numeric values.
1-- Create a sequence
2CREATE SEQUENCE order_seq;
3
4-- Get next value
5SELECT NEXTVAL('order_seq'); -- returns 1, 2, 3, ...
6
7-- Get current value (after NEXTVAL has been called)
8SELECT CURRVAL('order_seq');
9
10-- Use in INSERT
11INSERT INTO orders (id, product) VALUES (NEXTVAL('order_seq'), 'Widget');
12
13-- Remove a sequence
14DROP SEQUENCE order_seq;Sequences are persisted and maintain their state across restarts.
Edit this page on GitHub
Last updated