Processing of null values in PostgreSQL

Source: Internet
Author: User
Tags psql

Processing of null values in PostgreSQL

When a field value is null in the addition, subtraction, multiplication, division, and Division operations, the output results often disappoint us and we cannot get the expected values, you can use coalesce to convert a null field to a default value to improve the operation effect.

Coalesce function usage: coalesce (field name, default value), simple ~

Demo: [root @ dbserver ~] # Su-postgres-bash-3.2 $ psql music psql (9.5beta2) Input "help" to obtain help information. music = # create table test_null (id int, num1 int, num2 int); CREATE TABLE

Insert data. Some values are normal numbers, and others are null values: null: music = # INSERT into test_null values (1,100,100); insert 0 1 music = # insert into test_null values (2,200,200 ); INSERT 0 1 music = # insert into test_null values (3, null, 100); INSERT 0 1 music = # insert into test_null values (4,300, null ); INSERT 0 1 music = # insert into test_null values (5, null, 500); INSERT 0 1

Check the data in the table and find that all null fields are null: music = # select * from test_null; id | num1 | num2 ---- + ------ 1 | 100 | 100 2 | 200 | 200 3 | 100 4 | 300 | 5 | 500 (5 rows of Records)



When you view the result of a direct operation, you will find that all the operation results for null values are null: music = # select num1 + num2 from test_null ;? Column? ---------- 200 400 (5 rows of Records)



After using the coalesce function, you can solve the null problem: music = # select coalesce (num1, 0) + coalesce (num2, 0) from test_null ;? Column? ---------- 200 400 100 300 500 (5 rows of Records)

Here, the default value of coalesce is 0. You can also set it to another value. For example, you can set the default value of human body temperature to 36, freezing point to 0, and boiling point to 100.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.