NULL value causes blank row in SELECT results for text concatenationHow can the concatenatation of a text and a NULL value return a non-null result?Improve performance on concurrent UPDATEs for a timestamp column in PostgresSlow fulltext search due to wildly inaccurate row estimatesCan an Oracle IDENTITY column be nullable?Find most frequent values for a given columnWhy is this query with WHERE, ORDER BY and LIMIT so slow?PostgreSQL 9.5 query performance depends on JOINed column in SELECT clauseRow Locking in PostgresHow locks in Postgres behave when quitting the JVM abnormallyTimescaleDB performanceIndex on JSONB not improving query speed

NULL value causes blank row in SELECT results for text concatenation

Prepare a user to perform an action before proceeding to the next step

"Fewer errors means better products" or fewer errors mean better products."

How can you tell the version of Ubuntu on a system in a .sh (bash) script?

Best practice for keeping temperature constant during film development at home

What kind of horizontal stabilizer does a Boeing 737 have?

Planting Trees in Outer Space

Patio gate not at right angle to the house

How can a class have multiple methods without breaking the single responsibility principle

How to efficiently shred a lot of cabbage?

"Valet parking " or "parking valet"

If the Moon were impacted by a suitably sized meteor, how long would it take to impact the Earth?

Word for giving preference to the oldest child

How do I respond appropriately to an overseas company that obtained a visa for me without hiring me?

What parameters are to be considered when choosing a MOSFET?

Why didn't General Martok receive discommendation in Star Trek: Deep Space Nine?

Why do we need a voltage divider when we get the same voltage at the output as the input?

When did J.K. Rowling decide to make Ron and Hermione a couple?

Why don't short runways use ramps for takeoff?

Should I put my name first or last in the team members list?

Derivative is just speed of change?

How does the barbarian bonus damage interact with two weapon fighting?

Easy way to get process information from a window

How to litter train a cat if both my husband and I work away from home all day?



NULL value causes blank row in SELECT results for text concatenation


How can the concatenatation of a text and a NULL value return a non-null result?Improve performance on concurrent UPDATEs for a timestamp column in PostgresSlow fulltext search due to wildly inaccurate row estimatesCan an Oracle IDENTITY column be nullable?Find most frequent values for a given columnWhy is this query with WHERE, ORDER BY and LIMIT so slow?PostgreSQL 9.5 query performance depends on JOINed column in SELECT clauseRow Locking in PostgresHow locks in Postgres behave when quitting the JVM abnormallyTimescaleDB performanceIndex on JSONB not improving query speed






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have a query for producing some text for creating some VALUES text to put in a .sql file for inserting some rows. I get a blank line in the results:



postgres=# SELECT ' (' || obj_id || ', ''' || obj_type || '''),' FROM il2.objects WHERE obj_id < 11 ORDER BY obj_id;
?column?
-------------------------
(1, 'ScienceDomain'),

(3, 'PIs'),
(10, 'Instrument'),
(4 rows)


Doing a select *, it's pretty clear it's being caused by the obj_type being NULL for obj_id 2:



postgres=# SELECT * FROM il2.objects WHERE obj_id < 11;
obj_id | obj_type
--------+---------------
10 | Instrument
1 | ScienceDomain
2 |
3 | PIs
(4 rows)


(confirming it's NULL):



postgres=# SELECT * FROM il2.objects WHERE obj_type IS NULL;
obj_id | obj_type
--------+----------
2 |


Why is the result of the first SELECT giving me a blank row?

Even casting obj_type::text still gave me a blank row.




Additional Info:
The schema, for what it's worth:



postgres=# d il2.objects
Table "il2.objects"
Column | Type | Collation | Nullable | Default
----------+-------------------+-----------+----------+----------------------------------
obj_id | integer | | not null | generated by default as identity
obj_type | character varying | | |
Indexes:
"objects_pkey" PRIMARY KEY, btree (obj_id)









share|improve this question
































    1















    I have a query for producing some text for creating some VALUES text to put in a .sql file for inserting some rows. I get a blank line in the results:



    postgres=# SELECT ' (' || obj_id || ', ''' || obj_type || '''),' FROM il2.objects WHERE obj_id < 11 ORDER BY obj_id;
    ?column?
    -------------------------
    (1, 'ScienceDomain'),

    (3, 'PIs'),
    (10, 'Instrument'),
    (4 rows)


    Doing a select *, it's pretty clear it's being caused by the obj_type being NULL for obj_id 2:



    postgres=# SELECT * FROM il2.objects WHERE obj_id < 11;
    obj_id | obj_type
    --------+---------------
    10 | Instrument
    1 | ScienceDomain
    2 |
    3 | PIs
    (4 rows)


    (confirming it's NULL):



    postgres=# SELECT * FROM il2.objects WHERE obj_type IS NULL;
    obj_id | obj_type
    --------+----------
    2 |


    Why is the result of the first SELECT giving me a blank row?

    Even casting obj_type::text still gave me a blank row.




    Additional Info:
    The schema, for what it's worth:



    postgres=# d il2.objects
    Table "il2.objects"
    Column | Type | Collation | Nullable | Default
    ----------+-------------------+-----------+----------+----------------------------------
    obj_id | integer | | not null | generated by default as identity
    obj_type | character varying | | |
    Indexes:
    "objects_pkey" PRIMARY KEY, btree (obj_id)









    share|improve this question




























      1












      1








      1








      I have a query for producing some text for creating some VALUES text to put in a .sql file for inserting some rows. I get a blank line in the results:



      postgres=# SELECT ' (' || obj_id || ', ''' || obj_type || '''),' FROM il2.objects WHERE obj_id < 11 ORDER BY obj_id;
      ?column?
      -------------------------
      (1, 'ScienceDomain'),

      (3, 'PIs'),
      (10, 'Instrument'),
      (4 rows)


      Doing a select *, it's pretty clear it's being caused by the obj_type being NULL for obj_id 2:



      postgres=# SELECT * FROM il2.objects WHERE obj_id < 11;
      obj_id | obj_type
      --------+---------------
      10 | Instrument
      1 | ScienceDomain
      2 |
      3 | PIs
      (4 rows)


      (confirming it's NULL):



      postgres=# SELECT * FROM il2.objects WHERE obj_type IS NULL;
      obj_id | obj_type
      --------+----------
      2 |


      Why is the result of the first SELECT giving me a blank row?

      Even casting obj_type::text still gave me a blank row.




      Additional Info:
      The schema, for what it's worth:



      postgres=# d il2.objects
      Table "il2.objects"
      Column | Type | Collation | Nullable | Default
      ----------+-------------------+-----------+----------+----------------------------------
      obj_id | integer | | not null | generated by default as identity
      obj_type | character varying | | |
      Indexes:
      "objects_pkey" PRIMARY KEY, btree (obj_id)









      share|improve this question
















      I have a query for producing some text for creating some VALUES text to put in a .sql file for inserting some rows. I get a blank line in the results:



      postgres=# SELECT ' (' || obj_id || ', ''' || obj_type || '''),' FROM il2.objects WHERE obj_id < 11 ORDER BY obj_id;
      ?column?
      -------------------------
      (1, 'ScienceDomain'),

      (3, 'PIs'),
      (10, 'Instrument'),
      (4 rows)


      Doing a select *, it's pretty clear it's being caused by the obj_type being NULL for obj_id 2:



      postgres=# SELECT * FROM il2.objects WHERE obj_id < 11;
      obj_id | obj_type
      --------+---------------
      10 | Instrument
      1 | ScienceDomain
      2 |
      3 | PIs
      (4 rows)


      (confirming it's NULL):



      postgres=# SELECT * FROM il2.objects WHERE obj_type IS NULL;
      obj_id | obj_type
      --------+----------
      2 |


      Why is the result of the first SELECT giving me a blank row?

      Even casting obj_type::text still gave me a blank row.




      Additional Info:
      The schema, for what it's worth:



      postgres=# d il2.objects
      Table "il2.objects"
      Column | Type | Collation | Nullable | Default
      ----------+-------------------+-----------+----------+----------------------------------
      obj_id | integer | | not null | generated by default as identity
      obj_type | character varying | | |
      Indexes:
      "objects_pkey" PRIMARY KEY, btree (obj_id)






      postgresql select null concat






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 2 hours ago









      Erwin Brandstetter

      101k9 gold badges210 silver badges335 bronze badges




      101k9 gold badges210 silver badges335 bronze badges










      asked 8 hours ago









      RandallRandall

      1729 bronze badges




      1729 bronze badges























          2 Answers
          2






          active

          oldest

          votes


















          3















          Why is the result of the first SELECT giving me a blank row?




          Because concatenating NULL with any character type (or most other types, array types being a notable exception) results in NULL. Related:



          • How can the concatenatation of a text and a NULL value return a non-null result?

          The representation of NULL depends on your client. Some spell out NULL, some (incl. psql) put nothing instead. Often that's configurable.




          Even casting obj_type::text still gave me a blank row.




          Casting NULL to (almost) any type still returns NULL - of another data type.




          I have a query for producing some text for creating some VALUES text to put in a .sql file for inserting some rows.




          Have you considered COPY or the psql equivalent copy?



          Other solutions



          If your example isn't simplified, you might just select whole ROW values:



          SELECT o -- whole row
          FROM il2.objects o
          WHERE obj_id < 11
          ORDER BY obj_id;


          If you need that specific format, use format() to make it simple. Works with NULL values out of the box:



          SELECT format('(%s, %L),', obj_id, obj_type)
          FROM objects;


          You get NULL (unquoted) in place of NULL values (which is distinct from '' and may have to be distinguishable.)



          db<>fiddle here (added to the existing fiddle of McNets, cudos)






          share|improve this answer



























          • I didn't know about format() - nice. I hadn't considered COPY; in a previous job, the convention was always to do inserts with the VALUES convention, but that's an excellent alternative, too - thanks.

            – Randall
            6 hours ago






          • 1





            Just noticed that you've thought about this before. Worth linking to here. How can the concatenatation of a text and a NULL value return a non-null result?

            – Randall
            3 hours ago












          • @Randall: Oh yes, perfect match. I added it above. And thanks for fixing the links.

            – Erwin Brandstetter
            2 hours ago



















          2














          Use COALESCE function to return the current value or an empty string.



          SELECT ' (' || obj_id || ', ''' || coalesce(obj_type, '') || '''),' 
          FROM objects;




          | ?column? |
          | :-------------- |
          | (1, 'val 1'), |
          | (2, ''), |
          | (3, 'val 3'), |
          | (4, 'val 4'), |



          db<>fiddle here






          share|improve this answer



























            Your Answer








            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "182"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f244345%2fnull-value-causes-blank-row-in-select-results-for-text-concatenation%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3















            Why is the result of the first SELECT giving me a blank row?




            Because concatenating NULL with any character type (or most other types, array types being a notable exception) results in NULL. Related:



            • How can the concatenatation of a text and a NULL value return a non-null result?

            The representation of NULL depends on your client. Some spell out NULL, some (incl. psql) put nothing instead. Often that's configurable.




            Even casting obj_type::text still gave me a blank row.




            Casting NULL to (almost) any type still returns NULL - of another data type.




            I have a query for producing some text for creating some VALUES text to put in a .sql file for inserting some rows.




            Have you considered COPY or the psql equivalent copy?



            Other solutions



            If your example isn't simplified, you might just select whole ROW values:



            SELECT o -- whole row
            FROM il2.objects o
            WHERE obj_id < 11
            ORDER BY obj_id;


            If you need that specific format, use format() to make it simple. Works with NULL values out of the box:



            SELECT format('(%s, %L),', obj_id, obj_type)
            FROM objects;


            You get NULL (unquoted) in place of NULL values (which is distinct from '' and may have to be distinguishable.)



            db<>fiddle here (added to the existing fiddle of McNets, cudos)






            share|improve this answer



























            • I didn't know about format() - nice. I hadn't considered COPY; in a previous job, the convention was always to do inserts with the VALUES convention, but that's an excellent alternative, too - thanks.

              – Randall
              6 hours ago






            • 1





              Just noticed that you've thought about this before. Worth linking to here. How can the concatenatation of a text and a NULL value return a non-null result?

              – Randall
              3 hours ago












            • @Randall: Oh yes, perfect match. I added it above. And thanks for fixing the links.

              – Erwin Brandstetter
              2 hours ago
















            3















            Why is the result of the first SELECT giving me a blank row?




            Because concatenating NULL with any character type (or most other types, array types being a notable exception) results in NULL. Related:



            • How can the concatenatation of a text and a NULL value return a non-null result?

            The representation of NULL depends on your client. Some spell out NULL, some (incl. psql) put nothing instead. Often that's configurable.




            Even casting obj_type::text still gave me a blank row.




            Casting NULL to (almost) any type still returns NULL - of another data type.




            I have a query for producing some text for creating some VALUES text to put in a .sql file for inserting some rows.




            Have you considered COPY or the psql equivalent copy?



            Other solutions



            If your example isn't simplified, you might just select whole ROW values:



            SELECT o -- whole row
            FROM il2.objects o
            WHERE obj_id < 11
            ORDER BY obj_id;


            If you need that specific format, use format() to make it simple. Works with NULL values out of the box:



            SELECT format('(%s, %L),', obj_id, obj_type)
            FROM objects;


            You get NULL (unquoted) in place of NULL values (which is distinct from '' and may have to be distinguishable.)



            db<>fiddle here (added to the existing fiddle of McNets, cudos)






            share|improve this answer



























            • I didn't know about format() - nice. I hadn't considered COPY; in a previous job, the convention was always to do inserts with the VALUES convention, but that's an excellent alternative, too - thanks.

              – Randall
              6 hours ago






            • 1





              Just noticed that you've thought about this before. Worth linking to here. How can the concatenatation of a text and a NULL value return a non-null result?

              – Randall
              3 hours ago












            • @Randall: Oh yes, perfect match. I added it above. And thanks for fixing the links.

              – Erwin Brandstetter
              2 hours ago














            3












            3








            3








            Why is the result of the first SELECT giving me a blank row?




            Because concatenating NULL with any character type (or most other types, array types being a notable exception) results in NULL. Related:



            • How can the concatenatation of a text and a NULL value return a non-null result?

            The representation of NULL depends on your client. Some spell out NULL, some (incl. psql) put nothing instead. Often that's configurable.




            Even casting obj_type::text still gave me a blank row.




            Casting NULL to (almost) any type still returns NULL - of another data type.




            I have a query for producing some text for creating some VALUES text to put in a .sql file for inserting some rows.




            Have you considered COPY or the psql equivalent copy?



            Other solutions



            If your example isn't simplified, you might just select whole ROW values:



            SELECT o -- whole row
            FROM il2.objects o
            WHERE obj_id < 11
            ORDER BY obj_id;


            If you need that specific format, use format() to make it simple. Works with NULL values out of the box:



            SELECT format('(%s, %L),', obj_id, obj_type)
            FROM objects;


            You get NULL (unquoted) in place of NULL values (which is distinct from '' and may have to be distinguishable.)



            db<>fiddle here (added to the existing fiddle of McNets, cudos)






            share|improve this answer
















            Why is the result of the first SELECT giving me a blank row?




            Because concatenating NULL with any character type (or most other types, array types being a notable exception) results in NULL. Related:



            • How can the concatenatation of a text and a NULL value return a non-null result?

            The representation of NULL depends on your client. Some spell out NULL, some (incl. psql) put nothing instead. Often that's configurable.




            Even casting obj_type::text still gave me a blank row.




            Casting NULL to (almost) any type still returns NULL - of another data type.




            I have a query for producing some text for creating some VALUES text to put in a .sql file for inserting some rows.




            Have you considered COPY or the psql equivalent copy?



            Other solutions



            If your example isn't simplified, you might just select whole ROW values:



            SELECT o -- whole row
            FROM il2.objects o
            WHERE obj_id < 11
            ORDER BY obj_id;


            If you need that specific format, use format() to make it simple. Works with NULL values out of the box:



            SELECT format('(%s, %L),', obj_id, obj_type)
            FROM objects;


            You get NULL (unquoted) in place of NULL values (which is distinct from '' and may have to be distinguishable.)



            db<>fiddle here (added to the existing fiddle of McNets, cudos)







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 2 hours ago

























            answered 7 hours ago









            Erwin BrandstetterErwin Brandstetter

            101k9 gold badges210 silver badges335 bronze badges




            101k9 gold badges210 silver badges335 bronze badges















            • I didn't know about format() - nice. I hadn't considered COPY; in a previous job, the convention was always to do inserts with the VALUES convention, but that's an excellent alternative, too - thanks.

              – Randall
              6 hours ago






            • 1





              Just noticed that you've thought about this before. Worth linking to here. How can the concatenatation of a text and a NULL value return a non-null result?

              – Randall
              3 hours ago












            • @Randall: Oh yes, perfect match. I added it above. And thanks for fixing the links.

              – Erwin Brandstetter
              2 hours ago


















            • I didn't know about format() - nice. I hadn't considered COPY; in a previous job, the convention was always to do inserts with the VALUES convention, but that's an excellent alternative, too - thanks.

              – Randall
              6 hours ago






            • 1





              Just noticed that you've thought about this before. Worth linking to here. How can the concatenatation of a text and a NULL value return a non-null result?

              – Randall
              3 hours ago












            • @Randall: Oh yes, perfect match. I added it above. And thanks for fixing the links.

              – Erwin Brandstetter
              2 hours ago

















            I didn't know about format() - nice. I hadn't considered COPY; in a previous job, the convention was always to do inserts with the VALUES convention, but that's an excellent alternative, too - thanks.

            – Randall
            6 hours ago





            I didn't know about format() - nice. I hadn't considered COPY; in a previous job, the convention was always to do inserts with the VALUES convention, but that's an excellent alternative, too - thanks.

            – Randall
            6 hours ago




            1




            1





            Just noticed that you've thought about this before. Worth linking to here. How can the concatenatation of a text and a NULL value return a non-null result?

            – Randall
            3 hours ago






            Just noticed that you've thought about this before. Worth linking to here. How can the concatenatation of a text and a NULL value return a non-null result?

            – Randall
            3 hours ago














            @Randall: Oh yes, perfect match. I added it above. And thanks for fixing the links.

            – Erwin Brandstetter
            2 hours ago






            @Randall: Oh yes, perfect match. I added it above. And thanks for fixing the links.

            – Erwin Brandstetter
            2 hours ago














            2














            Use COALESCE function to return the current value or an empty string.



            SELECT ' (' || obj_id || ', ''' || coalesce(obj_type, '') || '''),' 
            FROM objects;




            | ?column? |
            | :-------------- |
            | (1, 'val 1'), |
            | (2, ''), |
            | (3, 'val 3'), |
            | (4, 'val 4'), |



            db<>fiddle here






            share|improve this answer





























              2














              Use COALESCE function to return the current value or an empty string.



              SELECT ' (' || obj_id || ', ''' || coalesce(obj_type, '') || '''),' 
              FROM objects;




              | ?column? |
              | :-------------- |
              | (1, 'val 1'), |
              | (2, ''), |
              | (3, 'val 3'), |
              | (4, 'val 4'), |



              db<>fiddle here






              share|improve this answer



























                2












                2








                2







                Use COALESCE function to return the current value or an empty string.



                SELECT ' (' || obj_id || ', ''' || coalesce(obj_type, '') || '''),' 
                FROM objects;




                | ?column? |
                | :-------------- |
                | (1, 'val 1'), |
                | (2, ''), |
                | (3, 'val 3'), |
                | (4, 'val 4'), |



                db<>fiddle here






                share|improve this answer













                Use COALESCE function to return the current value or an empty string.



                SELECT ' (' || obj_id || ', ''' || coalesce(obj_type, '') || '''),' 
                FROM objects;




                | ?column? |
                | :-------------- |
                | (1, 'val 1'), |
                | (2, ''), |
                | (3, 'val 3'), |
                | (4, 'val 4'), |



                db<>fiddle here







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 8 hours ago









                McNetsMcNets

                17k5 gold badges25 silver badges60 bronze badges




                17k5 gold badges25 silver badges60 bronze badges






























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Database Administrators Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f244345%2fnull-value-causes-blank-row-in-select-results-for-text-concatenation%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Sahara Skak | Bilen | Luke uk diar | NawigatsjuunCommonskategorii: SaharaWikivoyage raisfeerer: Sahara26° N, 13° O

                    The fall designs the understood secretary. Looking glass Science Shock Discovery Hot Everybody Loves Raymond Smile 곳 서비스 성실하다 Defas Kaloolon Definition: To combine or impregnate with sulphur or any of its compounds as to sulphurize caoutchouc in vulcanizing Flame colored Reason Useful Thin Help 갖다 유명하다 낙엽 장례식 Country Iron Definition: A fencer a gladiator one who exhibits his skill in the use of the sword Definition: The American black throated bunting Spiza Americana Nostalgic Needy Method to my madness 시키다 평가되다 전부 소설가 우아하다 Argument Tin Feeling Representative Gym Music Gaur Chicken 일쑤 코치 편 학생증 The harbor values the sugar. Vasagle Yammoe Enstatite Definition: Capable of being limited Road Neighborly Five Refer Built Kangaroo 비비다 Degree Release Bargain Horse 하루 형님 유교 석 동부 괴롭히다 경제력

                    19. јануар Садржај Догађаји Рођења Смрти Празници и дани сећања Види још Референце Мени за навигацијуу