1

Joins are the one thing I could never get my head around, ie, which type to use and how they actually work. I need to write a query and I know I will need a join for it.

The database is postgres.

Basic table set up is like this (some details redacted)

rates (
rates_id Primary Key, Auto Increment
state String, can either be 'current' or 'history'
)

rates_records (
rates_records_id Primary key, auto increment
rates_id = integer
column_1,
column_2
)

Every rates_records entry has rates_id set to a value that exists in the rates table

I want to update every rates_records row and modify the column_1 and column_2 data where the associated rates state = 'current'

How would I do this? Thanks

2 Answers 2

2

An alternative to Stefan's answer.

update rates_records 
   set column_1 = 'foo', 
       column_2 = 'bar'
from rates 
  where rates.rates_id = rates_records.rates_id
    and rates.state = 'current';

More details and examples are in the manul: http://www.postgresql.org/docs/current/static/sql-update.html

Which format you prefer is basically a matter of taste. I don't believe one is better or faster than the other (Stefan's answer being standard SQL so it's portable across DBMS).

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

3 Comments

Actually, besides being shorter, this should be substantially faster than the IN variant, where you also have a redundant join operation. It's the way to go.
@ErwinBrandstetter: are you sure the IN variant would be faster? Postgres is not bad at optimizing those things.
IN is slower, not faster. While IN is generally the slowest option, the redundant JOIN is the more important factor here.
0
update rates_records set column_1 = 'this', column_2 = 'that'
where rates_records_id 
in (select rates_records_id from rates_records rr 
join rates r on rr.rates_id = r.rates_id where state = 'current')

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.