Database Research & Development

  • Home
  • NoSQL
    • NoSQL
    • Cassandra
  • Databases
    • Database Theory
    • Database Designing
    • SQL Server Coding Standards
    • SQL Server
    • PostgreSQL
    • MySQL
    • Greenplum
    • Linux
  • Interviews
    • SQL Server Interviews
    • MySQL Interviews
    • SQL Puzzles
  • DBA Scripts
    • SQL Server DBA Scripts
    • PostgreSQL DBA Scripts
    • MySQL DBA Scripts
    • Greenplum DBA Scripts
  • Home
  • Blog Archives !
  • (: Laugh@dbrnd :)
  • Contact Me !
sqlserverinterviews
Home 2016 August PostgreSQL: Optimized way to get first Record per each GROUP (using DISTINCT ON, LATERAL)

PostgreSQL: Optimized way to get first Record per each GROUP (using DISTINCT ON, LATERAL)

This article is half-done without your Comment! *** Please share your thoughts via Comment ***

Dont you think, this is a very common requirement for most of the Database Developer.

Yes, MySQL Developer can visit this article.

Find top N records for each group in MySQL

In PostgreSQL, We can get a first record for each GROUP using different options like:

  • Using DISTINCT ON
  • Using LATERAL
  • CTE with ROW_NUMBER()
  • CTE with LATERAL
  • Subquery with ROW_NUMBER()
  • Using array_agg()

In this demonstration, I am going to give two optimized solutions to get one record per each GROUP.

Create a table with Sample records:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
CREATE TABLE tbl_Employees
(
EmpID INT
,EmpName CHARACTER VARYING
,EmpDepartment CHARACTER VARYING
,EmpSalary INT
);
 
INSERT INTO tbl_Employees
VALUES
(1,'Anvesh','Database',90000)
,(2,'Jenny','JAVA',65000)
,(3,'Martin','PHP',85000)
,(4,'Roy','PHP',94000)
,(5,'Eric','PHP',70000)
,(6,'Rajesh','Animation',50000)
,(7,'Mahi','Database',40000)
,(8,'Sofia','JAVA',60000);

First Solution using DISTINCT ON:
As per the Postgres official document,

The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s).
The ORDER BY clause will normally contain additional expression(s) that determine the desired precedence of rows within each DISTINCT ON group.

1
2
3
4
SELECT DISTINCT ON (EmpDepartment) *
FROM tbl_Employees
ORDER BY EmpDepartment
,EmpSalary DESC;
Second Solution using LATERAL:
A LATERAL allows sub-queries to reference columns provided by preceding FROM items.
1
2
3
4
5
6
7
8
9
10
SELECT DISTINCT T.*
FROM tbl_Employees e
,LATERAL
(
SELECT *
FROM tbl_Employees
WHERE EmpDepartment = e.EmpDepartment
ORDER BY EmpSalary DESC
LIMIT 1
) AS T;

The Result of both the solution :

1
2
3
4
5
6
empid | empname | empdepartment | empsalary
-------+---------+---------------+-----------
6 | Rajesh | Animation | 50000
1 | Anvesh | Database | 90000
2 | Jenny | JAVA | 65000
4 | Roy | PHP | 94000
Aug 25, 2016Anvesh Patel
PostgreSQL: password authentication failed for user "postgres" in UbuntuPostgreSQL: How to increase the performance of Bulk Insertion (INSERT)
Anvesh Patel
Anvesh Patel

Database Engineer

August 25, 2016 PostgreSQLAnvesh Patel, database, database research and development, dbrnd, DISTINCT ON, group by, LATERAL, plpgsql, Postgres Query, postgresql, PostgreSQL Administrator, PostgreSQL Error, PostgreSQL Programming, PostgreSQL Tips and Tricks
About Me!

I'm Anvesh Patel, a Database Engineer certified by Oracle and IBM. I'm working as a Database Architect, Database Optimizer, Database Administrator, Database Developer. Providing the best articles and solutions for different problems in the best manner through my blogs is my passion. I have more than six years of experience with various RDBMS products like MSSQL Server, PostgreSQL, MySQL, Greenplum and currently learning and doing research on BIGData and NoSQL technology. -- Hyderabad, India.

About DBRND !

dbrnd

This is a personal blog (www.dbrnd.com).

Any views or opinions represented in this blog are personal and belong solely to the blog owner and do not represent those of people, institutions or organizations that the owner may or may not be associated with in professional or personal capacity, unless explicitly stated.

Feel free to challenge me, disagree with me, or tell me I’m completely nuts in the comments section of each blog entry, but I reserve the right to delete any comment for any reason whatsoever (abusive, profane, rude, or anonymous comments) - so keep it polite.

The content of this website is protected by copyright. No portion of this website may be copied or replicated in any form without the written consent of the website owner.

Recent Comments !
  • Anvesh Patel { Sure will do... } – May 27, 12:43 PM
  • Anvesh Patel { Great... } – May 27, 12:41 PM
  • Anvesh Patel { Great... } – May 27, 12:39 PM
  • Anvesh Patel { Great... } – May 27, 12:36 PM
  • Anvesh Patel { Great... } – May 27, 12:28 PM
  • Anvesh Patel { Great... } – May 27, 12:27 PM
  • Anvesh Patel { Great... } – May 27, 12:16 PM
  • Older »
Follow Me !
  • facebook
  • linkedin
  • twitter
  • youtube
  • google
  • flickr
© 2015 – 2019 All rights reserved. Database Research & Development (dbrnd.com)
Posting....