328

Is it possible to do a select statement that takes only NOT NULL values?

Right now I am using this:

SELECT * FROM table

And then I have to filter out the null values with a php loop.

Is there a way to do:

SELECT * (that are NOT NULL) FROM table

?

Right now when I select * I get val1,val2,val3,null,val4,val5,null,null etc.... but I just want to get the values that are not null in my result. Is this possible without filtering with a loop?

ROMANIA_engineer's user avatar
ROMANIA_engineer
57k30 gold badges211 silver badges207 bronze badges
askedMar 12, 2011 at 20:58
bryan sammon's user avatar
9
  • 2
    What do you want to happen if there is a row where some columns have NULL values and other columns have not NULL values?CommentedMar 12, 2011 at 21:05
  • I would like to only get the values from the columns that are not null, and return only the column values in the row that are not null. Right now I use a loop to filter them out, is it possible to do that without a loop?CommentedMar 12, 2011 at 21:08
  • 1
    @bryan - What is your table structure? Do all columns have the same datatype?CommentedMar 12, 2011 at 21:10
  • 1
    @bryan - So what would your ideal result set look like then? A one column result set containing all the non null values? If not editing your question with example data and desired results would be helpful...CommentedMar 12, 2011 at 21:15
  • 2
    @bryan - It sounds like your table may well have repeating groups across columns? (See the Wiki article for an explanation and a suggested alternative structure if that is the caseen.wikipedia.org/wiki/First_normal_form)CommentedMar 12, 2011 at 21:30

12 Answers12

539

You should useIS NOT NULL. (The comparison operators= and<> both giveUNKNOWN withNULL on either side of the expression.)

SELECT * FROM table WHERE YourColumn IS NOT NULL;

Just for completeness I'll mention that in MySQL you can also negate thenull safe equality operator but this is not standard SQL.

SELECT *FROM table WHERE NOT (YourColumn <=> NULL);

Edited to reflect comments. It sounds like your table may not be in first normal form in which case changing the structure may make your task easier. A couple of other ways of doing it though...

SELECT val1 AS valFROM  your_tableWHERE val1 IS NOT NULLUNION ALLSELECT val2 FROM  your_tableWHERE val2 IS NOT NULL/*And so on for all your columns*/

The disadvantage of the above is that it scans the table multiple times once for each column. That may possibly be avoided by the below but I haven't tested this in MySQL.

SELECT CASE idx         WHEN 1 THEN val1         WHEN 2 THEN val2       END AS valFROM   your_table        /*CROSS JOIN*/       JOIN (SELECT 1 AS idx                   UNION ALL                   SELECT 2) tHAVING val IS NOT NULL  /*Can reference alias in Having in MySQL*/
answeredMar 12, 2011 at 21:01
Martin Smith's user avatar
Sign up to request clarification or add additional context in comments.

7 Comments

In the last approach, you usedCASE statement, notCASE function. So shouldn't it beEND CASE instead ofEND in theSELECT CASE ... part ?
For not-so-expert people, can you explain the last solution ? Does theidx rom the firstSELECT come from theidx in the secondSELECT ? What does theCASE statement try to accomplish ? What does the secondSELECT actually do ? And you are doing an inner join, not a cross join, right ?
I don't think this answers the question. It sounded like OP wanted to select (I assume one specific) row but exclude all columns from that result that were null - this answer requires you to either specify which columns aren't allowed to be null (which is a different problem entirely) or specify all columns, unsuitable for tables with many columns
(e.g. something along the lines ofSELECT * FROM table WHERE * IS NOT NULL AND primary_key="somevalue")
@csey - The question asker accepted this so presumably it answered it sufficiently as far as they are concerned. Feel free to add your own answer or ask a new question
|
25

You can filter out rows that contain a NULL value in a specific column:

SELECT col1, col2, ..., colnFROM yourtableWHERE somecolumn IS NOT NULL

If you want to filter out rows that contain a null in any column then try this:

SELECT col1, col2, ..., colnFROM yourtableWHERE col1 IS NOT NULLAND col2 IS NOT NULL-- ...AND coln IS NOT NULL

Update: Based on your comments, perhaps you want this?

SELECT * FROM(    SELECT col1 AS col FROM yourtable    UNION    SELECT col2 AS col FROM yourtable    UNION    -- ...    UNION    SELECT coln AS col FROM yourtable) T1WHERE col IS NOT NULL

And I agre with Martin that if you need to do this then you should probably change your database design.

answeredMar 12, 2011 at 21:01
Mark Byers's user avatar

3 Comments

Im not sure if I explained it well enough, but im gonna try a little better. Right now when I select * I get val1,val2,val3,null,val4,val5,null,null etc.... but I just want to get the values that are not null in my result. Is this possible without filtering with a loop?
@bryan - Could you explain what columns* returns? Maybe provide a bit of example data in your question as it is not clear from your comment above whether this is all one column.
Right now, * returns all of my values in the row. i.e. val1,val2,val3,null,val4,val5,null,null. But I want it to only return the column values that are not null. Right now I do it with a loop to filter out the values after it returns the result.
15
Select * from your_table WHERE col1 and col2 and col3 and col4 and col5 IS NOT NULL;

The only disadvantage of this approach is that you can only compare 5 columns, after that the result will always be false, so I do compare only the fields that can beNULL.

Aniket Kulkarni's user avatar
Aniket Kulkarni
13k10 gold badges70 silver badges94 bronze badges
answeredJan 20, 2012 at 19:57
Alan Chavez's user avatar

Comments

8

I found this solution:

This query select last not null value for each column.

Example


If you have a table:

id|title|body1 |t1   |b12 |NULL |b23 |t3   |NULL

you get:

title|bodyt3   |b2

Query


SELECT DISTINCT (  SELECT title  FROM test  WHERE title IS NOT NULL   ORDER BY id DESC   LIMIT 1) title, (  SELECT body  FROM test  WHERE body IS NOT NULL   ORDER BY id DESC   LIMIT 1) bodyFROM test

I hope help you.

answeredFeb 3, 2012 at 12:22
porquero's user avatar

1 Comment

GROUP_CONCAT(body) AS body
6

Following query working for me

when i have set default value of column 'NULL' then

select * from table where column IS NOT NULL

and when i have set default value nothing then

select * from table where column <>''
answeredAug 5, 2018 at 20:11
Basant's user avatar

Comments

3

Yes useNOT NULL in your query like this below.

SELECT * FROM tableWHERE col IS NOT NULL;
Sᴀᴍ Onᴇᴌᴀ's user avatar
Sᴀᴍ Onᴇᴌᴀ
8,3028 gold badges38 silver badges61 bronze badges
answeredJun 30, 2017 at 0:00
Jonathan Vasiliou's user avatar

Comments

2

I use the\! command within MySQL to grep out NULL values from the shell:

\! mysql -e "SELECT * FROM table WHERE column = 123456\G" | grep -v NULL

It works best with a proper.my.cnf where your database/username/password are specified. That way you just have to surround yourselect with\! mysql e and| grep -v NULL.

answeredJan 18, 2013 at 18:40
soulshake's user avatar

Comments

0

You didn't even have to use an asterisk to get the table fields.

answeredOct 18, 2023 at 14:42
Ricardo Erick Rebêlo's user avatar

Comments

0

Add condition >0 for int columns and != "" for varchar columns

select column1_id, column2, colummn3, where column1_id>0 and column2 != ""
answeredFeb 14, 2024 at 9:53
Abdul Samad Nizamani's user avatar

Comments

-3
SELECT duration,id FROM `tickets` WHERE duration !=""
Syscall's user avatar
Syscall
19.8k10 gold badges44 silver badges60 bronze badges
answeredMar 28, 2021 at 12:17
Heba abd El monaem's user avatar

Comments

-3

WHERE COALESCE(ALL YOUR COLUMNS) IS NOT NULL

answeredSep 9, 2022 at 13:56
rus's user avatar

2 Comments

Your answer could be improved with additional supporting information. Pleaseedit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answersin the help center.
Please add an explanation of your code along with a practical, syntactically correct example of a query using it. Examples help readers to more easily see how it can be applied to their situation, and descriptions let readers knowif and/orwhy the answer solves the problem.
-7
SELECT * FROM TABLE_NAMEwhere COLUMN_NAME <> '';
Pang's user avatar
Pang
10.2k146 gold badges87 silver badges126 bronze badges
answeredMar 31, 2016 at 16:20
Venkat Kallem's user avatar

2 Comments

This is not select which are empty. question is for selecting not null values
' ' and null is different
Protected question. To answer this question, you need to have at least 10 reputation on this site (not counting theassociation bonus). The reputation requirement helps protect this question from spam and non-answer activity.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.