Question

I'v a SQLite database and I want to generate a kind of validation check. The main target is to compare three fields in a table. If stnd_sht has the value 'nicht gegeben' then there should be a entry either in mass_sof of in mass_6m, if not then plausibility is not given.

So far I tried the following:

SELECT 
b.baum_id AS baum_id,

CASE 
WHEN b.stnd_sht ='nicht gegeben' AND b.mass_sof IS NULL  THEN 'fehler'
WHEN b.stnd_sht ='nicht gegeben' AND b.mass_6m IS NULL THEN 'fehler'
ELSE 'plausibel' END AS plaus

FROM baeume b;

and...

SELECT 
b.baum_id AS baum_id,

CASE WHEN (b.mass_sof IS NULL OR b.mass_6m IS NULL) AND b.stnd_sht ='nicht gegeben' THEN 'fehler'
ELSE 'plausibel' END AS plaus

FROM baeume b;

Everything works fine without any AND or OR operator but as I add additional expressions the result is not correct. Is the AND operator not supportet by the CASE statement, or am I totaly wrong and the statement needs another structure or has to be more complex? Thanks in advance, Patrick

Was it helpful?

Solution

These expressions are syntactically correct, but do not correspond to the explanation.

Sometimes, it helps to reverse a logical condition. According to the explanation, there is an error if stnd_sht is nicht gegeben and if both the mass_sof and mass_6m values are NULL.

This would correspond to the following expression:

SELECT baum_id,
       CASE WHEN stnd_sht = 'nicht gegeben' AND
                 mass_sof IS NULL           AND
                 mass_6m IS NULL
            THEN 'fehler'
            ELSE 'plausibel'
       END AS plaus
FROM baeume;

This could be simplified a little:

SELECT baum_id,
       CASE WHEN stnd_sht = 'nicht gegeben'          AND
                 COALESCE(mass_sof, mass_6m) IS NULL
            THEN 'fehler'
            ELSE 'plausibel'
       END AS plaus
FROM baeume;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top