Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a column, all rows

I added a new column to my table but I forgot to add the :default option. Now I want to populate that column on every single row.

Is there a way to do with using the console? I've been searching google for the past hour but I can't find anything.

I know how to do it for a single object, but not for all rows of a model.

Foo.find(1).update_attribute(:myattribute, 'value') 
like image 213
Martin Petrov Avatar asked Dec 22 '10 19:12

Martin Petrov


People also ask

How do you UPDATE a column to all rows in SQL?

Syntax: UPDATE table_name SET column_name1 = new_value1, column_name2 = new_value2 ---- WHERE condition; Here table_name is the name of the table, column_name is the column whose value you want to update, new_value is the updated value, WHERE is used to filter for specific data.

How do you UPDATE multiple rows in a column?

First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.

How do I UPDATE multiple rows at once?

There are a couple of ways to do it. INSERT INTO students (id, score1, score2) VALUES (1, 5, 8), (2, 10, 8), (3, 8, 3), (4, 10, 7) ON DUPLICATE KEY UPDATE score1 = VALUES(score1), score2 = VALUES(score2);


1 Answers

Try this:

Foo.update_all(some_column: "bar") 

This will generate SQL query to database:

UPDATE "foos" SET "some_column" = "bar";  
like image 57
Jimmy Huang Avatar answered Oct 17 '22 14:10

Jimmy Huang