Just a brief break from Swift programming — I stumbled across an interesting SQL shortcut the other day.
I was exploring a SQL table, trying to understand what kind of data was contained therein. I was doing things of the form:
select count(*) from thetable where description like ‘%thing%';
(I’m using PostgreSQL here, but I’m pretty sure this would work anywhere). And this was then often followed by
select count(*) from thetable where description not like ‘%thing%';
Which would have been OK, except that I remembered that
select count(*) from thetable;
Where were the missing rows? Oh, right! Nulls are special — they are neither equal nor not-equal to regular values. So that meant:
select count(*) from thetable where description is null;
I was constantly running the same comparison repeatedly to get the equal / not-equal / null breakdowns for various columns. And then I realized that:
select description like ‘%thing%’ as f, count(*) from thetable group by f;
f | count
∅ | 4
t | 16
f | 60
I could create the comparison as a field, then group by that field. There would be three possible values (true, false, and null) — so one pass would give me my counts.
I also prefer the way it reads. The thing I’m counting is at the beginning of the phrase, not the end — where it feels more natural. And this way, I don’t forget to check for the null case (which I often forget) — I get it for free.