Introduction to T-SQL
Structured Query Language (SQL) is a powerful tool for managing and querying relational databases. Transact-SQL (T-SQL) is an extension of SQL that is specific to Microsoft SQL Server. In this tutorial, we’ll cover the fundamentals of T-SQL, including basic syntax and common operations, with plenty of code examples to help you grasp the concepts.
Prerequisites
Before diving into T-SQL, make sure you have:
- Access to Microsoft SQL Server or SQL Server Management Studio (SSMS).
- Basic understanding of relational databases and SQL concepts.
1. Getting Started
Let’s begin by understanding how to connect to a SQL Server instance using SSMS. Open SSMS and connect to your SQL Server instance.
-- Connect to SQL Server instance
USE master;
GO
2. Creating a Database
To start working with T-SQL, you need a database. Let’s create one named “TutorialDB.”
-- Create a new database
CREATE DATABASE TutorialDB;
GO
-- Switch to the newly created database
USE TutorialDB;
GO
3. Creating Tables
Tables are used to store data in a relational database. Let’s create a simple table named “Employees.”
-- Create Employees table
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
Department NVARCHAR(50),
Salary DECIMAL(10, 2)
);
4. Inserting Data
Now, let’s insert some sample data into the “Employees” table.
-- Insert data into Employees table
INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Salary)
VALUES (1, 'John', 'Doe', 'IT', 50000),
(2, 'Jane', 'Smith', 'HR', 60000),
(3, 'David', 'Brown', 'Finance', 70000);
5. Querying Data
T-SQL provides powerful querying capabilities. Let’s retrieve all records from the “Employees” table.
-- Retrieve all records from Employees table
SELECT * FROM Employees;
6. Filtering Data
You can filter data using the WHERE clause. Let’s retrieve employees from the HR department.
-- Retrieve employees from HR department
SELECT * FROM Employees WHERE Department = 'HR';
7. Updating Data
To update existing records, use the UPDATE statement. Let’s increase the salary of employees in the Finance department.
-- Increase salary of employees in Finance department
UPDATE Employees SET Salary = Salary * 1.1 WHERE Department = 'Finance';
8. Deleting Data
Use the DELETE statement to remove records from a table. Let’s delete an employee from the “Employees” table.
-- Delete employee with EmployeeID 3
DELETE FROM Employees WHERE EmployeeID = 3;
Conclusion
Congratulations! You’ve now learned the basics of T-SQL. This tutorial covered essential concepts such as creating databases, tables, inserting, querying, updating, and deleting data. Keep practicing and exploring more advanced T-SQL features to become proficient in managing SQL Server databases.