LAG
WindowAccesses data from a previous row in the result set without a self-join.
Syntax
LAG(col, offset, default) OVER (ORDER BY col)
Example
SELECT date, revenue, LAG(revenue, 1) OVER (ORDER BY date) as prev_revenue, revenue - LAG(revenue, 1) OVER (ORDER BY date) as growth FROM daily_sales;
About SQL LAG
The LAG keyword belongs to the Window category of SQL statements. Accesses data from a previous row in the result set without a self-join. Understanding this command is essential for any developer working with relational databases like PostgreSQL, MySQL, SQLite, or SQL Server.
SQL (Structured Query Language) is the standard language for managing and querying relational databases. The LAG statement is supported across all major database systems, though specific syntax may vary slightly between PostgreSQL, MySQL, MariaDB, Oracle, SQL Server, and SQLite. Always consult your database's documentation for vendor-specific features and limitations.
Best practices for using LAG: always test queries on a development database before running them in production, use parameterized queries to prevent SQL injection, and leverage EXPLAIN to understand query performance. For complex queries, consider using CTEs (Common Table Expressions) to improve readability and maintainability.