Skip to content

Instantly share code, notes, and snippets.

@a-c-m
Last active January 29, 2025 18:50
Show Gist options
  • Save a-c-m/2a5078e9aca0b98135e67c0d1336ad3f to your computer and use it in GitHub Desktop.
Save a-c-m/2a5078e9aca0b98135e67c0d1336ad3f to your computer and use it in GitHub Desktop.
PG function to autocomplete fields
CREATE OR REPLACE FUNCTION dynamic_autocomplete(
table_name TEXT,
field_name TEXT,
search_input TEXT
) RETURNS TABLE(count INT, value TEXT)
LANGUAGE plpgsql AS
$$
DECLARE
query TEXT;
BEGIN
-- Construct the dynamic SQL query
query := format(
'SELECT COUNT(*)::INT, MIN(%I)::TEXT AS value
FROM %I
WHERE LOWER(%I) LIKE LOWER(''%%%s%%'')
GROUP BY LOWER(%I)
ORDER BY COUNT(*) DESC;',
field_name, table_name, field_name, search_input, field_name
);
-- Execute the query and return results
RETURN QUERY EXECUTE query;
END;
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment