Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
PostgreSQL querying through schemas

I want a query that lists all Customers who's status is "active". This query would return a list of customers who are marked as active. My problem is that I am lost on querying tables that reference other tables. Here is my schema.

 CREATE TABLE Customer (
  ID BIGSERIAL PRIMARY KEY NOT NULL,
  fNAME TEXT NOT NULL,
  lNAME TEXT NOT NULL,
  create_date DATE NOT NULL DEFAULT NOW() 
 );

 CREATE TABLE CustomerStatus (
  recordID BIGSERIAL NOT NULL,
  ID BIGSERIAL REFERENCES Customer NOT NULL,
  status TEXT NOT NULL,
  create_date DATE NOT NULL DEFAULT NOW()
 );

 INSERT INTO Customer (fNAME, lNAME) VALUES ('MARK', 'JOHNSON'), ('ERICK', 'DAWN'), ('MAY', 'ERICKSON'), ('JESS', 'MARTIN');

 INSERT INTO CustomerStatus (ID, status) VALUES (1, 'pending'), (1, 'active');     

 INSERT INTO CustomerStatus (ID, status) VALUES (2, 'pending'), (2, 'active'), (2, 'cancelled');     

 INSERT INTO CustomerStatus (ID, status) VALUES (3, 'pending'), (3, 'active');  

 INSERT INTO CustomerStatus (ID, status) VALUES (4, 'pending'); 
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I took courage to assume that record_id is serial => the latest id would be the last, to produce this qry:

t=# with a as (
  select *, max(recordid) over (partition by cs.id)
  from Customer c
  join CustomerStatus cs on cs.id = c.id
)
select *
from a
where recordid=max and status = 'active';
 id | fname |  lname   | create_date | recordid | id | status | create_date | max
----+-------+----------+-------------+----------+----+--------+-------------+-----
  1 | MARK  | JOHNSON  | 2017-04-27  |        2 |  1 | active | 2017-04-27  |   2
  3 | MAY   | ERICKSON | 2017-04-27  |        7 |  3 | active | 2017-04-27  |   7
(2 rows)

Time: 0.450 ms
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!