An index in SQL Server is a database object that improves the speed of data retrieval operations.
It works like a book index, allowing faster lookups based on indexed columns.
Types of indexes:
1. Clustered Index: Determines the physical order of data in a table (one per table).
2. Non-Clustered Index: Creates a separate structure from the data and stores pointers to actual data.
3. Unique Index: Ensures that all values in an indexed column are unique.
4. Filtered Index: Indexes a subset of data based on a filter condition.
5. Full-Text Index: Used for complex text-based queries.
INNER JOIN: Returns only the matching records from both tables based on the join condition.
OUTER JOIN: Returns matching records as well as unmatched records.
WHERE: Used to filter records before grouping (applies to individual rows).
HAVING: Used to filter records after grouping (applies to aggregated data).
Example:
SELECT department, COUNT(*) AS employee_count FROM Employees GROUP BY department HAVING COUNT(*) > 5;
A Common Table Expression (CTE) is a temporary result set that can be referenced within a SELECT, INSERT, UPDATE, or DELETE statement.
Example:
WITH EmployeeCount AS ( SELECT department, COUNT(*) AS emp_count FROM Employees GROUP BY department ) SELECT * FROM EmployeeCount WHERE emp_count > 5;
Temporary Table (#TempTable): Stored in the tempdb database and can have indexes. They can be used in multiple stored procedures or batches.
Table Variable (@TableVar): Stored in memory, does not support indexes (except primary keys), and is scoped to a batch or stored procedure.
Example:
DECLARE @TempTable TABLE (ID INT, Name VARCHAR(50)); INSERT INTO @TempTable VALUES (1, 'John'), (2, 'Jane'); SELECT * FROM @TempTable;
Copyrights © 2024 letsupdateskills All rights reserved