0
0
Supabasecloud~5 mins

Filtering and sorting queries in Supabase

Choose your learning style9 modes available
Introduction

Filtering and sorting help you find and organize data easily. They let you get only what you need in the order you want.

You want to see only users from a specific city in your app.
You need to list products by price from low to high.
You want to find all orders made after a certain date.
You want to show the newest blog posts first.
You want to filter tasks by status and sort by deadline.
Syntax
Supabase
const { data, error } = await supabase
  .from('table_name')
  .select('*')
  .eq('column_name', 'value')
  .order('column_name', { ascending: true })

Use .eq() or other filter methods to pick rows matching a condition.

Use .order() to sort results by a column.

Examples
Gets all users where city equals 'Paris'.
Supabase
const { data, error } = await supabase
  .from('users')
  .select('*')
  .eq('city', 'Paris')
Gets all products sorted by price from high to low.
Supabase
const { data, error } = await supabase
  .from('products')
  .select('*')
  .order('price', { ascending: false })
Gets orders made after Jan 1, 2024, sorted from oldest to newest.
Supabase
const { data, error } = await supabase
  .from('orders')
  .select('*')
  .gt('created_at', '2024-01-01')
  .order('created_at', { ascending: true })
Sample Program

This code gets users from the USA and sorts them by their last login time, newest first. It prints the list or an error if something goes wrong.

Supabase
import { createClient } from '@supabase/supabase-js'

const supabaseUrl = 'https://xyzcompany.supabase.co'
const supabaseKey = 'public-anonymous-key'
const supabase = createClient(supabaseUrl, supabaseKey)

async function getFilteredSortedUsers() {
  const { data, error } = await supabase
    .from('users')
    .select('*')
    .eq('country', 'USA')
    .order('last_login', { ascending: false })

  if (error) {
    console.error('Error:', error.message)
    return
  }

  console.log('Filtered and sorted users:', data)
}

getFilteredSortedUsers()
OutputSuccess
Important Notes

Use operators like eq (equals), gt (greater than), lt (less than) for filtering.

Sorting defaults to ascending order; set ascending: false for descending.

Always check for errors after queries to handle problems gracefully.

Summary

Filtering lets you pick only the data you want.

Sorting arranges data in the order you need.

Supabase makes filtering and sorting easy with simple methods.