0

Good day

I have a table with a dozen columns and i'm looking for a query that will return rows that only have specific columns filled up. So it shouldn't return rows where 'illegal' columns are filled up.

Something like:

SELECT * FROM table WHERE col1 is NOT NULL 
AND all_other_cols is NULL;

^ i know it can be done by listing every other column and indicating "not NULL", but is there another way of doing this?

Hopefully this makes sense

UPDATE:

Based on the answers below I'll just use "DESCRIBE my_table;" then build a query that will filter all unwanted columns with 'is NULL'

1
  • Checking all columns is the cleanest approach and might be the best in terms of optimization. If you want something simpler, have a look at COALESCE. Commented Jun 16, 2017 at 18:27

3 Answers 3

2

There is no direct feature for that. But what you can do is this:

You concatenate all table columns to a single string and then test that string against the column that is not meant to be NULL. These two values can only be identical if all other columns are empty or hold NULL.

The answer to this question might help with how to even simplify that:

MySQL concatenating all columns

Sign up to request clarification or add additional context in comments.

3 Comments

thank you i thought of that as well, so there's something like CONCAT_WS but for column names?
Take a look at the question I referenced.
I think i'll just end up using DESCRIBE my_table; then build a query with 'unwanted col is NULL', seems to be the simplest, thanks for confirming that there's no direct feature for this
1

I think your approach is the simplest one

1 Comment

This is not an answer to the question. This should have been a comment.
1

You could use ISNULL condition : check out here

2 Comments

The OP wrote that he knows about that, but that it is not what he is looking for...
True, but the link I gave is about optimizing isnull if he decides to use it. I should have written my answer in another way

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.