SQL Cheat Sheet: High‑Frequency String, Date, and Math Functions Ready for Immediate Use
Many developers write messy SQL or generate slow reports because they don’t know built‑in functions; this guide compiles the most frequently used string, date, math, and conversion functions—complete with ready‑to‑copy examples—to handle 99% of everyday data‑processing scenarios.
String Functions
LEN() – returns the length of a string. SELECT LEN('SQL小白实战') AS StrLength; SUBSTRING() – extracts a substring from a specified start position with a given length. SELECT SUBSTRING('13800138000',1,3) AS 手机号前三位; REPLACE() – replaces occurrences of a substring with another string. SELECT REPLACE('测试文本','测试','实战') AS NewText; UPPER() and LOWER() – convert a string to upper‑case or lower‑case. SELECT UPPER('sql'), LOWER('SQL'); LTRIM() and RTRIM() – remove leading or trailing spaces.
SELECT LTRIM(' 左空格'), RTRIM('右空格 ');Date & Time Functions
GETDATE() – returns the current timestamp. SELECT GETDATE() AS NowTime; DATEPART() – extracts a specific part (year, month, day, hour, etc.) from a date.
SELECT DATEPART(YEAR,GETDATE()) AS 年,
DATEPART(MONTH,GETDATE()) AS 月,
DATEPART(DAY,GETDATE()) AS 日;DATEADD() – adds or subtracts a specified interval to a date. SELECT DATEADD(DAY,3,GETDATE()) AS AfterThreeDay; DATEDIFF() – calculates the difference between two dates in a specified unit.
SELECT DATEDIFF(DAY,'2025-01-01',GETDATE()) AS DiffDay;Math Functions
ROUND() – rounds a numeric value to a given number of decimal places. SELECT ROUND(99.876,2) AS 保留两位小数; CEILING() and FLOOR() – round a number up or down to the nearest integer. SELECT CEILING(10.1), FLOOR(10.9); ABS() – returns the absolute value of a number.
SELECT ABS(-99.9) AS 绝对值;Conversion Functions
CAST() and CONVERT() – change a value from one data type to another.
-- Number to string
SELECT CAST(123 AS VARCHAR(20)) AS StrNum;
-- Date formatting (ISO 8601)
SELECT CONVERT(VARCHAR(10),GETDATE(),23) AS 标准日期;Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
liandk
Seasoned Java and mobile developer with years of experience, specializing in mini‑programs, public accounts, and full‑stack front‑end development. In the AI era, I continuously learn to broaden my knowledge and evolve. I revived a public account I started a decade ago during a dessert‑startup venture, using code as a vessel and knowledge as a companion. I share personal projects, technical articles, programming tips, and growth insights—let’s improve together and set sail.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
