# How to Get the First or Last Value in a Group Using Group By in SQL

DevFeed: [How to Get the First or Last Value in a Group Using Group By in SQL](<https://devfeed.tech/articles/how-to-get-the-first-or-last-value-in-a-group-using-group-by-in-sql-33938.md>)

Original publisher: [Read original article](<https://hakibenita.com/sql-group-by-first-last-value>)

Author: Haki Benita

Published: 2019-08-12T21:00:00Z

Content type: tutorial

Language: en

Sources: [Haki Benita](<https://devfeed.tech/sources/haki-benita.md>)

Topics: [PostgreSQL](<https://devfeed.tech/topics/postgresql.md>), [SQL](<https://devfeed.tech/topics/sql.md>), [Databases](<https://devfeed.tech/topics/databases.md>)

Tags: [articles](<https://devfeed.tech/tags/articles.md>), [hash](<https://devfeed.tech/tags/hash.md>), [how-to](<https://devfeed.tech/tags/how-to.md>), [join](<https://devfeed.tech/tags/join.md>), [postgresql](<https://devfeed.tech/tags/postgresql.md>), [query](<https://devfeed.tech/tags/query.md>), [sql](<https://devfeed.tech/tags/sql.md>), [window-functions](<https://devfeed.tech/tags/window-functions.md>)

## AI overview

This tutorial explains how to obtain the first or last value in a grouped SQL query, focusing on PostgreSQL. It uses separate queries for account balances and the latest credit value, joins them to produce the complete account state, and discusses the resulting execution plan.

## Source excerpt

Getting the last value of a group in an aggregated query in PostgreSQL is a challenging task. In this article we present a simple way to get the first or last value of a group using group by.