Define a Simple View
In this step, you will learn how to define a simple view in PostgreSQL. Views are virtual tables based on the result-set of an SQL statement. They are useful for simplifying complex queries, providing abstraction, and controlling data access.
Understanding Views
A view is essentially a stored query. When you query a view, PostgreSQL executes the underlying query and returns the result set as if it were a real table. Views do not store data themselves; they provide a different way to access the data stored in the base tables.
Creating the employees
Table
First, let's create a table named employees
to work with. Open a terminal and connect to the PostgreSQL database as the postgres
user:
sudo -u postgres psql
Now, create the employees
table:
CREATE TABLE employees (
employee_id SERIAL PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10, 2)
);
Next, insert some sample data into the employees
table:
INSERT INTO employees (first_name, last_name, department, salary) VALUES
('John', 'Doe', 'Sales', 60000.00),
('Jane', 'Smith', 'Marketing', 75000.00),
('Robert', 'Jones', 'Sales', 62000.00),
('Emily', 'Brown', 'IT', 80000.00),
('Michael', 'Davis', 'Marketing', 70000.00);
You can verify the data by running the following query:
SELECT * FROM employees;
You should see the inserted data in the output.
Defining the employee_info
View
Now that we have a table with data, let's create a simple view. This view will show only the first name, last name, and department of each employee. We can define a view named employee_info
using the following SQL statement:
CREATE VIEW employee_info AS
SELECT first_name, last_name, department
FROM employees;
This statement creates a view named employee_info
that selects the first_name
, last_name
, and department
columns from the employees
table.
Querying the View
To query the view, you can use a SELECT
statement just like you would with a regular table:
SELECT * FROM employee_info;
This query will return the first name, last name, and department of all employees, as defined in the view.
Describing the View
You can describe the view using the \d
command in psql
:
\d employee_info
This will show you the view definition and the columns it contains.