SQL Querying with Transact-SQL

This section provides comprehensive documentation on querying data using Transact-SQL (T-SQL) in Microsoft SQL Server.

The SELECT Statement

The SELECT statement is the fundamental command used to retrieve data from one or more tables in a database. It allows you to specify which columns and rows to return.

Syntax

SELECT [ALL | DISTINCT]
    <column_expression> [AS <alias>] [, ...]
FROM
    <table_source>
[WHERE
    <filter_condition>]
[GROUP BY
    <group_by_expression> [, ...]]
[HAVING
    <group_filter_condition>]
[ORDER BY
    <sort_expression> [ASC | DESC] [, ...]]
[OFFSET {<skip_rows>} ROWS
FETCH NEXT {<return_rows>} ROWS ONLY];

Key Components:

Example: Retrieving Product Names and Prices

SELECT
    ProductName,
    UnitPrice
FROM
    Production.Product
WHERE
    ListPrice > 50
ORDER BY
    ListPrice DESC;

Filtering Data with the WHERE Clause

The WHERE clause is used to extract only those records that fulfill specified criteria. You can use comparison operators, logical operators, and other conditions.

Common Operators:

Example: Finding Orders within a Date Range

SELECT
    SalesOrderID,
    OrderDate
FROM
    Sales.SalesOrderHeader
WHERE
    OrderDate BETWEEN '2023-01-01' AND '2023-03-31';

Example: Searching for Product Names starting with 'Ch'

SELECT
    ProductName
FROM
    Production.Product
WHERE
    ProductName LIKE 'Ch%';

Joining Tables

JOIN clauses are used to combine rows from two or more tables based on a related column between them. This is crucial for relational database querying.

Types of Joins:

Example: Listing Customer Names and their Orders

SELECT
    c.FirstName,
    c.LastName,
    soh.SalesOrderID,
    soh.OrderDate
FROM
    Sales.Customer AS c
INNER JOIN
    Sales.SalesOrderHeader AS soh ON c.CustomerID = soh.CustomerID
WHERE
    c.CustomerID = 123;

Aggregate Functions

Aggregate functions perform a calculation on a set of values and return a single value. They are often used with the GROUP BY clause.

Common Aggregate Functions:

Example: Counting Products and finding the Average Price per Category

SELECT
    pc.Name AS CategoryName,
    COUNT(p.ProductID) AS NumberOfProducts,
    AVG(p.ListPrice) AS AveragePrice
FROM
    Production.Product AS p
JOIN
    Production.ProductCategory AS pc ON p.ProductCategoryID = pc.ProductCategoryID
GROUP BY
    pc.Name
HAVING
    COUNT(p.ProductID) > 10
ORDER BY
    NumberOfProducts DESC;

Explore the links in the sidebar for more detailed information on specific T-SQL querying features.