It seems that you just found a bug in sqlite ! ==== create table T1(id integer primary key, val text); insert into T1(val) values('1one'), ('1two'), ('1three'); create table T2(id integer primary key, val text); insert into T2(val) values('2one'), ('2two'), ('2three'), ('2four'); select id, t2_cnt.cnt, max_t1.cnt from T2, (select count(*) as cnt from T2) t2_cnt, (select count(*) as cnt from T1) max_t1 order by id limit case when t2_cnt.cnt > max_t1.cnt then t2_cnt.cnt - max_t1.cnt else 0 end; ==== Ouput: ==== sqlite3 < "test.sql" Error: near line 7: no such column: t2_cnt.cnt ==== Removing the "limit": ==== create table T1(id integer primary key, val text); insert into T1(val) values('1one'), ('1two'), ('1three'); create table T2(id integer primary key, val text); insert into T2(val) values('2one'), ('2two'), ('2three'), ('2four'); select id, t2_cnt.cnt, max_t1.cnt from T2, (select count(*) as cnt from T2) t2_cnt, (select count(*) as cnt from T1) max_t1 order by id; ==== Ouput: ==== sqlite3 < "test.sql" 1|4|3 2|4|3 3|4|3 4|4|3 ====