Sequelize upsert method - Tutorial with example JS code

Learn how to perform a single row insert/ update using Sequelize upsert method

Posted on January 11, 2022


Sequelize v6 comes with a native Model.upsert() method that you can use to perform an INSERT ... ON CONFLICT DO UPDATE SQL statement.

The upsert() method accepts an object of data with the property keys serving as the column names and the property values as the column values.

The method would then return an array of two elements:

  • The instance the Model where you call the method, returning the new/updated row
  • The created boolean value, which tells you whether the record was created (true) or updated (false)

The syntax of the upsert() method is as shown below

const [instance, created] = await MyModel.upsert({
  // your new row data here
});

Or if you prefer promise-based syntax:

MyModel.upsert({
  // your new row data here
}).then(([instance, created]) => {
  // what to do on returned values
});

Let’s see an example of the upsert method in action next.

Suppose you have a table named Cities with the following data:

+----+------------+------------+
| id | cityName   | population |
+----+------------+------------+
|  1 | York       |     467000 |
|  2 | Bristol    |     467000 |
|  3 | Manchester |     210000 |
|  4 | London     |    8000000 |
+----+------------+------------+

Using the upsert() method, you can perform an insert or update to a specific row as shown below:

const [city, created] = await City.upsert({
  cityName: "York",
  population: 20000,
});

console.log(created); // true
console.log(city); // City object

In MySQL, the generated SQL statement would be as follows:

INSERT INTO `Cities` (`cityName`, `population`)
  VALUES (?, ?)
ON DUPLICATE KEY
  UPDATE
    `cityName` = VALUES (`cityName`),
    `population` = VALUES (`population`);

The model name City is transformed into Cities because Sequelize automatically converts the model name into its plural form.

For PostgreSQL and SQLite, the SQL syntax will use ON CONFLICT DO UPDATE as shown below:

INSERT INTO "Cities" ("id", "cityName", "population")
  VALUES ($1, $2, $3)
ON CONFLICT ("id")
  DO UPDATE SET
    "id" = EXCLUDED."id",
    "cityName" = EXCLUDED."cityName",
    "population" = EXCLUDED."population"
  RETURNING
    "id", "cityName", "population";

Without specifying a column with a unique constraint in your upsert() method, the method will do a normal INSERT statement.

The data in the table becomes the following:

+----+------------+------------+
| id | cityName   | population |
+----+------------+------------+
|  1 | York       |     467000 |
|  2 | Bristol    |     467000 |
|  3 | Manchester |     210000 |
|  4 | London     |    8000000 |
|  5 | York       |      20000 |
+----+------------+------------+

To make the upsert() method perform an UPDATE statement, you need to specify the primary key in the method argument:

const [city, created] = await City.upsert({
  id: 5,
  cityName: "Glasgow",
  population: 99999,
});

With the id key specified in the example above, an UPDATE statement will be executed on the corresponding table row:

+----+------------+------------+
| id | cityName   | population |
+----+------------+------------+
|  1 | York       |     467000 |
|  2 | Bristol    |     467000 |
|  3 | Manchester |     210000 |
|  4 | London     |    8000000 |
|  5 | Glasgow    |      99999 |
+----+------------+------------+

And that’s how the Sequelize upsert() method works.

This method allows you to insert/update a specific row without having to write a raw query.

Please note that the upsert() method is only available in Sequelize version 6. If you’re using Sequelize < 6 then you need to update your sequelize module dependency first.

Personal Finance Rules


*Some important Personal Finance Rules*

*Rule of 72*


No. of yrs required to double your money at a given rate, U just divide 72 by interest rate

Eg, if you want to know how long it will take to double your money at 8% interest, divide 72 by 8 and get 9 yrs

 

At 6% rate, it will take 12 yrs

At 9% rate, it will take 8 yrs


 

*Rule of 114*

 

No. of years required to triple your money at a given rate, U just divide 114 by interest rate.

 

For example, if you want to know how long it will take to triple your money at 12% interest, divide 114 by 12 and get 9.5 years

 

At 6% interest rate, it will take 19yrs


 

*Rule of 144*

 

No. of years required to quadruple your money at a given rate, U just divide 144 by interest rate.

 

For eg, if you want to know how long it will take to quadruple your money at 12% interest, divide 144 by 12 and get 12 yrs.

 

At 6% interest rate, it will take 24yrs


 

*Rule of 70*

 

Divide 70 by current inflation rate to know how fast the value of your investment will get reduced to half its present value. 

 

Inflation rate of 7% will reduce the value of your money to half in 10 years.


 

*4% Rule for Financial Freedom*

 

Corpus Reqd- 25*Annual Expenses

 

Eg- annual expense is 500,000 then corpus required to retire is 1.25 cr.

 

Put 50% into fixed income & 50% into equity.

 

Withdraw 4% every yr, i.e.5 lac.

 

This rule works for 96% of time in 30 yr period


 

*100 minus your age rule*

 

This rule is used for asset allocation. Subtract your age from 100 to find out, how much of your portfolio should be allocated to equities

 

Age 30

 

Equity : 70%

Debt : 30%

 

Age 60

 

Equity : 40%

Debt : 60%


 

*10-5-3 Rule*

 

One should have reasonable returns expectations

 

10℅ Rate of return - Equity / Mutual Funds

5℅ - Debts ( Fixed Deposits or Other Debt instruments)

3℅ - Savings Account


 

*50-30-20 Rule - Allocation*

 

Divide your income into

50℅ - Needs - Groceries, rent, emi

30℅ - Wants - Entertainment, vacations, etc

20℅ - Savings - Equity, MFs, Debt, FD, etc

 

Atleast try to save 20℅ of your income.

You can definitely save more

 


*3X Emergency Rule*

 

Always put atleast 3 times your monthly income in Emergency funds for emergencies such as Loss of employment, medical emergency, etc.

 

3 X Monthly Income

 

You can have around 6 X Monthly Income to be on a safer side


 

*40℅ EMI Rule*

 

Never go beyond 40℅ of your income into EMIs.

 

Say you earn, 50,000 per month. So you should not have EMIs more than 20,000 .

 

This Rule is generally used by Finance companies to provide loans. You can use it to manage your finances.


 


*Life Insurance Rule *

 

Always have Sum Assured as 20 times of your Annual Income

 

20 X Annual Income

 

Say you earn 5 Lacs annually, u shud at least have 1 crore insurance by following this Rule