EDUCBA

EDUCBA

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

PostgreSQL Select

By Priya PedamkarPriya Pedamkar

Home » Data Science » Data Science Tutorials » PostgreSQL Tutorial » PostgreSQL Select

PostgreSQL Select

Introduction to PostgreSQL Select

One of the most important purposes of any database is to store the data so that it can be retrieved and fetched whenever we want according to our requirements. The retrieved records are mostly used in reporting and analysis for the user or sometimes retrieving existing results to modify the same. The SELECT clause is used to fetch the data in the PostgreSQL database. We can retrieve the results from zero, one or more tables using the select clause. This article will learn how we can use the select clause to build the query statements, their syntax, and examples to better understand query building in PostgreSQL.

Syntax of PostgreSQL Select

Syntax of postgresql select are given below:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax:

SELECT [ ALL | DISTINCT | DISTINCT ON (column_or_expression) ] columns_or_expressions
FROM tables
[WHERE conditional_restrictions] [GROUP BY column_or_expression] [HAVING conditional_restrictions] [ORDER BY column_or_expression [ ASC | DESC | USING operator ] [ NULLS FIRST | NULLS LAST ]] [LIMIT [ row_count | ALL] [OFFSET value_of_offset [ ROW | ROWS ]] [FETCH { FIRST | NEXT } [ rows_to_be_fetched ] { ROW | ROWS } ONLY] [FOR { UPDATE | SHARE } OF table [ NOWAIT ]];

The select clause’s syntax is very complex and involves many possible combinations to provide flexibility to the user. We will learn the syntax by learning all the above-used clauses with the select clause.

  • ALL: To retrieve all the records that the query will fetch after applying all the conditions, restrictions and expressions.
  • DISTINCT: To retrieve only unique values of the column and expression from the retrieved results and further filter out the unique entries with respect to column or expression mentioned in the distinct parameter.
  • columns_or_expressions: This is the list of the column names or expressions that you wish to retrieve using the select query.
  • FROM: This keyword helps specify the name of the table from which you wish to retrieve the records. Further, we can use joins of type left join, right join, natural join, etc., to combine the results of two or more tables while retrieving the records.
  • WHERE: This clause helps specify the conditions, restrictions, and expressions to filter out the results while retrieving the records in the select query.
  • GROUP BY: The result set can be grouped based on some column or expression using group by statement. This is most frequently used while retrieving the aggregate functions manipulated columns like the sum or product of certain columns.
  • HAVING: The result can be filtered out further by applying the conditions and restrictions on the retrieved columns and expressions, which also include the aggregated values if used while retrieving the result.
  • ORDER BY: The resultset can be arranged in an orderly format based on certain columns and expressions when specified after the ORDER BY keyword. We can arrange the data in ascending or descending order by using ASC or DESC keyword.
  • LIMIT: The records retrieved can be limited to a certain number of rows by using the limit keyword. For example, if the query result would have resulted in 55 records and after applying the limit of 10 statements in the select query, only the first 10 records will be retrieved.
  • OFFSET: This is the number of the row from which you want to begin retrieving the records. For example, if the offset is mentioned as 5, the beginning from the 5th record, the result’s rows will be retrieved.
  • FETCH This functions similarly to the limit keyword that restricts the number of the records to be retrieved to a particular number.
  • FOR: The records can be restricted for access and are write-locked if FOR UPDATE is specifies and is allowed for reading operation but not update and insert operations by other transactions when FOR SHARE is specified.

Except FROM, all other clauses/keywords used in the above select clause syntax are optional in nature.

Examples of PostgreSQL Select

Following are the examples of postgresql select:

Let us create one example and insert a few records in the table to learn how to use a select clause to retrieve the records. Open your PostgreSQL command-line prompt and enter the following command to create a table named educba –

CREATE TABLE educba
(id INTEGER PRIMARY KEY,
technologies VARCHAR,
workforce INTEGER,
address VARCHAR);

PostgreSQL Select-1.1

Let us insert some values in the educba table using the following statement –

INSERT INTO educba VALUES (1,'java',20,'satara'),(2,'javascript',30,'mumbai'),(3,'java',20,'satara'),(4,'psql',30,'mumbai'),(5,'mysql',20,'satara'),(6,'maven',30,'mumbai'),(7,'hibernate',20,'satara'),(8,'spring',30,'mumbai'),(9,'angular',20,'satara'),(10,'html',30,'mumbai'),(11,'css',20,'satara'),(12,'reddis',30,'mumbai');

PostgreSQL Select-1.2

Let us create a simple select query statement to retrieve all the records from the educba table. Our query statement will be as follows:

SELECT * FROM educba;

Here, * represents all the columns to be retrieved and firing above query results in the following output –

PostgreSQL Select-1.3

Now we will apply the conditions using the where clause and retrieve only those records that have a workforce of 20 persons. For this, we will have to mention the condition as workforce = 20 in the where clause and our query statement will be as follows –

SELECT * FROM educba WHERE workforce=20;

PostgreSQL Select-1.4

Now, suppose we only want to retrieve the list of name of technologies with the workforce as 20, then the query statement will be as follows –

SELECT technologies FROM educba WHERE workforce=20;

PostgreSQL Select-1.5

Let us see how we can group the result based on workforce count and retrieve the technologies’ comma-separated string. For this, the query statement will be as follows:

Popular Course in this category
Sale
PostgreSQL Course (2 Courses, 1 Project)2 Online Courses | 1 Hands-on Project | 7+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (6,206 ratings)
Course Price

View Course

Related Courses

SELECT string_agg(technologies,','), workforce FROM educba GROUP BY workforce;

Output-1.6

Suppose that instead of retrieving the column head as string_agg, we can give the alias for the same using the “as” keyword as follows:

SELECT string_agg(technologies,',') as "List Of Technologies", workforce FROM educba GROUP BY workforce;

Output-1.7

Let us order the results alphabetically based on the technology’s name and limit the records to only 7 by using the limit clause. Our query statement will be as follows –

SELECT * FROM educba ORDER BY technologies ASC LIMIT 7;

Output-1.8

Recommended Articles

This is a guide to PostgreSQL Select. Here we also discuss the introduction and syntax of postgresql select and different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. PostgreSQL Like
  2. PostgreSQL round
  3. PostgreSQL GRANT
  4. PostgreSQL Inner Join

PostgreSQL Course (2 Courses, 1 Project)

2 Online Courses

1 Hands-on Project

7+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

2 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 - PostgreSQL Course (2 Courses, 1 Project) Learn More