Determine number of rows returns from SQLite.swift raw query

59 Views Asked by At

I am using the SQLite.swift library and running raw queries.

I have the following

let results = try db!.prepare("""
    SELECT class from "character" where character_id = ?
""", character.id
)

Does anyone know how to get the number of rows returned? (or more specifically whether it returns any rows).

I know I can loop through results, but was looking for a more efficient way.

2

There are 2 best solutions below

4
nbk On

You can add a subquery with the count to your query

CREATE TABLE "character"(character_id int, class varchar(120))

SELECT class, (SELECT COUNT(*) FROM  "character" where character_id = 1) count_ 
  from "character" where character_id = 1
class count_
SELECT class, _count
  from "character" CROSS JOIN (SELECT COUNT(*) _count FROM  "character" where character_id = 1) count_
  where character_id = 1
class _count

fiddle

0
HangarRash On

If you have no need to process each matching class and you only want the number of matching classes, then change the query to:

SELECT COUNT(class) from "character" where character_id = ?

This will give you one result row with one column containing the number of matching classes.

If you do need to process each class and you want the count, then use your existing query as-is and calculate the count as you process each result row.