Search code examples
sqlrubysequel

Using Sequel, can I create UPDATE statements with a FROM clause


Using Sequel I'd like to create an UPDATE statement like the following (from Postgres docs)

UPDATE employees SET sales_count = sales_count + 1 FROM accounts
  WHERE accounts.name = 'Acme Corporation'
  AND employees.id = accounts.sales_person;

However, looking at the Sequel documentation it's not clear where there's any way to create the FROM clause.

Is there a way to do this?

Thanks!


Solution

  • OK, Ben Lee's answer got me going in the right direction. Solution:

    DB[:employees].from(:employees, :accounts).
      where(:accounts__name => 'Acme Corporation').
      update_sql(:employees__sales_count => "employees.sales_count + 1".lit)
    

    I'm a bit uncertain about the use of .lit here, but it does seem to do the trick. (Also, I'm using update_sql rather than update to produce the SQL output rather than running the command.)

    Result, as desired:

    UPDATE "employees" 
       SET "employees"."sales_count" = employees.sales_count + 1 
      FROM "accounts"
     WHERE ("accounts"."name" = 'Acme Corporation')