SQL Server Documentation

Welcome to the comprehensive documentation for Microsoft SQL Server, a powerful relational database management system (RDBMS) used for a wide range of applications, from small business databases to large-scale enterprise solutions.

SQL Queries (T-SQL)

Transact-SQL (T-SQL) is Microsoft's proprietary extension to SQL used by SQL Server. It includes procedural programming, local variables, various support functions, and is used for everything from simple data retrieval to complex database administration tasks.

Basic SELECT Statements

The `SELECT` statement is used to query the database and retrieve data. You can specify which columns you want to retrieve and from which tables.

SELECT column1, column2
FROM table_name;

To select all columns from a table, use the asterisk (*):

SELECT *
FROM customers;

Filtering Data with WHERE Clause

The `WHERE` clause is used to filter records. It specifies conditions that must be met for records to be included in the result set.

SELECT product_name, price
FROM products
WHERE price > 50.00;

Note on Operators

Common operators used in the `WHERE` clause include: =, >, <, >=, <=, <> (or !=), LIKE, IN, BETWEEN, AND, OR.

Sorting Data with ORDER BY

The `ORDER BY` clause is used to sort the result set in ascending or descending order.

SELECT order_id, order_date
FROM orders
ORDER BY order_date DESC;

Joining Tables

SQL Server supports various types of joins to combine rows from two or more tables based on a related column.

SELECT customers.customer_name, orders.order_date
FROM customers
INNER JOIN orders ON customers.customer_id = orders.customer_id;

Performance Tip

Ensure that columns used in `JOIN` conditions are indexed for optimal query performance.

Aggregate Functions

Aggregate functions perform a calculation on a set of values and return a single value. Common functions include `COUNT`, `SUM`, `AVG`, `MIN`, and `MAX`.

SELECT COUNT(customer_id) AS total_customers
FROM customers;

SELECT AVG(price) AS average_product_price
FROM products;

Grouping Data with GROUP BY

The `GROUP BY` clause is used in conjunction with aggregate functions to group rows that have the same values in specified columns into summary rows.

SELECT city, COUNT(customer_id) AS number_of_customers
FROM customers
GROUP BY city
ORDER BY number_of_customers DESC;

Tip

Use the `HAVING` clause to filter groups based on a specified condition, similar to how `WHERE` filters individual rows.

This section provides a foundational understanding of T-SQL queries in SQL Server. For more advanced topics such as subqueries, common table expressions (CTEs), window functions, and data manipulation language (DML) statements (`INSERT`, `UPDATE`, `DELETE`), please refer to the detailed sections in the sidebar.