Skip to Content

Solved: How do I perform increment percentage calculations in SQL INSERT or UPDATE statement in PostgreSQL?

Question

I have a product table and I need to update the amount in the column table (float4 datatype) based on the increment percentage column. Example SQL command as below:

CREATE TABLE public."Product" (id int4 NOT NULL DEFAULT, "incrementPercentage" float4 NULL, "amount" float4 NULL, ...);

The incrementPercentage column might have a value or it might be empty (null), I like to know if the UPDATE statement with a CASE statement will work best. I would like to limit the value to 2 decimal places as well.

UPDATE Product
SET amount = CASE WHEN incrementPercentage IS NOT NULL THEN ((incrementPercentage/100)*incrementPercentage + amount) ELSE amount END

Answer

Refer to PostgreSQL 14 documentation related to Data Types, float4 is an alias for real. You might want to check to this statement in Arbitrary Precision Numbers portion:

The data types real and double precision are inexact, variable-precision numeric types.

You’ll need to go with numeric. With numeric you can also specify your precision. With real, I believe you’ll need to take care of precision yourself.

Alex Lim is a certified IT Technical Support Architect with over 15 years of experience in designing, implementing, and troubleshooting complex IT systems and networks. He has worked for leading IT companies, such as Microsoft, IBM, and Cisco, providing technical support and solutions to clients across various industries and sectors. Alex has a bachelor’s degree in computer science from the National University of Singapore and a master’s degree in information security from the Massachusetts Institute of Technology. He is also the author of several best-selling books on IT technical support, such as The IT Technical Support Handbook and Troubleshooting IT Systems and Networks. Alex lives in Bandar, Johore, Malaysia with his wife and two chilrdren. You can reach him at [email protected] or follow him on Website | Twitter | Facebook

    Ads Blocker Image Powered by Code Help Pro

    Your Support Matters...

    We run an independent site that is committed to delivering valuable content, but it comes with its challenges. Many of our readers use ad blockers, causing our advertising revenue to decline. Unlike some websites, we have not implemented paywalls to restrict access. Your support can make a significant difference. If you find this website useful and choose to support us, it would greatly secure our future. We appreciate your help. If you are currently using an ad blocker, please consider disabling it for our site. Thank you for your understanding and support.