2

I am running a query with join from 2 tables having similarly named index "time". I want to return the result with the same named index "time".

SELECT "tbl1"."a"                       "a", 
       "tbl1"."b"                       "b", 
       "tbl2"."c"                       "c", 
       COALESCE("tbl"."time", "tb2"."time") "time" 
FROM   "tbl1" 
       FULL OUTER JOIN "tbl2" 
                    ON "tbl1"."timestamp" = 
                       "tbl2"."timestamp" 
ORDER BY "time"

This query returns an error that "time" is redundant (in ORDER BY).

If I change alias "time" to something else - it will work. But I do want that query will return "time"

If I change ORDER BY to

ORDER BY COALESCE("tbl"."time", "tb2"."time")

It will also work, but as far as I understand it will do the search for Nones twice and extend execution time (isn't it?).

3
  • You can use that function call in your ORDER BY clause, it will not be executed second time. Commented Nov 28, 2018 at 12:43
  • What is the error you're getting. There is nothing wrong with your query. Commented Nov 28, 2018 at 12:44
  • "ERROR: column reference "time" is ambigious" Commented Nov 28, 2018 at 12:56

2 Answers 2

3

You can use positional column numbers instead of names:


SELECT "tbl1"."a"                       "a", 
       "tbl1"."b"                       "b", 
       "tbl2"."c"                       "c", 
       COALESCE("tbl"."time", "tb2"."time") "time" 
FROM   "tbl1" 
       FULL OUTER JOIN "tbl2" 
                    ON "tbl1"."timestamp" = 
                       "tbl2"."timestamp" 
ORDER BY 4;

This will also work forGROUP BY.

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

1 Comment

Wow! I didn't even knew it!
2

You could use a lateral join:

SELECT "tbl1"."a"                       "a", 
       "tbl1"."b"                       "b", 
       "tbl2"."c"                       "c", 
       v.time
FROM "tbl1" FULL OUTER JOIN
     "tbl2" 
     ON "tbl1"."timestamp" = "tbl2"."timestamp" CROSS JOIN LATERAL
     (VALUES (COALESCE("tbl"."time", "tb2"."time")) as v(time)
ORDER BY v."time";

I would suggest that you write your queries so all the double quotes are not needed.

1 Comment

Very interesting approach also !

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.