The Wayback Machine - https://web.archive.org/web/20241005211512/https://www.geeksforgeeks.org/postgresql-select/
Open In App

PostgreSQL – SELECT

Last Updated : 14 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The SELECT statement in PostgreSQL is one of the most powerful and flexible query statements available. It allows you to retrieve data from one or more tables in various ways by using different clauses.

Here, we will explore the basic usage of the PostgreSQL SELECT statement to query data from a database table.

Clauses used with SELECT Statement

The SELECT statement can be enhanced with several clauses to increase its flexibility and functionality:

  • DISTINCT operator: It is used to select distinct rows from a table.
  • ORDER BY clause: It is used to sort table rows.
  • WHERE clause: It is used to filter rows from a table. >LIMIT clause: It is used to select a subset of rows from the table.
  • FETCH clause: It is also used to select a subset of rows from the table.
  • GROUP BY clause: It is used to group different rows into a single group.
  • HAVING clause: It is used to filter rows from a table with specified attributes or features.
  • FROM clause: It is used to specify a column in a table.
  • Joins: It is used to join two or more tables together using joins such as ‘INNER JOIN’, ‘LEFT JOIN‘, ‘FULL OUTER JOIN‘, and ‘CROSS JOIN’ clauses.
  • Set operators: These operators such as UNION, INTERSECT, and EXCEPT are used to manipulate the different sets of data.

Basic Syntax of SELECT Statement

For the sake of simplicity we will be looking into the use of SELECT statement with FROM clause in our sample DVD rental database. The syntax for using the SELECT statement is as follows:

SELECT select_list 
FROM table_name;

Now, let’s evaluate the SELECT statement in more detail,

Firstly, we need to specify a particular column or a list of columns from where the data is to be retrieved. Commas are used to separate multiple columns, if a list of column is selected as below:

SELECT select_list1, select_list2, select_list3 FROM table_name;

For selecting all columns from the database, use

asterisk(‘*’)

as below:

SELECT * FROM table_name;

Secondly, we need to specify the name of the table from which data is to be retrieved, after the FROM keyword.

PostgreSQL SELECT Statement Examples

Now let us look into a few examples of using PostgreSQL SELECT statement in our sample database. For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link.

Example 1: Querying Data from One Column

Using SELECT statement to query data from one column.

Query:

SELECT first_name 
FROM customer;

Output:

Explanation: The query returns a list of first names from the ‘customer' table.

Example 2: Querying Data from Multiple Columns

Using SELECT statement to query data from multiple columns.

Query:

SELECT first_name, email 
FROM customer;

Output:

Explanation: The query returns a list of first names and email addresses from the ‘customer' table.

Example 3: Querying All Columns of a Table

Using SELECT statement to query data in all columns of a table.

Query:

SELECT * FROM customer;

Output:

Explanation: The query returns all columns from the ‘customer' table.

Example 4: Using SELECT Statement with Expressions

Using SELECT statement with expressions.

Query:

SELECT first_name || ' ' || last_name AS full_name, email 
FROM customer;

Output:

Explanation: The query returns the full names and email addresses of customers by concatenating the ‘first_name' and ‘last_name' columns.

Advanced Usage of SELECT Statement

1. Using DISTINCT to Remove Duplicates

Retrieve distinct rental rates from the film table.

Query:

SELECT DISTINCT rental_rate 
FROM film;

2. Sorting Results with ORDER BY

Retrieve and sort films by their title.

Query:

SELECT title, rental_rate 
FROM film
ORDER BY title;

3. Filtering Results with WHERE

Retrieve customers from a specific city.

Query:

SELECT first_name, last_name, email 
FROM customer
WHERE city = 'Los Angeles';

4. Limiting Results with LIMIT and FETCH

Retrieve the first 10 customers.

Query:

SELECT * 
FROM customer
LIMIT 10;

Or using FETCH.

Query:

SELECT * 
FROM customer
FETCH FIRST 10 ROWS ONLY;

5. Grouping Results with GROUP BY

Retrieve the count of customers by city.

Query:

SELECT city, COUNT(*) 
FROM customer
GROUP BY city;

6. Filtering Groups with HAVING

Retrieve cities with more than 5 customers.

Query:

SELECT city, COUNT(*) 
FROM customer
GROUP BY city
HAVING COUNT(*) > 5;

7. Joining Tables with JOIN

Retrieve rental information along with customer details.

Query:

SELECT c.first_name, c.last_name, r.rental_date 
FROM customer c
INNER JOIN rental r ON c.customer_id = r.customer_id;

8. Combining Results with Set Operators

Retrieve all unique cities from both customer and store tables.

Query:

SELECT city 
FROM customer
UNION
SELECT city
FROM store;

Conclusion

In conclusion, the PostgreSQL SELECT statement is a versatile and essential tool for querying data from databases. By understanding and utilizing its various clauses, you can perform complex queries efficiently. Whether you are retrieving specific columns, filtering data, or joining tables, the SELECT statement provides the flexibility needed for effective data management.



Previous Article
Next Article

Similar Reads

PostgreSQL - Connect To PostgreSQL Database Server in Python
The psycopg database adapter is used to connect with PostgreSQL database server through python. Installing psycopg: First, use the following command line from the terminal: pip install psycopg If you have downloaded the source package into your computer, you can use the setup.py as follows: python setup.py build sudo python setup.py installCreate a
4 min read
PostgreSQL - Export PostgreSQL Table to CSV file
In this article we will discuss the process of exporting a PostgreSQL Table to a CSV file. Here we will see how to export on the server and also on the client machine. For Server-Side Export: Use the below syntax to copy a PostgreSQL table from the server itself: Syntax: COPY Table_Name TO 'Path/filename.csv' CSV HEADER; Note: If you have permissio
2 min read
PostgreSQL - Installing PostgreSQL Without Admin Rights on Windows
If you are a part of a corporation, it is highly unlikely that you have the admin privileges to install any external software. But the curious souls that all software developers are, in this article, we will see the detailed process of installation of PostgreSQL without having administrator rights on our Windows machine. Installation: Follow the be
3 min read
PostgreSQL - Select Into
In PostgreSQL, the select into statement to select data from the database and assign it to a variable. Syntax: select select_list into variable_name from table_expression; In this syntax, one can place the variable after the into keyword. The select into statement will assign the data returned by the select clause to the variable. Besides selecting
2 min read
Python PostgreSQL - Select Data
In this article, we are going to see how to use select data using Python in PostgreSQL and psycopg2. Installation Open the command prompt and write the command given below. pip install psycopg2 SELECT statement is used to retrieve the required details of an existing table in PostgreSQL. The data that is returned is stored in a result table that is
3 min read
How to Select Random Row in PostgreSQL?
In PostgreSQL, selecting a random row from a table can be a useful feature in scenarios such as sampling data for analysis or displaying random content. PostgreSQL provides several techniques to achieve this, including using the RANDOM() function or the ORDER BY RANDOM() clause. In this article, we will explore these methods and demonstrate how to
4 min read
How to Select Row With Max Value in PostgreSQL
In PostgreSQL, efficiently selecting rows with maximum values from a table is a common task faced by developers and database administrators. Whether you're working on analytics, reporting, or data manipulation, knowing how to retrieve the maximum value per group can significantly enhance your SQL skills. In this article, we'll explore three powerfu
4 min read
How to Select Rows that Don't Exist in Other Table in PostgreSQL?
In PostgreSQL, there are times when we need to find records in one table that do not exist in another table. This can be useful for various data manipulation tasks and ensuring data integrity. In this article, we will explore different approaches along with examples to achieve this using PostgreSQL. By the end, you will have a clear understanding o
5 min read
What is Nested Select Statement in PostgreSQL?
Nested select statements, also known as subqueries which is a fundamental concept in PostgreSQL and play an important role in data retrieval and manipulation. In PostgreSQL, a powerful relational database management system, the nested select statements allow for complex queries by nesting one query within another. In this article, We will explore t
4 min read
How to Write a Normal Select Procedure in PostgreSQL?
PostgreSQL is an open-source relational database management system with a variety of features that allow users to operate database operations and improve the speed of queries. One of these options is the ability to write stored procedures, the SQL code that logically embeds logic for a more organized and maintained program. Here we should discuss t
4 min read
How to Select Dates Between Two Dates in PostgreSQL?
When managing a PostgreSQL database, we may often encounter scenarios where we need to filter data based on date ranges. This task is crucial for generating reports, analyzing trends, or retrieving time-sensitive information. However, querying for data within a specific date range can be a challenging task, especially when dealing with large datase
4 min read
PostgreSQL - SELECT INTO
In PostgreSQL, the SELECT INTO statement enables users to create a new table and insert data returned by a query. The new table's columns inherit the names and data types of the output columns from the SELECT clause. Unlike the standard SELECT statement, the SELECT INTO statement does not return data to the client. Let us get a better understanding
3 min read
PostgreSQL - SELECT DISTINCT clause
The SELECT statement with the DISTINCT clause to remove duplicate rows from a query result set in PostgreSQL. By leveraging the DISTINCT clause, you can ensure your query results contain only unique rows, whether you're dealing with a single column or multiple columns. The DISTINCT clause in PostgreSQL is used to return unique rows from a result se
2 min read
How to Select the Nth Row in a PostgreSQL Database Table?
In PostgreSQL, selecting specific rows is a fundamental operation frequently required for tasks such as data analysis, pagination, and reporting. The "nth" row refers to the row in a table that holds a particular position or rank, where "n" represents that specific position or ranking number. This article explores various techniques to efficiently
5 min read
PostgreSQL - Creating Updatable Views Using WITH CHECK OPTION Clause
PostgreSQL is the most advanced general purpose open source database in the world. pgAdmin is the most popular management tool or development platform for PostgreSQL. It is also an open source development platform. It can be used in any Operating Systems and can be run either as a desktop application or as a web in your browser. In this article, we
4 min read
Handling PostgreSQL BLOB data in Python
In this article, we will learn how to Handle PostgreSQL BLOB data in Python. BLOB is a Binary large object (BLOB) is a data type that can store any binary data.To store BLOB data in a PostgreSQL database, we need to use the Binary Large Object (BLOB) data type.By using the Binary Large Object (BLOB) data type, we can store any binary data in a Post
5 min read
Python | Getting started with psycopg2-PostGreSQL
PostgreSQL is a powerful, open source object-relational database system. PostgreSQL runs on all major operating systems. PostgreSQL follows ACID property of DataBase system and has the support of triggers, updatable views and materialized views, foreign keys. To connect PostgreSQL we use psycopg2 . It is the best and most friendly Database adapter
1 min read
Python | Database management in PostgreSQL
PostgreSQL is an open source object-relational database management system. It is well known for its reliability, robustness, and performance. PostgreSQL has a variety of libraries of API (Application programmable interface) that are available for a variety of popular programming languages such as Python. It provides a lot of features for Database m
6 min read
Do loop in Postgresql Using Psycopg2 Python
In this article, we use psycopg2 to loop through all data points using psycopg2 function in Python. We will first connect our PostgreSQL database using psycopg2.connect method, and pass the connection parameters such as the host, database, user, and password. Then we will create a cursor using the conn.cursor method. The cur.execute method, passes
4 min read
What is PostgreSQL - Introduction
This is an introductory article for the PostgreSQL database management system. In this we will look into the features of PostgreSQL and why it stands out among other relational database management systems. Brief History of PostgreSQL: PostgreSQL also known as Postgres, was developed by Michael Stonebraker of the University of California, Berkley. I
2 min read
Install PostgreSQL on Mac
This is a step-by-step guide to install PostgreSQL on a Mac OS machine. We will be installing PostgreSQL version 11.3 on Mac using the installer provided by EnterpriseDB in this article. There are three crucial steps for the installation of PostgreSQL as follows: Download PostgreSQL EnterpriseDB installer for MacInstall PostgreSQLVerify the install
2 min read
PostgreSQL - Loading a Database
In this article we will look into the process of loading a PostgreSQL database into the PostgreSQL database server. Before moving forward we just need to make sure of two things: PostgreSQL database server is installed on your system. A sample database. For the purpose of this article, we will be using a sample database which is DVD rental database
3 min read
PostgreSQL - NOT LIKE operator
The PostgreSQL NOT LIKE works exactly opposite to that of the LIKE operator. It is used to data using pattern matching techniques that explicitly excludes the mentioned pattern from the query result set.Its result include strings that are case-sensitive and doesn't follow the mentioned pattern. It is important to know that PostgreSQL provides with
2 min read
PostgreSQL - LIKE operator
The PostgreSQL LIKE operator is used query data using pattern matching techniques. Its result include strings that are case-sensitive and follow the mentioned pattern. It is important to know that PostgreSQL provides with 2 special wildcard characters for the purpose of patterns matching as below: Percent ( %) for matching any sequence of character
2 min read
PostgreSQL - SELF JOIN
PostgreSQL has a special type of join called the SELF JOIN which is used to join a table with itself. It comes in handy when comparing the column of rows within the same table. As, using the same table name for comparison is not allowed in PostgreSQL, we use aliases to set different names of the same table during self-join. It is also important to
3 min read
Install PostgreSQL on Linux
This is a step-by-step guide to install PostgreSQL on a Linux machine. By default, PostgreSQL is available in all Ubuntu versions as PostgreSql "Snapshot". However other versions of the same can be downloaded through the PostgreSQL apt repository. We will be installing PostgreSQL version 11.3 on Ubuntu in this article. There are three crucial steps
2 min read
PostgreSQL - Rename Database
In PostgreSQL, the ALTER DATABASE RENAME TO statement is used to rename a database. The below steps need to be followed while renaming a database: Disconnect from the database that you want to rename by connecting to a different database.Terminate all connections, connected to the database to be renamed.Now you can use the ALTER DATABASE statement
1 min read
PostgreSQL - Size of tablespace
In this article, we will look into the function that is used to get the size of the PostgreSQL database tablespace. The pg_tablespace_size() function is used to get the size of a tablespace of a table. This function accepts a tablespace name and returns the size in bytes. Syntax: select pg_tablespace_size('tablespace_name'); Example 1: Here we will
2 min read
PostgreSQL - Removing Temporary Table
In PostgreSQL, one can drop a temporary table by the use of the DROP TABLE statement. Syntax: DROP TABLE temp_table_name; Unlike the CREATE TABLE statement, the DROP TABLE statement does not have the TEMP or TEMPORARY keyword created specifically for temporary tables. To demonstrate the process of dropping a temporary table let's first create one b
2 min read
PostgreSQL - Block Structure
PL/pgSQL is a block-structured language, therefore, a PL/pgSQL function or store procedure is organized into blocks. Syntax: [ <<label>> ] [ DECLARE declarations ] BEGIN statements; ... END [ label ]; Let's analyze the above syntax: Each block has two sections: declaration and body. The declaration section is optional while the body sec
4 min read
Practice Tags :