Ask Your Question
2

How can I merge rows in TSQL to eliminate null values?

asked 2022-03-10 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-09-23 06:00:00 +0000

ladyg gravatar image

You can use the COALESCE function to merge rows and eliminate null values in TSQL.

Here is an example:

Suppose you have a table called "Customers" with the following data:

| CustomerID | FirstName | LastName | Email | |------------|-----------|----------|---------------| | 1 | John | Smith | john@example.com | | 2 | Jane | Doe | NULL | | 3 | Bob | Jones | bob@example.com |

To merge rows and eliminate null values in the Email column, you can use the COALESCE function like this:

SELECT CustomerID, FirstName, LastName, COALESCE(Email, '') AS Email
FROM Customers

This will return the following result:

| CustomerID | FirstName | LastName | Email | |------------|-----------|----------|---------------| | 1 | John | Smith | john@example.com | | 2 | Jane | Doe | | | 3 | Bob | Jones | bob@example.com |

The COALESCE function replaces null values with an empty string (''). Therefore, the Email column in the second row is now an empty string instead of null.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-03-10 11:00:00 +0000

Seen: 7 times

Last updated: Sep 23 '21