University

T-SQL Tutorial

Cogent Infotech
Blog
Location icon
Dallas, TX

T-SQL Tutorial

Transact-SQL, also known as T-SQL, is a powerful programming language used to manage and change data in relational databases. This tutorial will look at the basics of T-SQL and see how it differs from SQL - the most common language for managing databases.

SQL Vs. T-SQL

T-SQL is an important tool for managing big, complicated databases. From experienced developers to newbies, T-SQL has tools to help anyone get the most out of their data. The next few sections will highlight how to harness the power of T-SQL!

Getting Started with T-SQL

SQL, or Structured Query Language, is the language used to manage data in relational databases. T-SQL is based on SQL. Conversely, T-SQL goes further than SQL by adding features like variables, control flow statements, and stored procedures. The T-SQL syntax is similar to SQL. Hence, those who already know SQL will find it particularly easy to learn.

To make T-SQL work, one must connect to a SQL Server database. Once they have access, the user can use a database management tool to connect to the database. The SQL Server Management Studio is one such example. Here is a step-by-step walkthrough:

  1. User needs to open SQL Server Management Studio and click on "Connect" in the Object Explorer.
  2. In the Connect to Server dialogue box, they must select the appropriate server name and authentication method.
  3. Next, they need to click "Connect" to connect to the database.

Once the user is connected, they must run some basic T-SQL queries. Here's an example of a simple query:

SELECT * FROM Customers

This query retrieves all the rows and columns from the customer's table. As seen, the syntax of T-SQL is very similar to SQL, with the addition of the SELECT keyword.

Manipulating Data with T-SQL

The user, by now, is an expert at using T-SQL to get data out of a database! But it's time to move to the next step - how to change data. Here are some examples of T-SQL queries for adding, updating, and deleting data:

INSERT INTO Customers (FirstName, LastName, Email)

VALUES ("John", "Doe", 'johndoe@example.com')

This query adds a new row to the customer's table with the values "John", "Doe", and "johndoe@example.com" in the FirstName, LastName, and Email columns, respectively.

To update data in a table, the user needs to use the "UPDATE" statement.

UPDATE Customers

SET Email = 'newemail@example.com'

WHERE FirstName = 'John' AND LastName = 'Doe'

This query updates the email column for the row with FirstName "John" and LastName "Doe" to "newemail@example.com".

To delete data from a table, they have to use the DELETE statement.

DELETE FROM Customers

WHERE FirstName = "John" AND LastName = "Doe"

This query deletes the row with FirstName "John" and LastName "Doe" from the Customers table.

Working with Functions and Stored Procedures

T-SQL has different functions that can be used to change data and to calculate. Functions are pre-built pieces of code that take values as inputs, do something specific, and return a result.

The aggregate function is a much-used T-SQL function. Aggregate functions calculate on a set of values and return a single value. Some examples are as follows:

COUNT: Returns the number of rows in a table or the number of non-null values in a column.

SUM: Returns the sum of all the values in a column.

AVG: Returns the average of all the values in a column.

MAX: Returns the highest value in a column.

MIN: Returns the lowest value in a column.

Here's an example of using the COUNT function to retrieve the number of rows in a table:

SELECT COUNT(*) FROM Customers

This query returns the total number of rows in the Customers table.

Another commonly used function in T-SQL is the string function. String functions perform operations on strings, such as concatenation, trimming, and conversion. Here are some examples of string functions:

  • CONCAT: Concatenates two or more strings into one.
  • LEN: Returns the length of a string.
  • LOWER: Converts a string to lowercase.
  • UPPER: Converts a string to uppercase.

Here's an example of using the CONCAT function to concatenate two columns into one:

SELECT CONCAT (FirstName, " ", LastName) AS FullName FROM Customers

This query returns a new column called FullName, which is a concatenation of the FirstName and LastName columns.

Query Optimization

Query optimization is the process of making T-SQL queries work better by reducing the amount of time they take to run.

Index Optimization

Optimizing indexes is one of the best ways to make T-SQL queries run faster. Indexes speed up data retrieval by helping SQL Server easily find the rows matching a query. Users can use SQL Server's Database Engine Tuning Advisor to optimize indexes. This tool looks at how busy a database is and suggests changes to make it run faster.

Query Tuning

Query tuning is another way to speed up T-SQL queries. Query tuning looks at a query's execution plan to find performance issues and optimize the query to make it run faster. The execution plan shows how SQL Server runs a query. SQL Server Management Studio or the SQL Server Profiler tool can be used to see the execution plan.

There are many ways to improve the performance of queries. Here's a list of some of them:

  • Changing the way the query is written to make it work better.
  • Simplifying the query by taking out unnecessary joins or conditions.
  • Using the right index for the query to get the most out of indexes.
  • Forcing SQL Server to use a specific execution plan with query hints.
  • Splitting up large tables to improve performance.

Consider the following query:

SELECT * FROM Sales WHERE SaleDate >= '2022-01-01'

This query retrieves all the sales made after January 1st, 2022. If the sales table is very large, this query could take a long time to execute. To optimize this query, users can add an index to the SaleDate column and speed up data retrieval:

CREATE INDEX IX_Sales_SaleDate ON Sales(SaleDate)

With this index in place, the query should execute much faster.

Advanced Topics in T-SQL

Transactions

A transaction in T-SQL is a unit of work done on a database. Transactions help combine several database operations into a single, atomic one. This means that either all the operations in a transaction are done correctly, or none are done at all. The consistency and integrity of data in a database depend upon the transactions.

BEGIN TRANSACTION:

UPDATE Customers

SET Email = "newemail@example.com"

WHERE FirstName = "John" AND LastName = "Doe";

INSERT INTO Orders (CustomerId, OrderDate)

VALUES (1, GETDATE());

COMMIT TRANSACTION;

Here, users can start a new transaction using the BEGIN TRANSACTION statement. They can then perform two operations within the transaction. The first is to update the email address of a customer. And the second adds a new order to the Orders table. Finally, the user commits the transaction using the COMMIT TRANSACTION statement.

If an error occurs, the user can roll  the entire transaction back using the ROLLBACK TRANSACTION statement.

Triggers

In T-SQL, a trigger is a special stored procedure executed automatically when a specific event occurs in the database. Triggers can be used to enforce business rules, perform complex data validations, and audit changes made to a database.

Here's an example of how to create a trigger in T-SQL:

CREATE TRIGGER [dbo].[UpdateOrderTotal]

ON [dbo].[OrderItems]

AFTER "INSERT," "UPDATE," DELETE

AS

BEGIN

UPDATE Orders

SET Total = (SELECT SUM(Quantity * Price) FROM OrderItems WHERE OrderId = Orders.Id)

WHERE Id IN (SELECT DISTINCT OrderId FROM inserted);66666666666666666666666666666666666666666666666666666666666666666666666666666666666

Here, users are creating a trigger called UpdateOrderTotal executed after an insert, update, or delete operation is performed on the OrderItems table. The trigger updates the Total column of the Orders table. This update takes place based on the sum of the quantity and price of all order items.

Cursors

In T-SQL, a cursor is a database object that allows users to traverse through the rows of a result set one by one. Cursors are often used when users need to perform complex data manipulations that cannot be accomplished with a single query.

Here's an example of how to use a cursor in T-SQL:

DECLARE @CustomerId INT;

DECLARE @Total DECIMAL(18,2);

DECLARE curOrders CURSOR FOR

SELECT Id, Total FROM Orders WHERE CustomerId = 1;

OPEN curOrders;

FETCH NEXT FROM curOrders INTO @CustomerId, @Total;

WHILE @@FETCH_STATUS = 0

BEGIN

PRINT "Order Id: " + CAST(@CustomerId AS VARCHAR(10)) + , "Total: " + CAST(@Total AS VARCHAR(10));

FETCH NEXT FROM curOrders INTO @CustomerId, @Total;

END;

CLOSE curOrders;

DEALLOCATE curOrders;

In this example, the user makes a cursor called curOrders that pulls the Id and Total columns from the Orders table for a specific customer. Then, the user moves the cursor to the first row, opens the cursor, and writes the order ID and total to the console.

They keep getting the next row until there are no more rows left. At this point, users can close the cursor and give it to someone else.

Conclusion

T-SQL's features make it a powerful set of tools for optimizing queries and making useful functions and stored procedures. Further, it introduces users to advanced, yet efficient features like transactions, triggers, and cursors.

Cogent University is committed to empowering professionals with the right skills and knowledge and kickstart their career in tech. Our bootcamps are accessible to individuals eager to upskill and accelerate their career at zero upfront cost.

Read more such informative articles from our resources and visit Cogent University to know more about our bootcamps.

No items found.

COGENT / RESOURCES

Real-World Journeys

Learn about what we do, who our clients are, and how we create future-ready businesses.
Blog
SQL Data Types
Various types of data can be stored in an object, such as integer data, monetary data, character data, date and time data, and binary strings. Read more here.
Arrow
Blog
Architecture of MySQL
Explore MySQL architecture & client-level query results
Arrow
Blog
Features of MySQL
Open sesame! MySQL powers innovation, while others charge for keys. Explore open-source freedom
Arrow

Download Resource

Enter your email to download your requested file.
Thank you! Your submission has been received! Please click on the button below to download the file.
Download
Oops! Something went wrong while submitting the form. Please enter a valid email.