EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

Postgres Create View

By Payal UdhaniPayal Udhani

Home » Data Science » Data Science Tutorials » PostgreSQL Tutorial » Postgres Create View

Postgres Create View

Introduction to Postgres Create View

Views are the pseudo-tables that in reality are not materialized. The records of view do not actually consume any memory in the physical database. The views are created on the basis of certain existing temporary or permanent tables. The columns are combined or are specified from the existing tables while view creation which is in turn called as the base tables. The views which are created on the basis of temporary tables are considered as temporary and are dropped once the session associated with it is closed. Whenever a view is referred, internally a query is run on the base tables to retrieve the records of the view.

In this article, we will learn about how to create views and change or replace them and fetch the records from the view, and finally how to delete the view using the DROP command. All the permission allocation and ownership rules and manipulations of the views in PostgreSQL are the same and remain unchanged. Also, you should note that no updation, insertion, and deletion operations are permitted on the views. However, we can internally write the triggers on the view where we can write the queries for changing the base tables whenever the corresponding change is done on the view. Views can be created from one or more base tables and may contain one or more columns in it. We can retrieve the records from the view in the same fashion as we do for the tables. We will begin by learning the syntax to create the view in PostgreSQL.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax:

CREATE [ OR REPLACE ] [ TEMP | TEMPORARY ] VIEW nameOfView [ ( nameOfColumn [, ...] ) ] [ WITH ( view_option_name [= view_option_value] [, ... ] ) ] AS querySpecifyingRecords

Parameters:

  • TEMPORARY or TEMP – This is the optional statement that can be used in the query if you want to declare the target view as the temporary view. By default, the views are permanent in nature. Only in the case when the views are created using temporary base tables. the view is also considered temporary even if not mentioned in the query. Otherwise, until and unless specified in the query they are permanent in nature.
  • NameOfView – This is used for specifying the name of the target view that you want to create.
  • NameOfColumn – These are optional column names that can be specified for preparing the view that will contain columns named as specified. If not specified then they are deduced from the querySpecifyingRecords query which refers in turn to the base tables.
  • view_option_name – We can provide any optional parameters while creating the view using this syntax. For now, only one type of parameter is available to pass named security_barrier that helps to provide row-level security to the view when enabled.
  • QuerySpecifyingRecords – This can be SELECT query or the VALUES that help to specify rows and columns to be inserted in the view.

Example of Postgres Create View

To create the view we need to have the base tables. Let us check by typing the command \dt on psql prompt. As can be seen, only one table named educba exists in my postgres database. Let us create two tables named teams and developers and insert some values in both of them.

CREATE TABLE teams (
id SERIAL PRIMARY KEY,
team_count INTEGER,
department VARCHAR (100)
);

Now, we will create a table for developers that will act as the referencing or child table. There will be one to many relationships between teams and developers’ tables. team_id will be our referencing key which will refer to the id of the team’s table.

CREATE TABLE developers (
developer_id INTEGER NOT NULL,
team_id INTEGER REFERENCES teams (id),
name VARCHAR (100),
position VARCHAR (100),
technology VARCHAR (100),
PRIMARY KEY (developer_id,team_id)
);

INSERT INTO teams (id, team_count, department) VALUES('1','5','Accounting');
INSERT INTO teams (id, team_count, department) VALUES('2','6','Inventory');
INSERT INTO teams (id, team_count, department) VALUES('3','5','Human Resource');
INSERT INTO teams (id, team_count, department) VALUES('4','7','CRM');
INSERT INTO teams (id, team_count, department) VALUES('5','9','Bug Solver');
INSERT INTO teams (id, team_count, department) VALUES('6','4','Document');
INSERT INTO developers (developer_id, team_id, name, position, technology) VALUES(1,2,'Payal','senior SD','Java');
INSERT INTO developers (developer_id, team_id, name, position, technology) VALUES(2,1,'Heena','Developer','Angular');
INSERT INTO developers (developer_id, team_id, name, position, technology) VALUES(3,2,'Sayali','Developer','Hibernate');
INSERT INTO developers (developer_id, team_id, name, position, technology) VALUES(4,3,'Rahul','Support','Digital Marketing');
INSERT INTO developers (developer_id, team_id, name, position, technology) VALUES(5,3,'Siddhesh','Tester','Maven');

as shown below –

Postgres Create View 1

Now, let us check the contents of both tables teams and developers using query statements –

SELECT * FROM teams;

Postgres Create View 2

SELECT * FROM developers;

Postgres Create View 3

Firstly we will create a simple view which will retrieve the records from one table only developers with name and position columns with records whose team is “Inventory” means its team id is 2. For doing this our query statement will be as follows –

CREATE VIEW inv_team AS SELECT name,position FROM developers WHERE team_id = 2;

Postgres Create View 4

which will result into following output. To verify our view’s contents let us check them by firing the query

SELECT * FROM inv_team;

Postgres Create View 5

Note: that I closed the session and again opened the psql prompt and fired the select query which retrieved correct records which means that the view that we created is permanent one as we didn’t specified TEMP or TEMPORARY in the create view query.

Now, we will create a temporary view that will contain the name of the developer and its team’s department. That means there will be two base tables. Let us begin by framing or query statements.

CREATE or REPLACE TEMPORARY VIEW team_details AS SELECT a.department, b.name FROM teams a INNER JOIN developers b ON a.id = b.team_id;

which results in the following output –

Postgres Create View 6

Let us check its contents using the query

SELECT * FROM team_details;

Select 1

Now, as it is a temporary view let us close our session and check whether we get the same output after beginning a new session.

Select 2

As it can be seen the team_details view does not exist anymore as the session in which that temporary table was created was closed and hence the view deleted.

Now, let us check contents of inv_team view inn this new session.

SELECT * FROM inv_team;

Select 3

To delete this view, we will need to use the DROP VIEW command as follows –

DROP VIEW inv_team;

and check its contents by using the SELECT statement as above which gives output –

Select 4

So, the view is deleted permanently.

Conclusion

The views can be created on one or more base tables having one or more columns which can be either temporary or permanent in nature in PostgreSQL. DROP VIEW command is used to remove the view completely.

Recommended Articles

This is a guide to Postgres Create View. Here we discuss the introduction of Postgres Create View, syntax, parameters, and examples with code implementation. You may also have a look at the following articles to learn more –

  1. PostgreSQL age()
  2. PostgreSQL SET
  3. PostgreSQL Integer
  4. PostgreSQL NOT IN

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Special Offer - All in One Data Science Bundle (360+ Courses, 50+ projects) Learn More