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

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

Applying for mortgage when living together but only one will be on the mortgage

How to structure presentation to avoid getting questions that will be answered later in the presentation?

Why are prop blades not shaped like household fan blades?

What is a Mono Word™?

What does 「ちんちんかいかい」 mean?

Best practice for keeping temperature constant during film development at home

Help me, I hate squares!

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

Why does the Rust compiler not optimize code assuming that two mutable references cannot alias?

What is the term for completing a route uncleanly?

A conjectural trigonometric identity

Move arrows along a contour

Why is Searing Smite not listed in the Roll20 Spell books?

Create two random teams from a list of players

Scam? Checks via Email

May a hotel provide accommodation for fewer people than booked?

How to prevent a single-element caster from being useless against immune foes?

Reducing the time for rolling hash

What would the United Kingdom's "optimal" Brexit deal look like?

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

How do discovery writers hibernate?

Can you remove a blindfold using the Telekinesis spell?

Introduction to the Sicilian



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

                    Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                    Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                    Ласкавець круглолистий Зміст Опис | Поширення | Галерея | Примітки | Посилання | Навігаційне меню58171138361-22960890446Bupleurum rotundifoliumEuro+Med PlantbasePlants of the World Online — Kew ScienceGermplasm Resources Information Network (GRIN)Ласкавецькн. VI : Літери Ком — Левиправивши або дописавши її