FIRST_VALUE() in SQL
Returns the first value in an ordered partition of a result set.
Syntax
Return type
FIRST_VALUE() Function Example
What is FIRST_VALUE() in SQL?
The FIRST_VALUE()
function in SQL returns the first value within an ordered partition of a result set. It is commonly used for retrieving the earliest record, identifying baseline values, and ranking datasets.
This function is supported in SQL Server, PostgreSQL, MySQL 8.0+, and Oracle as part of window functions.
This function is widely used in financial analysis, trend identification, and historical comparisons.
Parameters:
expression: Column or expression to retrieve
frame_clause (optional): Defines window frame boundaries
Example Use Cases:
-- Compare to best performing product
-- Track deviation from opening price
-- Initial score in competition
Notes:
Behavior: Returns NULL if partition is empty
Performance Considerations: Window function optimization may be needed
Version Info: Core window function available in most modern DBMS
Deprecated/Recommended Alternatives: None, standard functionality
Error Handling:
Error: Syntax error if ORDER BY is omitted
Recommendation: Always specify ORDER BY and consider frame clause
Supported Databases:
DBMS
Function / Syntax
Example
Behavior with NULL
MySQL
FIRST_VALUE()
FIRST_VALUE(col) OVER (ORDER BY date)
Returns NULL
PostgreSQL
FIRST_VALUE()
FIRST_VALUE(col) OVER (ORDER BY date)
Returns NULL
SQL Server
FIRST_VALUE()
FIRST_VALUE(col) OVER (ORDER BY date)
Returns NULL
SQLite
FIRST_VALUE()
FIRST_VALUE(col) OVER (ORDER BY date)
Returns NULL
BigQuery
FIRST_VALUE()
FIRST_VALUE(col) OVER (ORDER BY date)
Returns NULL
Snowflake
FIRST_VALUE()
FIRST_VALUE(col) OVER (ORDER BY date)
Returns NULL
Athena
FIRST_VALUE()
FIRST_VALUE(col) OVER (ORDER BY date)
Returns NULL
Related Functions:
LAST_VALUE()
Returns the last value in an ordered partition of a result set.
LAG()
Accesses data from a previous row in the result set within a specified window partition.
LEAD()
Accesses data from a subsequent row in the result set within a specified window partition.
ROW_NUMBER()
Assigns a unique sequential integer to rows within a result set partition.