Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQLite/SQLAlchemy: Check values are either NULL or the same for several columns

I would like to check for several columns that: For each column the value is either NULL or the same for all records.

For example, the condition holds for the following table

+------+------+------+------+
| Col1 | Col2 | Col3 | Col4 |
+------+------+------+------+
| A    | B    | NULL | NULL |
| NULL | B    | C    | NULL |
| A    | B    | C    | NULL |
+------+------+------+------+

How can I do that, preferably with one query?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT:
An alternative question would be: How can I sum the distinct values of each of the selected columns

>Solution :

You can check if the distinct number of values in each individual column is less than or equal to 1:

SELECT COUNT(DISTINCT Col1) <= 1 ok1,
       COUNT(DISTINCT Col2) <= 1 ok2,
       COUNT(DISTINCT Col3) <= 1 ok3,
       COUNT(DISTINCT Col4) <= 1 ok4
FROM tablename; 

Or, you can get a result for the the whole table:

SELECT MAX(
         COUNT(DISTINCT Col1),
         COUNT(DISTINCT Col2),
         COUNT(DISTINCT Col3),
         COUNT(DISTINCT Col4)
       ) <= 1 ok  
FROM tablename;

See the demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading