EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial PostgreSQL Views
Secondary 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

PostgreSQL Views

PostgreSQL Views

Introduction to PostgreSQL Views

In these articles, we will learn about PostgreSQL Views. Views are basically a query with a name; therefore, a view is useful for wrapping a commonly used complex query; we can represent data in the database tables using views named query, we can define views using one or more tables known as base tables, the view is a logical table which represents data from one or many tables.using the SELECT command.

The query’s complexity can be simplified with the help of view as users can query a view using a SELECT command. Like a table, we can add permission to the users using a view that stores data for which we need authorized users only.

How to Create PostgreSQL Views?

Let us see how to create the views:

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

CREATE [OR REPLACE][TEMP OR TEMPORARY] [RECURSIVE] VIEW view_name [(column_name [, ...])] [ WITH (view_options_name [= view_options_value] [, ... ])]

Explanation: If a view with the same name already exists, it is replaced. The view name must be unique. It should not be the same as any other view, sequence, table, foreign table or index in the same schema.

  • TEMP / TEMPORARY: If the view is created as a temporary view, then it is automatically removed at the end of the session.
  • RECURSIVE: Creates a recursive view.
  • name: The name of a view to be
  • column_name: The user can define a list of column names of the view. Only defined columns will get considered in query others are
  • WITH: ( view_options_name [= view_options_value]…)We can specify optional parameters for a view.

Creating PostgreSQL Views

We can create PostgreSQL views using various ways:

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,354 ratings)

Consider the following tables to understand the PostgreSQL views:

To understand the examples of considering the following ‘student’ and ‘Branch’ table structures

  • Student: rollno,  firstname, lastname, branch_id,  result, joining_date
  • Branch: branch_id, branch

1. WHERE clause

Code:

CREATE VIEW student_view
AS SELECT rollno, firstname, lastname, result, joining_date
FROM student
WHERE branch_id = 4;

It will create a view ‘student _view’ taking records (for rollno, firstname, lastname, result, joining_date columns) of the student table if those records contain the value 4 for branch_id column.

Code:

select * from student_view

Output:

PostgreSQL Views - 1

2. AND and OR

Code:

CREATE VIEW my_student_view
AS SELECT *
FROM student
WHERE(branch_id = 1 AND result = false)
OR(branch_id = 2 AND firstname='Jacob');

  • It will create a view ‘my_student_view’ taking records for all student table columns
  • if branch_id is 1, and the result is false.
  • or branch_id is 2, and the firstname is ‘Jacob’.

Code:

select * from student_view

Output:

PostgreSQL Views - 2

3. GROUP BY

Code:

CREATE VIEW my_student_view
AS SELECT branch_id, count (*)
FROM student
GROUP BY branch_id;

It will create a view ‘my_student_view’ taking all records grouped with respect to branch_id and stored branch_id and several students for each Branch (branch_id) from the student table.

Code:

select * from student_view

Output:

PostgreSQL Views - 3

4. ORDER BY

Code:

CREATE VIEW my_student_view
AS SELECT branch_id, count (*)
FROM student
GROUP BY branch_id
order by branch_id;

It will create a view of my_student_view, taking all the records grouped with respect to branch_id and sorted against branch_id and the number of student tables for each department (branch_id) from the student table.

Code:

select * from student_view

Output:

PostgreSQL Views - 4

5. BETWEEN and IN

Code:

CREATE VIEW my_student_view AS
SELECT * FROM student
WHERE firstname BETWEEN 'G' AND 'K'
AND rollno IN (101,102,103,105);

It will create a view ‘my_student_view’ taking all the records of employees table; if the firstname column of the student starts with any of the characters from ‘G’ through ‘K’ and rollno are any of the following 101,102,103,105

Code:

select * from student_view

Output:

PostgreSQL Views - 5

6. LIKE

Code:

CREATE VIEW my_student_view
AS SELECT *
FROM student
WHERE firstname NOT LIKE 'J%' AND lastname NOT LIKE
'C%';

It will create a view my_student_view taking all the records of the student table. If the student’s firstname does not start with ‘J’ and lastname of the student does not start with ‘C’.

Code:

select * from student_view

Output:

 LIKE

7. Subqueries

Code:

CREATE VIEW my_student_view
AS SELECT rollno,firstname,lastname
FROM student
WHERE branch_id IN(
SELECT branch_id
FROM Branch
WHERE branch_id IN (1,2)
);

It will create a view my_student_view taking all the records of rollno, firstname, lastname of student table. The subquery retrieves those branch_id’s from the Branch table, which branch_id are any of the 1 and 2.

Code:

select * from student_view

Output:

Subqueries

8. JOIN

Code:

CREATE VIEW my_student_view
AS SELECT s.rollno, s.firstname, s.lastname, b.branch
FROM student s, branch b
WHERE s.branch_id = b.branch_id;

It will create a view of my_student_view along with a JOIN statement. The JOIN statement here retrieves rollno, firstname, lastname, from student table and branch_id from branch table if branch_id of student table and that of the branch are the same.

Code:

select * from student_view

Output:

JOIN

How to Modify PostgreSQL Views?

ALTER VIEW statement modifies the definition of an existing view.

1. ALTER with SET DEFAULT

ALTER VIEW [ IF EXISTS] views_name ALTER [ COLUMN ] column_name SET DEFAULT expression

2. ALTER with DROP

ALTER VIEW [ IF EXISTS] views_name ALTER [ COLUMN ] column_name DROP DEFAULT

3. ALTER with OWNER

ALTER VIEW [ IF EXISTS] views_name OWNER TO new_view_owner

4. ALTER with RENAME

ALTER VIEW [ IF EXISTS] views_name RENAME TO new_view_name

5. ALTER with SET SCHEMA

ALTER VIEW [ IF EXISTS] views_name SET SCHEMA new_view_schema

6. ALTER with SET

ALTER VIEW [ IF EXISTS] views_name SET ( view_options_name [= view_options_value] ... )

7. ALTER with RESET

ALTER VIEW [ IF EXISTS ] views_name RESET ( view_options_name ... )

Explanation:

  • views_name: The name of the
  • IF EXISTS: Do not throw an error if the view does not exist.
  • SET/DROP DEFAULT: Set or remove the default value for a column.
  • new_view_owner: Defines view’s new owner’s username.
  • new_view_name: The new name for the view.
  • new_view_schema: The new schema for the view.
  • view_options_name : Defines view options to be set/
  • view_options_value : Defines the new value for associated view options.

To rename the view ABC to XYZ.

ALTER VIEW test_view RENAME TO testview;

How to Drop PostgreSQL Views?

  • To remove a view, we must use the DROP VIEW statement.
  • To drop a view, users must have the DROP privilege for each view.

Syntax:

DROP VIEW [IF EXISTS] view_name [, view_name] ...
[ CASCADE | RESTRICT]

Explanation:

  • IF EXISTS: Do not throw an error if the view does not exist.
  • view_name: The name (optionally schema-qualified) of the view to remove.
  • CASCADE: It will automatically remove all view-dependent objects.
  • RESTRICT: It will not allow you to delete view if any dependent object exists.

The following command will remove the view called ‘postgresql_view’:

DROP VIEW 'postgresql_view';

Conclusion

We hope you have understood the concept of PostgreSQL views. And also learned about how to create, modify, and remove PostgreSQL views.

Recommended Articles

This is a guide to PostgreSQL Views. Here we discuss Syntax and also learned about how to create, modify, and remove PostgreSQL views. You can also go through our other related articles to learn more –

  1. PostgreSQL Data Types
  2. PostgreSQL WHERE Clause
  3. Relational Database
  4. What is PostgreSQL?
  5. Learn the Examples of PostgreSQL FETCH
  6. How to Work Sequence in PostgreSQL?
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
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

ISO 10004:2018 & ISO 9001:2015 Certified

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

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*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 Login

Forgot Password?

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.

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.

Let’s Get Started

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

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more