Search code examples
sqlsqlitepdohaving

Trouble with SQLite SQL Query


I'm trying to run the following query in SQLite 3:

SELECT *,
  DISTANCE(latitude, longitude, ?, ?) AS "distance"
FROM "country"
WHERE "id" NOT LIKE ?
HAVING "distance" <= ?
ORDER BY "distance" ASC;

But I get the following error:

SQLSTATE[HY000]: General error: 1 a GROUP BY clause is required before HAVING

I don't understand why SQLite wants me to group results, but still I tried the following:

SELECT *,
  DISTANCE(latitude, longitude, ?, ?) AS "distance"
FROM "country"
WHERE "id" NOT LIKE ?
GROUP BY "id"
HAVING "distance" <= ?
ORDER BY "distance" ASC;

And I also tried this:

SELECT *,
  DISTANCE(latitude, longitude, ?, ?) AS "distance"
FROM "country"
WHERE "id" NOT LIKE ?
GROUP BY "distance"
HAVING "distance" <= ?
ORDER BY "distance" ASC;

No errors, but all records were returned (even those having "distance" > ?). I also tried doing:

SELECT *,
  DISTANCE(latitude, longitude, ?, ?) AS "distance"
FROM "country"
WHERE "id" NOT LIKE ?
  AND "distance" <= ?
ORDER BY "distance" ASC;

Same output, all records were returned. I've double checked - the distance is being correctly calculated... I've no idea what's wrong with this query, can someone help me out?


Solution

  • You can't specify a HAVING clause without having specified a GROUP BY clause. Use:

      SELECT *, 
             DISTANCE(latitude, longitude, ?, ?) AS dist
        FROM COUNTRY c
       WHERE c.id NOT LIKE ?
         AND DISTANCE(c.latitude, c.longitude, ?, ?) <= ?
    ORDER BY dist;
    

    If you don't want to call DISTANCE more than once, you can use a subquery:

      SELECT x.*
        FROM (SELECT c.*, 
                     DISTANCE(latitude, longitude, ?, ?) AS dist
                FROM COUNTRY c
               WHERE c.id NOT LIKE ?) x
       WHERE x.dist <= ? 
    ORDER BY dist;