43

I am confused with the USING keyword which is used to join two tables in postgres. I first saw it in another SO post Compare two tables in postgres. I checked the manual for postgres 2.6. Joins Between Tables.
I can't understand how postgres identified the user_id to be joined (in the SO post).

2 Answers 2

65

As the PostgreSQL documentation states:

The USING clause is a shorthand that allows you to take advantage of the specific situation where both sides of the join use the same name for the joining column(s). It takes a comma-separated list of the shared column names and forms a join condition that includes an equality comparison for each one. For example, joining T1 and T2 with USING (a, b) produces the join condition ON T1.a = T2.a AND T1.b = T2.b.

So simply said, in this case both tables have the column user_id and the join is done based on them.

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

1 Comment

@NandakumarV The documentation could use a bit of cross-linking or enhancement, I also had to do some digging to actually find the place where this is explained
1

A USING clause can be used with an EXECUTE statement in PL/pgSQL language(LANGUAGE plpgsql) for a function, procedure and DO statement.

For example, you can use a USING clause with an EXECUTE statement in a DO statement as shown below:

*Memos:

  • v1 and v2 assigned to the USING clause can be used multiple times.
  • You must use $1 and $2instead of v1 and v2 in "" of the EXECUTE statement otherwise there is error.
DO $$
DECLARE
  v1 TEXT := 'Apple';
  v2 TEXT := 'Kiwi';
  row RECORD;
BEGIN
  EXECUTE 'SELECT $1, $2, $2, $1' INTO row USING v1, v2;
  RAISE INFO '%', row; -- INFO:  (Apple,Kiwi,Kiwi,Apple)
END
$$;

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.