0% found this document useful (0 votes)
42 views2 pages

SQL Functions for LeetCode Challenges

The document outlines the most commonly used SQL functions categorized into mathematical, string, date, aggregate, logical, and window functions. It provides specific examples of each function, such as ROUND, LENGTH, DATEDIFF, COUNT, and IF, along with their purposes. Additionally, it mentions useful clauses like LIMIT for controlling output rows.

Uploaded by

maxsinghparihar
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)
42 views2 pages

SQL Functions for LeetCode Challenges

The document outlines the most commonly used SQL functions categorized into mathematical, string, date, aggregate, logical, and window functions. It provides specific examples of each function, such as ROUND, LENGTH, DATEDIFF, COUNT, and IF, along with their purposes. Additionally, it mentions useful clauses like LIMIT for controlling output rows.

Uploaded by

maxsinghparihar
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

Most Used SQL Functions in LeetCode Top 50

Mathematical Functions

ROUND(column, decimals): Rounds to specified decimal places

FLOOR(column): Rounds down to nearest integer

CEIL(column) / CEILING(column): Rounds up to nearest integer

ABS(column): Absolute value

MOD(a, b): Modulus (remainder of a/b)

String Functions

LENGTH(string): Number of characters

LEFT(string, n) / RIGHT(string, n): Get leftmost/rightmost characters

SUBSTRING(string, start, length): Extract substring

CONCAT(str1, str2): Join strings

LOWER(string) / UPPER(string): Case conversion

TRIM(string): Remove leading/trailing spaces

REPLACE(string, from, to): Replace substring

INSTR(string, substring): Position of substring (MySQL)

Date Functions

DATEDIFF(date1, date2): Days between dates

DATE_FORMAT(date, format): Format date (MySQL specific)

YEAR(date) / MONTH(date) / DAY(date): Extract year, month, or day

NOW() / CURDATE(): Current date/time

STR_TO_DATE(str, format): Convert string to date

Aggregate Functions

COUNT(*) / COUNT(DISTINCT col): Count rows or unique values

SUM(column): Total sum

AVG(column): Average value

MIN(column) / MAX(column): Minimum or maximum value


Most Used SQL Functions in LeetCode Top 50

Logical / Conditional Functions

IF(condition, true_value, false_value): Conditional logic (MySQL)

CASE WHEN THEN ELSE END: SQL standard conditional branching

ISNULL(value) / IFNULL(col, default): Handle nulls

Window Functions (Advanced)

ROW_NUMBER() OVER (...): Assign row number in partitions

RANK() / DENSE_RANK(): Rank rows

LEAD() / LAG(): Previous or next rows value

Other Useful Clauses

LIMIT n: Limit number of output rows (used for top-N queries)

Common questions

Powered by AI

DATE_FORMAT allows users to convert dates to preferred string representations, controlling the appearance of dates in outputs by specifying format strings (e.g., 'YYYY-MM-DD', 'DD-MM-YYYY'). This enhances readability and interpretation, particularly in reports or user interfaces where a specific date format aligns with regional, cultural, or contextual preferences, facilitating better understanding among diverse audiences.

INSTR provides a direct position index of a substring within a string, allowing precise location tracking and enhancing search efficiency compared to LIKE, which only confirms existence. INSTR's ability to specify starting positions and efficiently compute substring presence offers faster performance in large datasets by bypassing wildcard patterns and focusing on substring indices.

COUNT(DISTINCT column) calculates the number of unique values in a column, which helps in understanding the diversity or uniqueness of data entries and avoiding duplicates. Alternatively, COUNT(*) counts all rows, including duplicates and nulls. The choice between them significantly affects query results, particularly in data analysis contexts where identifying unique entries or duplicates impacts insights or decisions.

DATEDIFF efficiently calculates the day difference between two dates, useful for aging or duration analysis in applications such as calculating payment deadlines or service durations. Alternatives might include manual calculations using DAY and arithmetic or more accuracy-focused functions for considering hours and minutes. DATEDIFF is optimal for whole-day calculations, though less suited for needs addressing smaller time units.

Both IF and CASE WHEN THEN ELSE allow conditional queries, but they differ in flexibility and standardization. IF is limited to MySQL, uses fewer conditions, and is formatted as IF(condition, true_value, false_value). CASE is an SQL standard and supports complex multi-condition checks, formatted as CASE WHEN condition THEN result ELSE default END. CASE is more versatile and preferred when handling multiple conditions across various SQL platforms.

LEAD and LAG functions enable row-based, non-aggregated calculations across partitions of data, allowing users to access subsequent or preceding row values within those partitions. This capability facilitates calculations that depend on values from different rows, such as moving averages or differences between current and previous transaction amounts, enhancing SQL's analytical capabilities beyond simple aggregations.

The ROUND function adjusts a numeric value to a specified number of decimal places, rounding away from zero if the next digit is 5 or greater. FLOOR, on the other hand, rounds down to the nearest integer, regardless of whether the fractional component is above or below .5. Conversely, CEIL (or CEILING) rounds up to the nearest integer, irrespective of the fractional part. This nuanced behavior allows each function to round numbers differently depending on the desired outcome.

The primary pitfall of using the TRIM function is that it only removes leading and trailing spaces but does not affect spaces within the string. If the data integrity relies on uniform spacing or normalized data, relying exclusively on TRIM could lead to inconsistencies. Furthermore, if specific characters are mistakenly considered as part of the leading or trailing spaces, they may be removed unnecessarily, affecting data accuracy.

RANK assigns the same rank to rows with identical values, but skips subsequent ranks, thus reflecting more accurately on data tied within the same ordered group. ROW_NUMBER, however, assigns unique sequential numbers without regard to duplicate values, potentially leading to misleading interpretations in datasets containing ties. RANK's handling of ties makes it more suited for rankings that require consistency in grouping equivalently ranked items.

REPLACE is particularly useful when you want to substitute all occurrences of a specific substring with another substring throughout a string, making it ideal for cleaning or standardizing data. In contrast, SUBSTRING is used when you need to extract a specific part of the string rather than modify or replace sections within it. Choosing REPLACE over SUBSTRING is apt when the objective is focused on modification rather than extraction.

You might also like