Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning PostgreSQL

You're reading from   Learning PostgreSQL Create, develop and manage relational databases in real world applications using PostgreSQL

Arrow left icon
Product type Paperback
Published in Nov 2015
Publisher Packt
ISBN-13 9781783989188
Length 464 pages
Edition 1st Edition
Arrow right icon
Toc

Table of Contents (16) Chapters Close

Preface 1. Relational Databases FREE CHAPTER 2. PostgreSQL in Action 3. PostgreSQL Basic Building Blocks 4. PostgreSQL Advanced Building Blocks 5. SQL Language 6. Advanced Query Writing 7. Server-Side Programming with PL/pgSQL 8. PostgreSQL Security 9. The PostgreSQL System Catalog and System Administration Functions 10. Optimizing Database Performance 11. Beyond Conventional Data types 12. Testing 13. PostgreSQL JDBC 14. PostgreSQL and Hibernate Index

Advanced SQL


In the following sections, some other advanced SQL techniques will be introduced:

  • The DISTINCT ON clause, which helps finding the first records in groups

  • The set returning functions, which are functions that return relations

  • LATERAL joins, which allow subqueries to reference each other

  • Some special aggregating functions

Selecting the first records

Quite often it is necessary to find the first records based on some criteria. For example, let's take the car_portal database; suppose it is required to find the first advertisement for each car_id in the advertisement table.

Grouping can help in this case. It will require a subquery to implement the logic:

SELECT advertisement_id, advertisement_date, adv.car_id,
    seller_account_id
  FROM car_portal_app.advertisement adv
  INNER JOIN
  (
    SELECT car_id, min(advertisement_date) min_date
      FROM car_portal_app.advertisement
      GROUP BY car_id
  ) first ON adv.car_id=first.car_id AND
    adv.advertisement_date = first.min_date;...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime