Swift: Using filters

Filters allow you to only return rows that match certain conditions.

Filters can be used on select(), update(), upsert(), and delete() queries.

If a Postgres function returns a table response, you can also apply filters.

Implement URLQueryRepresentable protocol in your own types to be able to use them as filter value.

Supported filtes are: eq, neq, gt, gte, lt, lte, like, ilike, is, in, cs, cd, sl, sr, nxl, nxr, adj, ov, fts, plfts, phfts, wfts. Check available operators in PostgREST.

Examples

Applying Filters

try await supabase.database
  .from("cities")
  .select("name, country_id")
  .eq("name", value: "The Shire")    // Correct

try await supabase.database
  .from("citites")
  .eq("name", value: "The Shire")    // Incorrect
  .select("name, country_id")

Chaining

try await supabase.database
  .from("cities")
  .select("name, country_id")
  .gte("population", value: 1000)
  .lt("population", value: 10000)

Conditional Chaining

let filterByName: String? = nil
let filterPopLow: Int? = 1000
let filterPopHigh: Int? = 10000

var query = await supabase.database
  .from("cities")
  .select("name, country_id")

if let filterByName \{
  query = query.eq("name", value: filterByName)
\}
if let filterPopLow \{
  query = query.gte("population", value: filterPopLow)
\}
if let filterPopHigh \{
  query = query.lt("population", value: filterPopHigh)
\}

struct Response: Decodable \{
  // expected fields
\}
let result: Response = try await query.execute().value

Filter by values within a JSON column

try await supabase.database
  .from("users")
  .select()
  .eq("address->postcode", value: 90210)

Filter Foreign Tables

try await supabase.database
  .from("countries")
  .select(
    """
      name,
      cities!inner (
        name
      )
    """
  )
  .eq("cities.name", value: "Bali")