Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
How to Efficiently Convert Rows to Columns in MariaDB?
Next article icon

How to Efficiently Convert Rows to Columns in PostgreSQL?

Last Updated : 17 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Converting rows to columns, often referred to as pivoting or transposing, is a crucial aspect of data transformation in SQL. This technique is useful for improving data readability, facilitating analysis, aligning data formats with the requirements of reporting tools, and optimizing queries. In PostgreSQL, we can achieve this using methods like the CASE statement and the CROSSTAB function from the tablefunc extension.

This article will walk you through how to manipulate and convert rows to columns in PostgreSQL, with practical examples. We’ll cover two approaches: using CASE statements and the CROSSTAB function to convert rows to columns, along with the necessary steps to implement them efficiently.

How to Convert Columns to Rows in PostgreSQL

Before we begin, it’s essential to understand the structure of our data. Identify the columns that need to be pivoted and the unique identifiers that link rows together. In PostgreSQL, there are two popular methods to perform this transformation:

  • Using CASE Statements
  • Using CROSSTAB function

Method 1: Using CASE Statements

One easy way to convert rows to columns in PostgreSQL is by using the CASE statement along with aggregation functions(MAX, MIN, SUM, etc...). This approach is suitable when we have a limited number of distinct values in the column we want to transpose. Here a table needs one unique key column to apply group-by clause.

Syntax:

SELECT
id,
AGGR_FUNC(CASE WHEN column_name = 'value1' THEN result_column END) AS new_column1,
AGGR_FUNC(CASE WHEN column_name = 'value2' THEN result_column END) AS new_column2
FROM
table_name
GROUP BY
id;

key terms

  • AGGR_FUNC: An aggregate function like SUM(), MIN(), or MAX().
  • id: The unique identifier for rows in the table.
  • column_name: The column whose values will determine the new columns.

Example: Converting Rows to Columns Using CASE Statements

The following example will show how the CASE statement can be used to manually pivot data, allowing us to display employee names based on their department in separate columns. To convert the distinct dept values (Sales and Accounting) into columns, we can write the following query using CASE statement.

Step 1: Create the Employees Table

CREATE TABLE EMPLOYEE (
empId INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept TEXT NOT NULL
);

INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales');
INSERT INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting');
INSERT INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales');

Output

empIdnamedept
0001ClarkSales
0002DaveAccounting
0003AvaSales

Step 2: Convert Rows to Columns Using the CASE Statement

To pivot the distinct dept values (Sales and Accounting) into separate columns, we can write the following query using the CASE statement:

Query:

SELECT
empid,
MAX(CASE WHEN dept = 'Sales' THEN name END) AS Sales,
MAX(CASE WHEN dept = 'Accounting' THEN name END) AS Accounting
FROM
Employee
GROUP BY
empid;

Output

using-case-statemnet
Using Case statement

Explanation:

  • The two distinct values in the dept column (Sales and Accounting) are pivoted into columns.
  • For each empid, we use CASE to conditionally display the employee names in their respective department columns.
  • For example, Clark appears in the Sales column for empid 0001, while Dave appears in the Accounting column for empid 0002.

This approach is suitable when you have a small and manageable number of distinct values to pivot. However, if we are dealing with a dynamic set of values, the CROSSTAB function is a more efficient solution.

Method 2: Using the CROSSTAB Function

PostgreSQL provides the crosstab function, which is part of the tablefunc extension. This function simplifies the process of transposing data when dealing with unknown values or dynamic values by automatically converting rows into columns. Ensure that the tablefunc extension is installed and enabled before using it.

Step 1: Install the tablefunc Extension

Before using the CROSSTAB function, we need to install the tablefunc extension. Run the following command to enable it:

CREATE EXTENSION IF NOT EXISTS tablefunc;

Syntax:

SELECT * FROM crosstab(
'SELECT id, category, value FROM your_table ORDER BY 1, 2',
'SELECT DISTINCT category FROM your_table ORDER BY 1'
) AS ct(id type, column1 type, column2 type, ...);

key terms

  • crosstab: The function to pivot the table.
  • The first argument is a query that retrieves the data to be pivoted.
  • The second argument provides the list of unique values (to be turned into columns).

Example: Converting Rows to Columns Using CROSSTAB Function

In this example, the CROSSTAB function is used to dynamically convert the dept values into columns. We will use the same EMPLOYEE table to demonstrate how to convert rows to columns using the CROSSTAB function. The first query retrieves the empid, dept, and name values, and the second query fetches the distinct departments (Sales and Accounting).

Query:

SELECT * FROM crosstab(
'SELECT empid, dept, name FROM Employee ORDER BY 1,2',
'SELECT DISTINCT dept FROM Employee ORDER BY 1'
) AS ct(empid int, Sales VARCHAR(50), Accounting VARCHAR(50));

Output

Using-CROSSTAB-function
Using CROSSTAB function

Explanation:

  • The crosstab function dynamically transforms the data based on the distinct values in the dept column.
  • It automatically creates separate columns for each department and fills them with the appropriate employee names.

Ensure that the source query (SELECT empid, dept, name FROM Employee ORDER BY 1, 2) is correctly ordered, as the CROSSTAB function relies on the proper order to work.

Conclusion

In PostgreSQL, transposing rows to columns can be efficiently acheived using either CASE statements or the CROSSTAB function. The CASE statement approach is ideal for smaller datasets with a limited number of distinct values, while the CROSSTAB function is better suited for more dynamic and complex tasks. Both methods are invaluable for data transformation, reporting, and analysis in PostgreSQL.


Next Article
How to Efficiently Convert Rows to Columns in MariaDB?
author
nikhilkalburgi
Improve
Article Tags :
  • PostgreSQL
  • Databases
  • PostgreSQL Query

Similar Reads

  • How to Efficiently Convert Rows to Columns in PL/SQL?
    In Oracle PL/SQL, converting rows into columns is a common operation, especially useful for reporting, data analysis, and reformatting data for easy visualization. PL/SQL, or Procedural Language/Structured Query Language, is a powerful procedural extension to SQL, created by Oracle, that integrates
    5 min read
  • How to Efficiently Convert Rows to Columns in SQL?
    In SQL, rows and columns are the fundamental building blocks of a database. Rows represent individual records, while columns represent the attributes or characteristics of those records. However, there may be instances where we need to convert rows to columns in order to better analyze and manipulat
    5 min read
  • How to Efficiently Convert Rows to Columns in MariaDB?
    In the area of database management, the ability to convert rows to columns efficiently is a valuable skill. MariaDB, a popular open-source relational database management system offers various methods to achieve this transformation. In this article, we'll learn about How to Convert Rows into Columns
    3 min read
  • How to Convert Rows into Columns in MySQL?
    Converting rows into columns, also known as pivoting or transposing, is a common operation in DBMS, and MySQL provides robust functionality for achieving this transformation. This process is useful to reshape data for better analysis or reporting. This guide will explore the syntax, usage, and examp
    3 min read
  • SQL Query to Convert Rows to Columns in SQL Server
    In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we h
    2 min read
  • Excel Transpose: Convert Rows to Columns (4 Easy Methods)
    Have you ever needed to switch rows to columns or vice versa in Excel without retyping your data? The Transpose function in Excel makes this process quick and hassle-free. Whether you're working with simple data sets or complex tables, understanding how to use Excel Paste Special Transpose or formul
    8 min read
  • Compute a Difference (Delta) Between Two Columns on Different Rows in postgreSQL
    In PostgreSQL the modern relational database system, two types of queries are supported: SQL for the traditional relational databases and JSON for the non-relational databases. It is free and anybody can use it. The difference (delta) computation between the values of two columns of PostgreSQL at di
    5 min read
  • How to Set a NOT NULL Column into NULL in PostgreSQL?
    PostgreSQL is an open-source relational database management system in short RDBMS. It is commonly known for its reliability and vast feature set. We can clearly state that it is one of the most powerful RDBMS available. We often create some columns with NOT NULL constraints but later on, there will
    4 min read
  • How to Combine Two Columns into One in R dataframe?
    In this article, we will discuss how to combine two columns into one in dataframe in R Programming Language.  Method 1 : Using paste() function This function is used to join the two columns in the dataframe with a separator. Syntax: paste(data$column1, data$column2, sep=" ") where data is the input
    2 min read
  • How to Use STRING_AGG to Concatenate Strings in PostgreSQL?
    In database management, aggregating and concatenating strings is a common requirement. PostgreSQL provides a powerful solution for this with the STRING_AGG function. This article explores how to leverage STRING_AGG to concatenate strings in PostgreSQL efficiently, offering multiple approaches to cat
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences