Fix PostgreSQL Error 22016: Invalid Argument for Nth Value Function
In this article
PostgreSQL error code 22016—*"invalid argument for nth_value function"*—means you're passing an incompatible type, incorrect parameter, or unsupported value to the `nth_value` function. This function extracts a value from an ordered set of values (or rows) by position, but its parameters must match PostgreSQL's exact requirements. Here's how to diagnose and fix it properly.
What You'll Need
- A working PostgreSQL client (psql, Application Client, or IDE like DBeaver/PgAdmin)
- Access to your PostgreSQL database (user with SELECT permissions)
- A basic understanding of SQL queries (though troubleshooting focuses on syntax)
- Optional: PostgreSQL function documentation (link in troubleshooting section)
Step-by-Step Resolution
- Check your current query syntax using the simplest possible example first. The error often occurs when mixing query types or unsupported parameters. Try this minimal valid version:
SELECT nth_value('apple', ARRAY[1, 2, 3]) AS result;This should return "apple" without errors. If it does, your issue is in the full query. - Verify array/column data types match expectations. The nth_value function requires:
- An array parameter (e.g., `ARRAY[1,2,3]`) or sequence of values from a column
- The nth_value function must return a value compatible with your SELECT column type
- If using a column, ensure it's ordered with DEFAULT ORDER BY clause
- For array parameters, values must be of the same type (e.g., no mixing strings and numbers)
SELECT nth_value('fruit', ARRAY[1, 'orange', 5]);This fails because mixed types aren't supported directly. - Handle NULL values properly. The nth_value function treats NULL values as invalid:
- When selecting from columns, ensure DEFAULT ORDER BY excludes NULLs or handles them with COALESCE
- For array parameters, filter out NULL values if present
SELECT nth_value(COALESCE(column_name, 'default'), ARRAY[1,2,3])
- Check for unsupported parameters. The function has strict parameter limits:
- Only accepts one positional parameter (nth_value(3, array))
- Doesn't support window functions or complex expressions directly
- Must return a scalar value
-- Wrong: Using multiple arguments incorrectly SELECT nth_value('x', ARRAY[1,2], 3); -- Wrong: Trying to use window functions SELECT nth_value(ROW_NUMBER() OVER(), ARRAY[1,2,3]); - Validate your query structure. Common structural causes include:
- Missing parentheses around array parameters
- Using aggregate functions improperly (e.g., nth_value(AVG(column)))
- Trying to use nth_value in a subquery that returns multiple rows without window functions
SELECT nth_value(ORDER BY some_column, ARRAY[1,2,3]) AS third_value;
vs failing:SELECT nth_value(SOME_TABLE.some_column, ARRAY[1,2,3]);
- Test with minimal reproduction case. Create a fresh table with simple data:
CREATE TABLE test_data AS SELECT generate_series(1,10) AS num; SELECT nth_value(num, ARRAY[1,2,3,4,5]);
If this works but your real query fails, the issue is in your data or query context.
Common Mistakes
- Mixing array literals with column references. The function expects either: - An array literal (ARRAY[1,2,3]) or - A column reference with ORDER BY clause Never do both simultaneously.
- Assuming window functions are equivalent. `nth_value` requires explicit array parameters, while window functions like `ROW_NUMBER()` provide ordering automatically. These give different results:
- With nth_value:
SELECT nth_value(ORDER BY salary DESC, ARRAY[1,2,3])
- With window function:
SELECT salary FROM employees ORDER BY salary DESC LIMIT 3;
- Ignoring type compatibility. The return value must match the column type exactly. If you're returning an integer but storing as VARCHAR, you'll need CASCADE SERIALIZATION.
- Using positional parameters incorrectly. The syntax MUST be `nth_value(position, array)`. Any additional parameters trigger the error.
Tips
- Use PostgreSQL's `show max_stack_depth` to ensure your query isn't hitting recursion limits while processing arrays.
- For large datasets, consider pre-filtering rows with ORDER BY before applying nth_value to improve performance.
- When debugging, add `EXPLAIN` to see how your query processes the array:
- For complex scenarios, break down your query into smaller steps that you can test individually.
- Use the PostgreSQL documentation's [nth_value function page](https://www.postgresql.org/docs/current/functions-array.html#FUNCTIONS-ARRAY-NTH_VALUE) as reference for parameter limits and examples.
EXPLAIN SELECT nth_value(column, ARRAY[1,2,3]);Look for "Array Access" operations.
Troubleshooting
- If the query still fails with error 22016 after these steps:
- Check the exact error message for additional context about what went wrong
- Try recasting your array parameter to ensure consistent types:
SELECT nth_value(CAST(column AS TEXT), CAST(ARRAY[1,2,3] AS TEXT[]));
- Run `SELECT * FROM pg_type` to verify array types in your database
- When testing with generated data:
- Create a temporary table with explicit data types:
CREATE TEMP TABLE test AS SELECT generate_series(1,10)::integer AS num;
- Verify the table schema with `SELECT column_type FROM information_schema.columns WHERE table_name='test';`
- Create a temporary table with explicit data types:
- Check your application's string/number conversion functions for silent type mismatches
- Ensure no ORM or query builder is altering your nth_value calls
- Add explicit casting in your code to prevent implicit conversions that might cause type issues
- Use `unnest` or `jsonb_array_elements` if working with JSON arrays instead of direct array parameters
- Verify your JSON type with `SELECT jsonb_typeof(your_column);`
Frequently Asked Questions
Why does nth_value work in some queries but not others?
The function behaves differently based on whether you're working with array literals or column references. Array literals have strict type requirements while column references depend on your query's ORDER BY clause, which might include NULLs or have different ordering behavior than you expect.Can I use nth_value with subqueries?
Yes, but only if you're using an array literal parameter:SELECT nth_value(ARRAY[1,2,3], (SELECT some_column FROM table ORDER BY sort_column));Subqueries with window functions won't work with nth_value unless you convert them to arrays first.
What should I do if I need the nth element from a result set but don't want to use window functions?
For simple cases with known position:SELECT column_name FROM table ORDER BY some_column LIMIT 3 OFFSET 0;For more complex scenarios, consider using a CTE with window functions instead of trying to work around the nth_value limitations.
Is there a way to get the 5th element from an array when the array might be missing values?
No, nth_value doesn't handle missing values in arrays. You would need to pre-filter or use a different approach like:SELECT nth_value(ARRAY[1,2,3,4,5,NULL], ARRAY[1,2]) AS fifth_value FROM (VALUES ('x')) AS t;
with careful position handling.