0% found this document useful (0 votes)
29 views15 pages

Essential SQL Functions Guide

This is sql cheatsheet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views15 pages

Essential SQL Functions Guide

This is sql cheatsheet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SQL Functions Cheatsheet - Complete Reference

Guide
A comprehensive quick-reference guide covering all essential SQL functions from basic to
advanced, organized by category for easy lookup and problem-solving.

Table of Contents
1. Aggregate Functions
2. String/Text Functions
3. Date and Time Functions
4. Mathematical Functions
5. Window Functions
6. Conditional Functions
7. NULL Handling Functions
8. Conversion Functions
9. Analytical Functions
10. System Functions
11. Quick Problem-Solving Guide

Aggregate Functions

Basic Aggregates

-- COUNT: Count rows/values


COUNT(*) -- Count all rows
COUNT(column) -- Count non-NULL values
COUNT(DISTINCT column) -- Count unique non-NULL values

-- SUM: Sum numeric values


SUM(column) -- Sum all non-NULL values
SUM(DISTINCT column) -- Sum unique values

-- AVG: Average values


AVG(column) -- Average of non-NULL values
AVG(DISTINCT column) -- Average of unique values

-- MIN/MAX: Minimum and Maximum


MIN(column) -- Smallest value
MAX(column) -- Largest value

-- Examples
SELECT
COUNT(*) as total_rows,
COUNT(salary) as salary_count,
SUM(salary) as total_salary,
AVG(salary) as avg_salary,
MIN(salary) as min_salary,
MAX(salary) as max_salary
FROM employees;

Statistical Aggregates

-- STDDEV: Standard deviation


STDDEV(column) -- Sample standard deviation
STDDEV_POP(column) -- Population standard deviation

-- VARIANCE: Variance
VARIANCE(column) -- Sample variance
VAR_POP(column) -- Population variance

-- STRING_AGG/GROUP_CONCAT: Concatenate values


STRING_AGG(column, ',') -- PostgreSQL/SQL Server
GROUP_CONCAT(column) -- MySQL
LISTAGG(column, ',') -- Oracle

String/Text Functions

Basic String Operations

-- CONCAT: Concatenate strings


CONCAT(str1, str2, str3) -- Join multiple strings
str1 || str2 -- Concatenation operator (PostgreSQL/Oracle)

-- LENGTH/LEN: String length


LENGTH(string) -- MySQL/PostgreSQL
LEN(string) -- SQL Server
CHAR_LENGTH(string) -- Character length

-- SUBSTRING/SUBSTR: Extract part of string


SUBSTRING(string, start, length) -- Standard SQL
SUBSTR(string, start, length) -- Oracle/MySQL
LEFT(string, length) -- Get leftmost characters
RIGHT(string, length) -- Get rightmost characters

-- Examples
SELECT
CONCAT(first_name, ' ', last_name) as full_name,
LENGTH(email) as email_length,
SUBSTRING(phone, 1, 3) as area_code,
LEFT(zip_code, 5) as zip_prefix
FROM customers;
Case Conversion

-- UPPER/LOWER: Change case


UPPER(string) -- Convert to uppercase
LOWER(string) -- Convert to lowercase
INITCAP(string) -- Capitalize first letter of each word (Oracle)

-- Examples
SELECT
UPPER(last_name) as last_name_upper,
LOWER(email) as email_lower,
INITCAP(city) as city_proper
FROM employees;

String Cleaning and Formatting

-- TRIM: Remove whitespace


TRIM(string) -- Remove leading and trailing spaces
LTRIM(string) -- Remove leading spaces
RTRIM(string) -- Remove trailing spaces
TRIM(BOTH 'x' FROM string) -- Remove specific characters

-- REPLACE: Replace text


REPLACE(string, old_text, new_text) -- Replace all occurrences

-- REVERSE: Reverse string


REVERSE(string) -- Reverse character order

-- Examples
SELECT
TRIM(address) as clean_address,
REPLACE(phone, '-', '') as clean_phone,
REVERSE(product_code) as reversed_code
FROM products;

String Search and Pattern Matching

-- CHARINDEX/INSTR/POSITION: Find substring position


CHARINDEX(substring, string) -- SQL Server (1-based)
INSTR(string, substring) -- Oracle/MySQL (1-based)
POSITION(substring IN string) -- PostgreSQL (1-based)

-- LIKE: Pattern matching


column LIKE 'pattern' -- % for multiple chars, _ for single char
column ILIKE 'pattern' -- Case-insensitive LIKE (PostgreSQL)

-- SPLIT_PART: Split string by delimiter


SPLIT_PART(string, delimiter, part_number) -- PostgreSQL
Date and Time Functions

Current Date and Time

-- Current date/time functions


CURRENT_DATE -- Current date (YYYY-MM-DD)
CURRENT_TIME -- Current time (HH:MM:SS)
CURRENT_TIMESTAMP -- Current date and time
NOW() -- MySQL/PostgreSQL current timestamp
GETDATE() -- SQL Server current timestamp
SYSDATE -- Oracle current timestamp

-- Examples
SELECT
CURRENT_DATE as today,
CURRENT_TIME as now_time,
CURRENT_TIMESTAMP as now_full
FROM dual; -- Oracle; use any table for other databases

Date Extraction

-- EXTRACT: Get date parts


EXTRACT(YEAR FROM date) -- Get year
EXTRACT(MONTH FROM date) -- Get month
EXTRACT(DAY FROM date) -- Get day
EXTRACT(HOUR FROM datetime) -- Get hour

-- DATEPART: SQL Server date parts


DATEPART(YEAR, date) -- Get year
DATEPART(MONTH, date) -- Get month
DATEPART(DAY, date) -- Get day
DATEPART(WEEKDAY, date) -- Get day of week

-- YEAR/MONTH/DAY: Direct extraction functions


YEAR(date) -- Extract year
MONTH(date) -- Extract month
DAY(date) -- Extract day

-- Examples
SELECT
order_date,
EXTRACT(YEAR FROM order_date) as order_year,
EXTRACT(MONTH FROM order_date) as order_month,
YEAR(order_date) as year_alt,
MONTH(order_date) as month_alt
FROM orders;
Date Arithmetic

-- DATEADD: Add time intervals (SQL Server)


DATEADD(YEAR, 1, date) -- Add 1 year
DATEADD(MONTH, 6, date) -- Add 6 months
DATEADD(DAY, 30, date) -- Add 30 days

-- INTERVAL: Add intervals (MySQL/PostgreSQL)


date + INTERVAL '1 YEAR' -- Add 1 year
date + INTERVAL '6 MONTH' -- Add 6 months
date + INTERVAL '30 DAY' -- Add 30 days

-- ADD_MONTHS: Oracle month arithmetic


ADD_MONTHS(date, 6) -- Add 6 months

-- Examples
SELECT
hire_date,
DATEADD(YEAR, 1, hire_date) as anniversary, -- SQL Server
hire_date + INTERVAL '1 YEAR' as anniversary_mysql, -- MySQL
ADD_MONTHS(hire_date, 12) as anniversary_oracle -- Oracle
FROM employees;

Date Differences

-- DATEDIFF: Calculate differences


DATEDIFF(DAY, start_date, end_date) -- Days between dates (SQL Server)
DATEDIFF(YEAR, birth_date, GETDATE()) -- Age in years (SQL Server)

-- Direct subtraction (Oracle/PostgreSQL)


end_date - start_date -- Days between (Oracle)
AGE(end_date, start_date) -- Interval between (PostgreSQL)

-- Examples
SELECT
employee_name,
birth_date,
DATEDIFF(YEAR, birth_date, GETDATE()) as age,
DATEDIFF(DAY, hire_date, GETDATE()) as days_employed
FROM employees;

Date Formatting

-- FORMAT: Format dates (SQL Server)


FORMAT(date, 'yyyy-MM-dd') -- Custom format

-- TO_CHAR: Format dates (Oracle/PostgreSQL)


TO_CHAR(date, 'YYYY-MM-DD') -- Custom format
TO_CHAR(date, 'Month DD, YYYY') -- Month name format

-- DATE_FORMAT: Format dates (MySQL)


DATE_FORMAT(date, '%Y-%m-%d') -- Custom format
-- Examples
SELECT
order_date,
FORMAT(order_date, 'yyyy-MM-dd') as formatted_sql_server,
TO_CHAR(order_date, 'YYYY-MM-DD') as formatted_oracle,
DATE_FORMAT(order_date, '%Y-%m-%d') as formatted_mysql
FROM orders;

Mathematical Functions

Basic Math Operations

-- ABS: Absolute value


ABS(number) -- Returns positive value

-- ROUND: Rounding
ROUND(number) -- Round to nearest integer
ROUND(number, decimals) -- Round to specified decimal places

-- CEILING/CEIL: Round up
CEILING(number) -- Round up to nearest integer
CEIL(number) -- Same as CEILING (MySQL)

-- FLOOR: Round down


FLOOR(number) -- Round down to nearest integer

-- Examples
SELECT
price,
ABS(price - 100) as price_diff,
ROUND(price, 2) as rounded_price,
CEILING(price) as price_ceiling,
FLOOR(price) as price_floor
FROM products;

Advanced Math Functions

-- POWER/POW: Exponentiation
POWER(base, exponent) -- Raise base to power
POW(base, exponent) -- Same as POWER (MySQL)

-- SQRT: Square root


SQRT(number) -- Square root

-- LOG: Logarithms
LOG(number) -- Natural logarithm
LOG10(number) -- Base-10 logarithm
LOG(base, number) -- Logarithm with custom base

-- EXP: Exponential
EXP(number) -- e raised to power

-- Examples
SELECT
quantity,
POWER(quantity, 2) as quantity_squared,
SQRT(quantity) as quantity_sqrt,
LOG(quantity) as quantity_ln
FROM inventory;

Trigonometric Functions

-- Basic trig functions


SIN(radians) -- Sine
COS(radians) -- Cosine
TAN(radians) -- Tangent

-- Inverse trig functions


ASIN(value) -- Arcsine
ACOS(value) -- Arccosine
ATAN(value) -- Arctangent

-- Angle conversion
RADIANS(degrees) -- Convert degrees to radians
DEGREES(radians) -- Convert radians to degrees

-- Constants
PI() -- Value of π (3.14159...)

Other Math Functions

-- SIGN: Get sign of number


SIGN(number) -- Returns -1, 0, or 1

-- MOD: Modulo operation


MOD(dividend, divisor) -- Remainder after division
number % divisor -- Modulo operator

-- RANDOM/RAND: Random numbers


RANDOM() -- Random 0-1 (PostgreSQL)
RAND() -- Random 0-1 (MySQL/SQL Server)
RAND(seed) -- Random with seed

-- Examples
SELECT
SIGN(profit) as profit_direction,
MOD(order_id, 10) as last_digit,
RAND() as random_value
FROM sales;
Window Functions

Ranking Functions

-- ROW_NUMBER: Unique sequential numbers


ROW_NUMBER() OVER (ORDER BY column)
ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC)

-- RANK: Ranking with gaps for ties


RANK() OVER (ORDER BY score DESC)
RANK() OVER (PARTITION BY category ORDER BY price)

-- DENSE_RANK: Ranking without gaps


DENSE_RANK() OVER (ORDER BY salary DESC)

-- NTILE: Divide into equal groups


NTILE(4) OVER (ORDER BY sales) -- Quartiles

-- Examples
SELECT
employee_name,
department,
salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) as row_num,
RANK() OVER (ORDER BY salary DESC) as salary_rank,
DENSE_RANK() OVER (ORDER BY salary DESC) as dense_rank,
NTILE(4) OVER (ORDER BY salary DESC) as quartile
FROM employees;

Aggregate Window Functions

-- SUM: Running totals


SUM(amount) OVER (ORDER BY date) -- Cumulative sum
SUM(amount) OVER (PARTITION BY customer ORDER BY date) -- By customer

-- AVG: Moving averages


AVG(amount) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)

-- COUNT: Running counts


COUNT(*) OVER (ORDER BY date)

-- Examples
SELECT
order_date,
amount,
SUM(amount) OVER (ORDER BY order_date) as running_total,
AVG(amount) OVER (ORDER BY order_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) as mo
FROM orders;
Offset Functions

-- LAG: Previous row value


LAG(column, offset, default) OVER (ORDER BY column)
LAG(salary, 1, 0) OVER (ORDER BY hire_date) -- Previous salary

-- LEAD: Next row value


LEAD(column, offset, default) OVER (ORDER BY column)
LEAD(salary, 1, 0) OVER (ORDER BY hire_date) -- Next salary

-- FIRST_VALUE: First value in window


FIRST_VALUE(column) OVER (PARTITION BY dept ORDER BY salary DESC)

-- LAST_VALUE: Last value in window


LAST_VALUE(column) OVER (PARTITION BY dept ORDER BY salary DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)

-- Examples
SELECT
employee_name,
salary,
hire_date,
LAG(salary, 1, 0) OVER (ORDER BY hire_date) as prev_salary,
LEAD(salary, 1, 0) OVER (ORDER BY hire_date) as next_salary,
FIRST_VALUE(salary) OVER (PARTITION BY department ORDER BY salary DESC) as highest_de
FROM employees;

Conditional Functions

CASE Statement

-- Simple CASE
CASE column
WHEN value1 THEN result1
WHEN value2 THEN result2
ELSE default_result
END

-- Searched CASE
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
END

-- Examples
SELECT
employee_name,
salary,
CASE
WHEN salary > 80000 THEN 'High'
WHEN salary > 50000 THEN 'Medium'
ELSE 'Low'
END as salary_category,
CASE department
WHEN 'IT' THEN 'Technology'
WHEN 'HR' THEN 'Human Resources'
ELSE 'Other'
END as dept_category
FROM employees;

IF Functions (MySQL)

-- IF: Simple conditional


IF(condition, true_value, false_value)

-- Examples
SELECT
product_name,
price,
IF(price > 100, 'Expensive', 'Affordable') as price_category
FROM products;

NULL Handling Functions

COALESCE

-- COALESCE: Return first non-NULL value


COALESCE(value1, value2, value3, default)

-- Examples
SELECT
customer_name,
COALESCE(phone_mobile, phone_home, phone_work, 'No phone') as contact_phone,
COALESCE(email, 'No email') as contact_email
FROM customers;

ISNULL/IFNULL

-- ISNULL: Replace NULL with value (SQL Server)


ISNULL(column, replacement_value)

-- IFNULL: Replace NULL with value (MySQL)


IFNULL(column, replacement_value)

-- NVL: Replace NULL with value (Oracle)


NVL(column, replacement_value)

-- Examples
SELECT
employee_name,
ISNULL(middle_name, '') as middle_name_clean, -- SQL Server
IFNULL(bonus, 0) as bonus_amount, -- MySQL
NVL(commission, 0) as commission_amount -- Oracle
FROM employees;

NULLIF

-- NULLIF: Return NULL if values are equal


NULLIF(value1, value2)

-- Examples
SELECT
customer_name,
NULLIF(discount, 0) as actual_discount -- Returns NULL if discount is 0
FROM customers;

Conversion Functions

CAST and CONVERT

-- CAST: Standard SQL conversion


CAST(expression AS data_type)

-- CONVERT: SQL Server conversion with format


CONVERT(data_type, expression)
CONVERT(data_type, expression, style)

-- Examples
SELECT
order_id,
CAST(order_date AS VARCHAR) as date_string,
CAST(total_amount AS INT) as amount_integer,
CONVERT(VARCHAR(10), order_date, 101) as formatted_date -- SQL Server MM/DD/YYYY
FROM orders;

TO_CHAR/TO_NUMBER/TO_DATE (Oracle)

-- TO_CHAR: Convert to string


TO_CHAR(number, 'format')
TO_CHAR(date, 'format')

-- TO_NUMBER: Convert to number


TO_NUMBER(string, 'format')

-- TO_DATE: Convert to date


TO_DATE(string, 'format')

-- Examples
SELECT
employee_id,
TO_CHAR(salary, '$999,999.99') as formatted_salary,
TO_CHAR(hire_date, 'Month DD, YYYY') as formatted_hire_date,
TO_NUMBER('1234.56', '9999.99') as converted_number,
TO_DATE('2023-12-25', 'YYYY-MM-DD') as converted_date
FROM employees;

Other Conversion Functions

-- STR: Convert number to string (SQL Server)


STR(number, length, decimal_places)

-- FORMAT: Format values (SQL Server)


FORMAT(value, format)
FORMAT(123456.789, 'C', 'en-US') -- Currency format
FORMAT(GETDATE(), 'yyyy-MM-dd') -- Date format

-- Examples
SELECT
product_id,
STR(price, 10, 2) as price_string,
FORMAT(price, 'C', 'en-US') as price_currency,
FORMAT(created_date, 'yyyy-MM-dd') as formatted_date
FROM products;

Analytical Functions

Statistical Functions

-- PERCENTILE: Calculate percentiles


PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) -- Median
PERCENTILE_DISC(0.25) WITHIN GROUP (ORDER BY salary) -- 25th percentile

-- PERCENT_RANK: Relative rank as percentage


PERCENT_RANK() OVER (ORDER BY salary)

-- CUME_DIST: Cumulative distribution


CUME_DIST() OVER (ORDER BY salary)

-- Examples
SELECT
employee_name,
salary,
PERCENT_RANK() OVER (ORDER BY salary) as salary_percent_rank,
CUME_DIST() OVER (ORDER BY salary) as salary_cume_dist
FROM employees;
System Functions

Information Functions

-- USER: Current user


USER() -- MySQL
CURRENT_USER -- PostgreSQL/SQL Server
USER -- Oracle

-- DATABASE: Current database


DATABASE() -- MySQL
DB_NAME() -- SQL Server
CURRENT_SCHEMA -- PostgreSQL

-- VERSION: Database version


VERSION() -- MySQL/PostgreSQL
@@VERSION -- SQL Server

-- Examples
SELECT
USER() as current_user,
DATABASE() as current_db,
VERSION() as db_version;

Quick Problem-Solving Guide

Common Problem Patterns

1. Finding Top N Records per Group

-- Using ROW_NUMBER()
WITH ranked_data AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) as rn
FROM products
)
SELECT * FROM ranked_data WHERE rn <= 3;

2. Running Totals and Moving Averages

SELECT
date,
amount,
SUM(amount) OVER (ORDER BY date) as running_total,
AVG(amount) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) as moving_a
FROM sales;
3. Comparing Current vs Previous Values

SELECT
month,
revenue,
LAG(revenue) OVER (ORDER BY month) as prev_month_revenue,
revenue - LAG(revenue) OVER (ORDER BY month) as revenue_change,
ROUND((revenue - LAG(revenue) OVER (ORDER BY month)) / LAG(revenue) OVER (ORDER BY mo
FROM monthly_sales;

4. Handling NULL Values Elegantly

SELECT
customer_name,
COALESCE(phone, email, 'No contact info') as primary_contact,
CASE
WHEN phone IS NOT NULL THEN 'Phone: ' || phone
WHEN email IS NOT NULL THEN 'Email: ' || email
ELSE 'No contact available'
END as contact_display
FROM customers;

5. Text Processing and Cleaning

SELECT
TRIM(UPPER(product_name)) as clean_name,
REPLACE(REPLACE(phone, '-', ''), ' ', '') as clean_phone,
SUBSTRING(description, 1, 50) || '...' as short_description
FROM products
WHERE LENGTH(TRIM(product_name)) > 0;

6. Date Calculations and Formatting

SELECT
customer_id,
birth_date,
EXTRACT(YEAR FROM AGE(CURRENT_DATE, birth_date)) as age,
CASE
WHEN EXTRACT(YEAR FROM AGE(CURRENT_DATE, birth_date)) >= 65 THEN 'Senior'
WHEN EXTRACT(YEAR FROM AGE(CURRENT_DATE, birth_date)) >= 18 THEN 'Adult'
ELSE 'Minor'
END as age_category,
TO_CHAR(birth_date, 'Month DD, YYYY') as formatted_birth_date
FROM customers;
7. Pivot-like Operations with CASE

SELECT
product_id,
SUM(CASE WHEN EXTRACT(MONTH FROM order_date) = 1 THEN quantity ELSE 0 END) as jan_sal
SUM(CASE WHEN EXTRACT(MONTH FROM order_date) = 2 THEN quantity ELSE 0 END) as feb_sal
SUM(CASE WHEN EXTRACT(MONTH FROM order_date) = 3 THEN quantity ELSE 0 END) as mar_sal
FROM order_details od
JOIN orders o ON od.order_id = o.order_id
GROUP BY product_id;

Performance Tips
Use window functions instead of correlated subqueries when possible
Prefer EXISTS over IN with subqueries for better performance
Use COALESCE instead of nested CASE WHEN ... IS NULL statements

Index columns used in window function PARTITION BY and ORDER BY clauses

Be cautious with LAST_VALUE - always specify window frame explicitly


This cheatsheet covers the most commonly used SQL functions across major database systems.
Keep it handy for quick reference during development and problem-solving!

Common questions

Powered by AI

The COUNT function in SQL can be applied in three main ways: COUNT(*), COUNT(column), and COUNT(DISTINCT column). COUNT(*) counts all rows in the result set, including ones with NULL values. COUNT(column) counts only the rows where the specified column is not NULL. COUNT(DISTINCT column) counts unique non-NULL values in a specified column .

ROW_NUMBER() assigns a unique sequential integer to rows within a partition, allowing for row-level identification useful for deduplication or pagination tasks. NTILE() divides the result set into 'n' bucket segments, which is crucial for dividing data into quantiles for statistical analysis. Both are powerful for advanced data analysis, enabling flexible data parsing without altering the dataset structure .

The CASE statement in SQL allows the inclusion of conditional logic within queries, enabling dynamic outcomes based on data values. It can be used for categorizing data or performing multiple conditional checks. For example, a query could calculate a salary category by evaluating salary levels: SELECT employee_name, salary, CASE WHEN salary > 80000 THEN 'High' WHEN salary > 50000 THEN 'Medium' ELSE 'Low' END as salary_category FROM employees .

CURRENT_DATE returns the current date in the format YYYY-MM-DD in all systems, but CURRENT_TIMESTAMP fetches both current date and time. The specific formatting and precision of CURRENT_TIMESTAMP may vary across databases like MySQL, PostgreSQL, SQL Server, and Oracle. These functions are typically used in logging operations, tracking data modifications, or creating audit trails .

The CONCAT function can join multiple strings or column values into a single result, which enhances readability and presentation, such as formatting full names by combining first and last names or constructing complex data outputs like addresses. However, it might not handle NULL values gracefully unless handled explicitly, as any NULL in a CONCAT operation can result in a NULL overall output .

REPLACE enables substitution of specific text segments within strings, which is invaluable for data cleansing, such as standardizing phone numbers. LEFT can extract a specified number of characters from the start of a string, useful in formatting or extracting prefixes. However, both functions operate firmly on fixed criteria; they lack the flexibility of pattern recognition in regular expressions, limiting them in dynamic text transformations .

CURRENT_TIMESTAMP is used in MySQL/PostgreSQL to return the current date and time with precision. GETDATE() serves the same purpose in SQL Server, although its precision might slightly differ. A key usage scenario for both includes timestamping records at the time of insertion or updating, facilitating tracking changes and historical analysis .

DATEADD (in SQL Server) and INTERVAL (in MySQL/PostgreSQL) allow the addition of a specified time interval to a given date, aiding in scenarios like setting expiration dates or forecasting. For example, adding one year to hire_date to determine an anniversary might use SELECT hire_date, DATEADD(YEAR, 1, hire_date) as anniversary in SQL Server, and similarly hire_date + INTERVAL '1 YEAR' in MySQL/PostgreSQL .

SQL provides functions like COALESCE, ISNULL, IFNULL, and NVL to handle NULL values. COALESCE returns the first non-NULL value from a series of arguments and is standard across most SQL databases. ISNULL and IFNULL are specific to SQL Server and MySQL, respectively, and replace NULL with a specified value. NVL serves the same purpose in Oracle databases. These approaches ensure operations can proceed by substituting NULLs with meaningful defaults .

LAG and LEAD functions in SQL allow access to a value in a prior or subsequent row within the same result set without using complex joins. This capability is crucial for comparing current with previous or next observations in a dataset, such as tracking the change in salaries or stock prices over time. This results in more straightforward, efficient comparative analytic operations .

You might also like