0

Paging and sort by columns in 2 tables.

  1. customer(id, first_name, last_name)
  2. customer_email(customer_id, type, email).

One customer could have multiple emails.

Requirement: get 10 customers and sort by last_name, email.

--Sort by customer.last_name, customer_email.email

select c.*, ce.email
from customer c
inner join (select   distinct c.id, c.last_name
            from     customer c, customer_email ce 
            where    c.id = ce.customer_id 
            order by c.last_name, ce.email offset 0 limit 10
           ) AS paged_c on paged_c.id = c.id 
inner join customer_email ce on c.id = ce.customer_id
order by c.last_name, ce.email;

Doesn't work with the error

ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 6:                 order by c.last_name, ce.email offset 0 limi...
                                              ^
1
  • Describe what you are trying to do. It is not clear what output you are expecting. Commented Sep 14, 2018 at 19:04

1 Answer 1

1

PostgreSQL is right to complain about your query; your requirements are unclear.

If you want the first 10 customers, ordered by last name an e-mail, but each customer can have several e-mail addresses, how do you do that? Which of the e-mail addresses is used for sorting the customers?

The error message basically reflects that uncertainty.

Come up with a clear definition of the sort order and translate that into SQL, then PostgreSQL will be happy to run your query.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.