Introduction
In the previous lessons, you learned how to use basic SELECT queries, filtering, and sorting. In this lesson, you will go beyond simply listing data. You will transform values during query execution and present the results in a form that is easier for users and applications to understand.
SQL Server functions are built-in T-SQL tools that perform an operation on one or more values and return a result. String functions help format character data, numeric functions perform calculations, and date-time functions extract date parts or calculate intervals. Aliases make column headings more meaningful, while calculated columns produce new values from existing columns.
The examples use product data in the WorkshopDB database. Run the scripts in SSMS after selecting the appropriate database.
Preparing the example environment
USE WorkshopDB;
GO
IF OBJECT_ID('dbo.Products', 'U') IS NOT NULL
DROP TABLE dbo.Products;
GO
CREATE TABLE dbo.Products
(
ProductID int IDENTITY(1,1) NOT NULL PRIMARY KEY,
ProductName nvarchar(100) NOT NULL,
Category nvarchar(50) NOT NULL,
UnitPrice decimal(10,2) NOT NULL,
StockQuantity int NOT NULL,
CreatedAt date NOT NULL
);
GO
INSERT INTO dbo.Products
(ProductName, Category, UnitPrice, StockQuantity, CreatedAt)
VALUES
(N'Kablosuz Klavye', N'Aksesuar', 899.90, 25, '2025-02-10'),
(N'USB-C Çoklayıcı', N'Aksesuar', 649.50, 12, '2025-03-18'),
(N'27 inç Monitör', N'Monitör', 7499.00, 7, '2024-11-05'),
(N'Ofis Koltuğu', N'Ofis', 5250.75, 4, '2025-01-22');
GOString functions
String functions are useful in reporting, search screens, and application output. Common examples include UPPER, LOWER, LEN, LEFT, RIGHT, SUBSTRING, REPLACE, and CONCAT.
Changing case and measuring length
SELECT
ProductName,
UPPER(ProductName) AS [Uppercase Product],
LOWER(Category) AS [Lowercase Category],
LEN(ProductName) AS [Product Name Length]
FROM dbo.Products;The AS expression assigns an alias to a result column. Aliases can contain spaces when they are enclosed in square brackets. An alias does not rename the actual database column; it changes only the heading returned by that query.
Extracting and replacing text
SELECT
ProductName,
LEFT(ProductName, 5) AS [First Five Characters],
RIGHT(ProductName, 4) AS [Last Four Characters],
REPLACE(Category, N'Aksesuar', N'Çevre Birimi') AS [Displayed Category]
FROM dbo.Products;LEFT and RIGHT return characters from the beginning or end of a string. REPLACE substitutes every matching occurrence of one text value with another. Using these functions inside a SELECT statement is safe when you only want to change the displayed result; the stored values remain unchanged.
Combining strings
SELECT
CONCAT(ProductName, N' - ', Category) AS [Product Description]
FROM dbo.Products;CONCAT combines values into one string and can handle NULL values as empty strings. When the + operator is used for concatenation, a NULL input can cause the complete result to become NULL. For incomplete data, CONCAT or COALESCE is often safer.
Numeric functions
Numeric functions are used for prices, quantities, discounts, scores, and other calculations. ABS returns an absolute value, ROUND rounds a number, CEILING rounds upward to the next integer, and FLOOR rounds downward.
SELECT
ProductName,
UnitPrice,
ROUND(UnitPrice * 1.20, 2) AS [Price Including Tax],
CEILING(UnitPrice) AS [Ceiling Value],
FLOOR(UnitPrice) AS [Floor Value],
ABS(StockQuantity - 10) AS [Distance From Ten]
FROM dbo.Products;In this example, UnitPrice * 1.20 calculates a price increased by 20 percent. ROUND limits the displayed calculation to two decimal places. For financial calculations, an appropriate decimal type is generally preferable to avoid unnecessary precision loss.
Data types and division
When two integer values are divided in T-SQL, the result can be integer division. If a decimal result is required, convert at least one operand to a decimal type.
SELECT
ProductName,
StockQuantity / 10 AS [Integer Division],
CAST(StockQuantity AS decimal(10,2)) / 10 AS [Decimal Division]
FROM dbo.Products;Date and time functions
Date and time functions support reporting, aging calculations, period analysis, and future-date calculations. YEAR, MONTH, and DAY return numeric date parts. DATENAME returns a textual date-part value. DATEADD adds an interval to a date, while DATEDIFF calculates the difference between two dates.
SELECT
ProductName,
CreatedAt,
YEAR(CreatedAt) AS [Year],
MONTH(CreatedAt) AS [Month Number],
DATENAME(month, CreatedAt) AS [Month Name],
DATEADD(month, 6, CreatedAt) AS [Six Months Later],
DATEDIFF(day, CreatedAt, CAST(GETDATE() AS date)) AS [Days Elapsed]
FROM dbo.Products;GETDATE() returns the current date and time from the SQL Server computer. Therefore, the Days Elapsed result changes when the query is executed on a different day. For repeatable tests, use a parameter or a fixed reference date instead of relying on the current system time.
Avoid ambiguous regional date formats. Values written in the YYYY-MM-DD form are clear and practical for examples that use the date data type.
Aliases and calculated columns
A calculated expression can be generated in a query without adding a physical column to the table. For example, inventory value can be calculated by multiplying unit price by stock quantity.
SELECT
ProductID AS [Product ID],
ProductName AS [Product Name],
UnitPrice AS [Unit Price],
StockQuantity AS [Stock Quantity],
UnitPrice * StockQuantity AS [Total Inventory Value]
FROM dbo.Products
ORDER BY [Total Inventory Value] DESC;In this query, [Total Inventory Value] is only an alias in the result set. If the same calculation is required frequently or should be part of the table definition, you can define a computed column.
Creating a computed column with a table
CREATE TABLE dbo.ProductInventory
(
ProductID int NOT NULL PRIMARY KEY,
UnitPrice decimal(10,2) NOT NULL,
StockQuantity int NOT NULL,
StockValue AS (UnitPrice * StockQuantity)
);A computed column is defined by an expression that uses columns from the same table. You do not provide a direct INSERT or UPDATE value for the computed column. When its source columns change, SQL Server calculates the result again.
Adding a computed column to an existing table
ALTER TABLE dbo.Products
ADD StockValue AS (UnitPrice * StockQuantity);
GO
SELECT ProductName, UnitPrice, StockQuantity, StockValue
FROM dbo.Products;The PERSISTED option can be used when appropriate. It causes SQL Server to physically store the computed value and update it when dependent columns change. It is not required for every calculation. For simple calculations with low processing cost, a regular computed column may be sufficient.
NULL values and conversions
NULL is not zero and is not an empty string. It represents an unknown or unavailable value. Functions handle NULL differently, so define the desired behavior before producing a report. COALESCE can provide a fallback value.
SELECT
ProductName,
COALESCE(Category, N'Category not specified') AS [Category]
FROM dbo.Products;Use CAST or CONVERT when you need to change a data type. If a conversion might fail because of invalid input, TRY_CAST or TRY_CONVERT can return NULL instead of stopping the entire query with a conversion error.
Common mistakes
- Confusing an alias with a real column name:
ASchanges the result heading, not the table schema. - Using an unsuitable type for money: Consider
decimalwith suitable precision for financial calculations. - Overlooking integer division: Use
CASTorCONVERTwhen a decimal result is required. - Ignoring
NULLbehavior: Decide how missing values should be handled before concatenation or arithmetic. - Treating current dates as fixed values:
GETDATE()can return a different result each time the query runs. - Trying to assign a value to a computed column: Update the source columns instead.
- Using
FORMATunnecessarily: Formatting can convert results to text. Preserve numeric or date types when sorting and calculating.
Short practice exercise
Complete the following task using dbo.Products:
- Return the product name in uppercase with the alias
ProductNameDisplay. - Calculate the unit price after a 10 percent discount, rounded to two decimal places.
- Display the creation year and the date six months after creation.
- Multiply unit price by stock quantity and return the result as
InventoryValue. - Sort the results by inventory value in descending order.
SELECT
UPPER(ProductName) AS [ProductNameDisplay],
ROUND(UnitPrice * 0.90, 2) AS [DiscountedPrice],
YEAR(CreatedAt) AS [CreationYear],
DATEADD(month, 6, CreatedAt) AS [SixMonthsLater],
UnitPrice * StockQuantity AS [InventoryValue]
FROM dbo.Products
ORDER BY [InventoryValue] DESC;Conclusion
In this lesson, you learned how to transform strings, perform numeric calculations, and analyze date-time values with SQL Server functions. You also used aliases to improve report readability and explored calculated columns both in queries and in table definitions.
When using functions, pay close attention to data types, NULL values, date formats, and rounding behavior. In later lessons, these techniques can be combined with JOIN, GROUP BY, views, and more advanced reporting queries to produce richer database results.
Sources
- https://learn.microsoft.com/en-us/sql/t-sql/functions/string-functions-transact-sql?view=sql-server-ver17
- https://learn.microsoft.com/en-us/sql/t-sql/functions/date-and-time-data-types-and-functions-transact-sql?view=sql-server-ver17
- https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql?view=sql-server-ver17
- https://learn.microsoft.com/en-us/sql/relational-databases/tables/specify-computed-columns-in-a-table?view=sql-server-ver17