🧾 SQL References & Functions
Estimated reading: 3 minutes 40 views

πŸ› οΈ SQL Server Functions – Built-In String, Date, Math, and Conditional Functions

🧲 Introduction – Why SQL Server Functions Are Essential

SQL Server functions are powerful built-in operations that let you manipulate strings, perform calculations, handle dates, evaluate conditions, and moreβ€”all directly within your SQL queries. These functions reduce the need for external logic and help make your code cleaner, faster, and easier to maintain.

Whether you’re formatting data for reports, calculating metrics, or transforming input, mastering SQL Server’s function library unlocks next-level efficiency.

🎯 In this guide, you’ll learn:

  • Categories of built-in SQL Server functions
  • Syntax and usage with practical examples
  • Real-world scenarios where functions shine
  • Tips for performance and compatibility

πŸ“š 1. SQL Server Function Categories

CategoryExamplesUse Case
πŸ”€ StringLEN(), CHARINDEX(), REPLACE()Formatting, searching, cleaning text
πŸ”’ MathROUND(), ABS(), POWER()Financial calculations, metrics
πŸ—“οΈ Date/TimeGETDATE(), DATEADD(), DATEDIFF()Reports, logs, scheduling
πŸ“Š AggregateSUM(), AVG(), COUNT()Analytics and summaries
❓ ConditionalIIF(), CASE, ISNULL(), COALESCE()Flow control, null handling
🧠 MetadataSUSER_NAME(), DB_NAME(), @@VERSIONSession and server diagnostics

πŸ”€ 2. String Functions in SQL Server

βœ… Common Examples

SELECT LEN('SQL Server');           -- β†’ 10
SELECT REPLACE('123-456', '-', '') -- β†’ '123456'
SELECT CHARINDEX('S', 'SQL');      -- β†’ 1

πŸ“˜ Use LTRIM() and RTRIM() to remove leading/trailing spaces.


πŸ”’ 3. Math Functions

SELECT ROUND(123.4567, 2);      -- β†’ 123.46
SELECT ABS(-500);              -- β†’ 500
SELECT POWER(2, 5);            -- β†’ 32

Great for billing, scientific data, and analytics.


πŸ—“οΈ 4. Date & Time Functions

SELECT GETDATE();              -- Current datetime
SELECT DATEADD(DAY, 7, GETDATE());   -- 7 days from now
SELECT DATEDIFF(YEAR, '2000-01-01', GETDATE()); -- Age calculation

βœ… SQL Server stores datetime with high precision. Use FORMAT() for display formatting.


πŸ“Š 5. Aggregate Functions

SELECT COUNT(*) FROM orders;
SELECT AVG(price) FROM products;
SELECT MAX(salary) FROM employees;

πŸ“˜ Must be used with GROUP BY for grouped results.


❓ 6. Conditional and Null Handling

SELECT IIF(score >= 60, 'Pass', 'Fail') FROM exams;

SELECT CASE
  WHEN age < 18 THEN 'Minor'
  WHEN age >= 18 THEN 'Adult'
END FROM people;

SELECT ISNULL(name, 'N/A') FROM employees;
SELECT COALESCE(phone, email, 'Not Provided');

🧠 IIF() is shorthand for CASE, introduced in SQL Server 2012+.


🧠 7. System & Metadata Functions

SELECT DB_NAME();           -- Current database
SELECT SYSTEM_USER;         -- Logged-in user
SELECT @@VERSION;           -- SQL Server version

Use these in logging, audits, or dynamic SQL.


πŸ“¦ 8. Real-World Use Cases

ScenarioFunctions Used
Generate full namesCONCAT(), LTRIM(), RTRIM()
Age calculationDATEDIFF(), GETDATE()
Display formatted currencyFORMAT(price, 'C')
Clean up null values in reportsISNULL(), COALESCE()
Create ranked reportsRANK() OVER, ROW_NUMBER()

βš™οΈ 9. Performance Tips

  • βœ… Use scalar functions sparingly in WHERE/JOIN clausesβ€”can block index use
  • βœ… Prefer ISNULL() for single fallback, COALESCE() for multiple
  • βœ… Avoid FORMAT() in high-volume queriesβ€”great for display, not speed

πŸ“Œ Summary – Recap & Next Steps

SQL Server functions are essential for writing powerful, reusable, and concise queries. Knowing when and how to use these built-in tools lets you solve complex problems without leaving SQL.

πŸ” Key Takeaways:

  • Built-in functions span string, math, date, and logic categories
  • Use conditional functions for cleaner, readable business logic
  • Use system functions for environment awareness and security

βš™οΈ Real-World Relevance:
Widely used in financial systems, enterprise dashboards, admin panels, stored procedures, and report generators.


❓ FAQ – SQL Server Functions

❓ What’s the difference between IIF() and CASE?

βœ… IIF() is simpler for binary decisions. CASE handles multiple conditions and is more flexible.

❓ Can I create my own functions?

βœ… Yes, use CREATE FUNCTION to build User-Defined Functions (UDFs).

❓ Is FORMAT() efficient for sorting?

❌ No. Use FORMAT() for display only, not in WHERE or ORDER BY clauses.

❓ What’s the safest way to handle NULL values?

βœ… Use ISNULL() for defaults, or COALESCE() for fallback chains.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ› οΈ SQL Server Functions

Or Copy Link

CONTENTS
Scroll to Top