T - SQL Course Content
T - SQL Course Content
T-SQL, or Transact-SQL, is the proprietary language used to interact with Microsoft SQL Server
databases. It's a powerful tool that combines the declarative nature of SQL with procedural
programming elements, allowing you to perform a wide range of tasks, from simple data retrieval to
complex database administration.
CREATE - statement used to start create new objects like: database, table, view, index, temporary
table, trigger, function or procedure.
ALTER - statement used to modify table name or table columns(add, drop, rename), view, trigger.
Data Manipulation Language (DML) affect the information stored in the database.
Use DML statements to insert, update, and delete the rows in the database.
MERGE - insert, update, or delete records on a table from the results of a join.
BULK INSERT - imports records from a data file into a database table or view
Data Control Language (DCL) - permissions statements control which users and logins can access
data and perform operations.
Transaction Control Language (TCL) commands are used to manage transactions in the database.
Len - returns the number of characters from a string expression, excluding trailing spaces.
Patindex - returns the starting position of the first occurrence of a pattern in a specified expression.
DATEDIFF - returns the difference between the specified startdate and enddate.
DATEFROMPARTS - returns a date value for the specified year, month or day.
DATENAME - returns a string that represents the specified datepart of the specified date.
DATEPART - returns an integer that represents the specified datepart of the specified date.
DATETIMEFROMPARTS - returns a datetime value for the specified date and time arguments.
DATETIME2FROMPARTS - returns a datetime2 value for the specified date and time arguments.
DAY - returns from a date an integer that represents the day of the month.
MONTH - returns an int value that represents the month of the specified date.
SMALLDATETIMEFROMPARTS - returns a smalldatetime value for the specified date and time.
SWITCHOFFSET - returns a datetimeoffset value that is changed from the stored time zone offset.
SYSDATETIME - returns a datetime2(7) value that contains the date and time of the computer on
which the instance of SQL Server is running.
SYSDATETIMEOFFSET - Returns a datetimeoffset(7) value that contains the date and time of the
computer on which the instance of SQL Server is running.
SYSUTCDATETIME - the date and time is returned as UTC time (Coordinated Universal Time).
TIMEFROMPARTS - returns a time value for the specified time and with the specified precision.
YEAR - returns an int value that represents the year of the specified date
@@ERROR - returns the error number for the last Transact-SQL statement executed.
ERROR_PROCEDURE - returns the name of the stored procedure or trigger where an error occurs.
ERROR_SEVERITY - returns the severity value of the error where an error occurs.
ORIGINAL_LOGIN - returns the name of the login that connected to the instance of SQL Server.
SESSION_USER - returns the user name of the current session in the current database.
@@LOCK_TIMEOUT - returns the current lock time-out setting in milliseconds for the current
session.
@@SERVICENAME - returns the name of the registry key under which SQL Server is running.
PARSE - returns the result of an expression, translated to the requested data type in SQL Server.
TRY_CAST - returns a value cast to the specified data type if the cast succeeds.
TRY_CONVERT - returns a value cast to the specified data type if the cast succeeds.
TRY_PARSE - is used for converting expressions from string to date/time and number types.
ROW_NUMBER - its primary purpose is to serialize the rows of the result set in the partitioned order
provided by the OVER clause.
RANK - returns the rank of a value in a given list. The rank of a value is its position in the list, with the
first value having a rank of 1.
T- SQL OPERATORS
SQL Server supports several types of operators that can be used to filter or manipulate data in a
database:
Relational operators: These operators are used to compare values in a database and return a
Boolean value (true or false) based on the outcome of the comparison. Examples of relational
operators include = (equal to), > (greater than), and <> (not equal to).
Compound operators: These operators combine multiple conditions to filter data in a database. The
most common compound operator is the AND operator, which returns only rows that meet both
conditions. The OR operator returns rows that meet either condition.
Logical operators: These operators are used to test the truth of a statement or expression. The most
common logical operators are NOT, AND, and OR. NOT negates the value of the statement or
expression, AND returns true if both statements are true, and OR returns true if either statement is
true.
Other operators: include IS NULL, IN, BETWEEN, LIKE, EXISTS, CROSS APPLY, EXCEPT, INTERSECT, etc.
Logical Operators - all, and, any, between, exists, in, like, not, or, some.
The Transact SQL language allow you to use various data types like: Numeric (int, numeric, decimal,
float), Character Strings (char, varchar), Unicode Character Strings (nchar, nvarchar) , Date (date,
datetime, datetime2, time) and other data types.
Binary Strings
Character Strings
Datetimeoffset - defines a date with a time of a day that has time zone awareness.
Numerics
Int - the primary integer data type in SQL Server, has 4 bytes storage.
Decimal - defines a numeric data type with fixed precision and scale numbers.
Cursor - defines an cursor data type for variables or stored procedure OUTPUT parameters.
One of the most important features of SQL Server is its ability to execute queries and subqueries to
retrieve data from the database. In this article, we will discuss SQL Server queries and subqueries in
detail.
A SQL Select Query is used to return records from the SQL Server database. Using select queries you
can populate variables, cursors, tables, views.
Queries
A query in SQL Server is a request for data from one or more tables or views in the database. SQL
Server uses the Structured Query Language (SQL) to execute queries. SQL Server queries can be
simple or complex, depending on the requirements of the user. A simple query can retrieve data
from a single table, while a complex query can retrieve data from multiple tables and perform
advanced operations such as sorting, filtering, and grouping.
GROUP BY
The T-SQL GROUP BY is used when an aggregate function exists in the select query.
GROUP BY r.course_id
HAVING
The T-SQL HAVING specifies a search condition for a group or an aggregate function.
WHERE c.id=r.course_id
GROUP BY r.course_id
ORDER BY
WHERE c.id=r.course_id
GROUP BY r.course_id
WHERE
The T-SQL WHERE specifies a search condition for the rows returned by the select query.
BETWEEN
The T-SQL BETWEEN returns rows if the value is within the range of comparisons.
LIKE
Subqueries
A subquery in SQL Server is a query that is nested inside another query. The subquery can be used to
retrieve data that will be used as input for the outer query. The outer query can be a SELECT,
UPDATE, or DELETE statement. Subqueries are useful when you need to retrieve data from multiple
tables and combine the results into a single result set. Subqueries can also be used to perform
calculations or aggregate functions on data before it is used in the outer query.
EXISTS
The T-SQL EXISTS return rows if a SQL subquery contains any rows.
IN
The T-SQL IN returns rows if a specified value matches any value in a SQL subquery.
SOME
The T-SQL SOME compares a value with a single column set of values.
ANY
The T-SQL ANY returns rows if any value is equal to one value in a subquery.
SQL Server queries and subqueries are powerful tools for retrieving data from a database. SQL Server
subqueries can be used to retrieve data from multiple tables and perform advanced operations on
the data before it is used in the outer query. By mastering SQL Server queries and subqueries, you
can become an expert in data analysis and reporting
This article provides an introduction to what T-SQL joins are and how to use them in the SQL Server
database.
T-SQL Joins are used to return records from two or more tables in a SQL Server database.
A SQL join consists of a query that uses multiple tables. SQL Server query uses clauses, subqueries,
expressions, operators and CTEs.
Inner Join
The T-SQL Inner Join returns rows from two tables when a match is found.
Left Join
The T-SQL Left Join returns all rows from the left table, even if there are no matches with the right
table.
ON a.column1 = b.column1
ORDER BY a.column1;
Right Join
The T-SQL Right Join returns all rows from the right table, even if there are no matches with the left
table.
ON a.column1 = b.column1
ORDER BY a.column1;
Self Join
ON a.column1 = b.column1
ORDER BY a.column1;
This article provides an introduction to what T-SQL joins are and how to use them in the SQL Server
database.
T-SQL Joins are used to return records from two or more tables in a SQL Server database.
A SQL join consists of a query that uses multiple tables. SQL Server query uses clauses, subqueries,
expressions, operators and CTEs.
Inner Join
The T-SQL Inner Join returns rows from two tables when a match is found.
Left Join
The T-SQL Left Join returns all rows from the left table, even if there are no matches with the right
table.
ON a.column1 = b.column1
ORDER BY a.column1;
Right Join
The T-SQL Right Join returns all rows from the right table, even if there are no matches with the left
table.
ON a.column1 = b.column1
ORDER BY a.column1;
Self Join
ON a.column1 = b.column1
ORDER BY a.column1;
Cross Join
The T-SQL Cross Join, also known as a Cartesian product, returns the combination of every row from
the first table with every row from the second table. It is used to combine every row from one table
with every row from another table, resulting in a much larger table with a number of rows equal to
the product of the number of rows in each table.
SELECT *
FROM table_A
T-SQL Control-of-Flow
This article describes how to use the T-SQL Control-of-Flow in SQL Server database. To control the
order of execution in SQL Server in sequential order, it has several control of flow keywords. These
keywords are known as Control-of-flow language. Following are the 10 main SQL Server Control-of-
flow keywords: BEGIN...END, BREAK, CONTINUE, GOTO label, IF...ELSE, RETURN, THROW, TRY...CATCH,
WAITFOR, WHILE.
1. BEGIN...END
The control-of-flow BEGIN...END keyword groups Transact SQL statements in a block to execute.
BEGIN
{ sql_statement | statement_block }
END
2. BREAK
Use BREAK keyword as an exit statement. If BREAK is inserted into an WHILE loop, once the BREAK
statement is executed, it exits the current loop and executes the further statements.
BREAK
Example
In the following example, we will show how to use the BREAK keyword to exit a WHILE statement.
First, declare and set the variable @num = 1. This variable is incremented by the value 1 as long as
the WHILE statement is run. To exit the WHILE statement, I set the condition that @num > 2. When
running the script, the Example for SQL Server message will be displayed twice.
3. CONTINUE
The main functionality of CONTINUE is to restart a WHILE LOOP by ignoring the statements after the
CONTINUE keyword.
CONTINUE
Example
The example below shows how to use the CONTINUE keyword to continue running a WHILE
statement. The WHILE statement is set to run from 0 to 4, with the help of the @num variable that is
incremented by 1 as long as the conditions in the WHILE block are met. If the variable @num will
have the value 3, then exit WHILE using BREAK, otherwise, using the CONTINUE keyword, WHILE will
continue running. At the end of WHILE's run, the message Example of T-SQL loops will be displayed
three times.
4. GOTO label
GOTO in SQL Server defines a label and it allows the code to jump onto that label from one section to
another.
label:
GOTO label
Example
The example below shows how to use the GOTO statement in SQL Server. In the BEGIN...END block I
declared two labels Test_1 and Test_2 that represent some access points if the given conditions are
met. After reaching the first point labeled Test_1, go directly to the point labeled Test_3, skipping the
point labeled Test_2
5. IF...ELSE
IF-ELSE control flow statement executes a set of blocks in a way that if the condition mentioned in
the IF parameter is True, the IF block executes, if it is False, then the ELSE block is executed.
IF Boolean_expression
{ sql_statement | statement_block }
This article describes how to use the T-SQL Control-of-Flow in SQL Server database. To control the
order of execution in SQL Server in sequential order, it has several control of flow keywords. These
keywords are known as Control-of-flow language. Following are the 10 main SQL Server Control-of-
flow keywords: BEGIN...END, BREAK, CONTINUE, GOTO label, IF...ELSE, RETURN, THROW, TRY...CATCH,
WAITFOR, WHILE.
1. BEGIN...END
The control-of-flow BEGIN...END keyword groups Transact SQL statements in a block to execute.
{ sql_statement | statement_block }
END
2. BREAK
Use BREAK keyword as an exit statement. If BREAK is inserted into an WHILE loop, once the BREAK
statement is executed, it exits the current loop and executes the further statements.
BREAK
Example
In the following example, we will show how to use the BREAK keyword to exit a WHILE statement.
First, declare and set the variable @num = 1. This variable is incremented by the value 1 as long as
the WHILE statement is run. To exit the WHILE statement, I set the condition that @num > 2. When
running the script, the Example for SQL Server message will be displayed twice.
3. CONTINUE
The main functionality of CONTINUE is to restart a WHILE LOOP by ignoring the statements after the
CONTINUE keyword.
CONTINUE
Example
The example below shows how to use the CONTINUE keyword to continue running a WHILE
statement. The WHILE statement is set to run from 0 to 4, with the help of the @num variable that is
incremented by 1 as long as the conditions in the WHILE block are met. If the variable @num will
have the value 3, then exit WHILE using BREAK, otherwise, using the CONTINUE keyword, WHILE will
continue running. At the end of WHILE's run, the message Example of T-SQL loops will be displayed
three times.
USE model
GO
BEGIN
IF @num = 3
BREAK
ELSE
CONTINUE
END;
GO
4. GOTO label
GOTO in SQL Server defines a label and it allows the code to jump onto that label from one section to
another.
label:
GOTO label
Example
The example below shows how to use the GOTO statement in SQL Server. In the BEGIN...END block I
declared two labels Test_1 and Test_2 that represent some access points if the given conditions are
met. After reaching the first point labeled Test_1, go directly to the point labeled Test_3, skipping the
point labeled Test_2.
5. IF...ELSE
IF-ELSE control flow statement executes a set of blocks in a way that if the condition mentioned in
the IF parameter is True, the IF block executes, if it is False, then the ELSE block is executed.
IF Boolean_expression
{ sql_statement | statement_block }
[ ELSE
{ sql_statement | statement_block } ]
Example
The IF EXISTS condition checks if the select returns a record and if yes then displays YES, otherwise
displays NO.
6. RETURN
RETURN keyword exits the query or procedure unconditionally. It can also be used as an exit
statement as statements after RETURN are not executed further.
RETURN [ integer_expression ]
Example
In the example below we have two inserts in the students table, between these two inserts is the T-
SQL RETURN statement. The first insert will be inserted in the students table so that the RETURN
statement ends the running of the BEGIN...END block. If we comment the SQL Server RETURN
statement, then both rows will be inserted in the students table
7. THROW
THROW raise an exception and if a CATCH block is available, it allows the CATCH block to execute
further.
THROW
Example
In the following example, we will show how to use the THROW statement to handle possible errors
that may occur in a SQL Server block. The first step is to create a table with a single column that
contains the primary key constraint. The second step is to write the BEGIN TRY...END TRY block that
contains the inserts in the created table, the first two inserts are unique, the third is a duplicate
insert, and the last insert is unique. The third step, the BEGIN CATCH...END CATCH block catches and
displays the error generated by the duplicate insert. The last step is to run the script that will produce
the following result: the first two lines will be inserted, then the error Error in try catch block will be
displayed
8. TRY...CATCH
TRY...CATCH block is used for error handling in T-SQL. If an error is encountered in the TRY block, the
control is given to the CATCH block to handle the error.
{ sql_statement | statement_block }
END TRY
BEGIN CATCH
[ { sql_statement | statement_block } ]
END CATCH;
Example
The example below shows how to use the TRY...CATCH to handle errors in SQL Server. The select
written in the BEGIN TRY...END TRY block generates the error, and with the help of the BEGIN
CATCH...END CATCH block the error is caught. The error number is extracted and set in the declared
variable @ErrorNumber. It is also useful to extract the error message that we set in the
@ErrorMessage variable. To extract the error number and message, I used the SQL Server system
functions ERROR_NUMBER and ERROR_MESSAGE.
9. WAITFOR
The execution of statements is paused for a specific time or interval if the WAITFOR keyword is
stated.
WAITFOR
DELAY 'time_to_pass'
| TIME 'time_to_execute'
| [ ( receive_statement ) | ( get_conversation_group_statement ) ]
[ , TIMEOUT timeout ]
Example
In the following example, we will use WAITFOR TIME to insert a new record in the students table at a
time specified by the user. The example also contains WAITFOR DELAY to delay the second insert in
the students table. WAITFOR statement can also be used to execute functions or procedures at a
given time
10. WHILE
The statements mentioned in the WHILE block are executed only if the condition mentioned in the
WHILE parameter turns True. If it is False, the WHILE block doesn't execute further
WHILE Boolean_expression
{ sql_statement | statement_block | BREAK | CONTINUE }
Example
The example uses an @count variable initially set with the value 1. Then it runs the WHILE statement
as long as the value in @count is less than or equal to 5. Inside the BEGIN...END block, the @count
variable is incremented by the value 1 to avoid the infinite running of the WHILE statement. When
@count becomes greater than 5, the WHILE statement stops. When running the script, the While in
SQL Server message will be displayed five times.
T-SQL stored procedures are objects created in the SQL Server database and consist of SQL
statements. Stored procedures remain saved in the SQL Server database for calling or executed
whenever needed.
T-SQL stored procedures are mostly used because they can be reused to save time
Improved security for database objects. Controls what database activities are performed.
Improved performance. The first time the procedure is executed it compiles and creates an execution
plan which is reused for subsequent executions so that the processing of the procedure takes less
time.
Create Procedure
AS
SQL statement
GO;
Alter Procedure
The T-SQL statement Alter Procedure is used to modifies stored procedures.
AS
SQL statement
GO;
Create Function
RETURNS data_type AS
BEGIN
SQL statement
RETURN value
END;
GO;
GO;
The T-SQL command DROP PROCEDURE is used to drop or delete the stored procedures.
GO;
GO;
SQL Server System Stored Procedures are predefined procedures that are included in the SQL Server
database management system. These procedures are stored in the master database and are used for
performing various administrative tasks, such as configuring server settings, managing database
objects, and monitoring server performance.
Some of the most commonly used System Stored Procedures in SQL Server include:
Sp_special_columns - Returns the optimal set of columns that uniquely identify a row in the table.
Sp_configure - Displays or changes global configuration settings for the current server.
Sp_databases - Shows all databases name and size for an instance of the SQL Server.
Sp_execute - Executes a prepared Transact-SQL statement using a specified handle and optional
parameter value.
Sp_prepare - Prepares a parameterized Transact-SQL statement and returns a statement handle for
execution.
Sp_helptrigger - Returns the type or types of DML triggers defined on the specified table.
Sp_server_info - Returns a list of attribute names and matching values for SQL Server.
Sp_unprepare - Discards the execution plan created by the sp_prepare stored procedure.
Sp_updatestats - Runs UPDATE STATISTICS against all user-defined and internal tables in the current
database.
Sp_who - Returns information about current users, sessions, and processes in an instance of the SQL
Server.
System Stored Procedures can be executed using SQL Server Management Studio or any other tool
that supports SQL Server. They are an essential tool for managing and maintaining SQL Server
databases, and can help simplify and automate common administrative tasks
T-SQL Triggers
In this article we will learn how to use triggers in the Transact SQL server. A trigger is an object
created in the database that is automatically triggered when an event occurs. Events such as: insert,
update, delete.
The triggers are of several types: DML triggers, DDL triggers, LOGON triggers.
The most commonly used trigger is the DML type, and is created when using CREATE TRIGGER,
followed by the syntax ON {table_name | view_name} FOR INSERT, UPDATE, DELETE.
The ALTER TRIGGER syntax is used to modify the SQL statement inside a trigger.
The DROP TRIGGER syntax is used to delete a trigger from the database.
The T-SQL statement Create Trigger is used to create triggers: DML, DDL, Logon.
Create Trigger
The T-SQL statement Create Trigger is used to create triggers: DML, DDL, Logon.
DML Trigger
ON { table_name | view_name }
AS { SQL statement [ ; ] }
GO
DDL Trigger
{ FOR | AFTER }
AS { SQL statement [ ; ] }
GO
Logon Trigger
ON ALL SERVER
{ FOR| AFTER }
LOGON
AS { SQL statement [ ; ] }
GO
Alter Trigger
The Alter Trigger command is used to modify triggers: DML, DDL, Logon.
ON { table_name | view_name }
AS { SQL statement [ ; ] }
Go
Drop Trigger
To drop or delete a trigger uses the syntax Drop Trigger. The syntax is used for all types of triggers.
GO
Enable Trigger
To enable a trigger uses the syntax Enable Trigger. The syntax is used to enable one or all triggers.
ENABLE TRIGGER trigger_name ON table_name;
Disable Trigger
To disable a trigger uses the syntax Disable Trigger. The syntax is used to disable one or all triggers.
T-SQL Views
A T-SQL view is a virtual table and is created by a select composed of one or more tables.
Types of Views
Create View
AS
SQL statement
GO
Alter View
AS
SQL statement
GO
You can modify view records using the insert, update or delete commands.
Rename View
Drop View
Cursors – T SQL
In this section you can learn how to work with cursors using operations like declare cursor, create
procedure, fetch, delete, update, close, set, deallocate. To create a cursor, use the CURSOR DECLARE
syntax. When you declare a cursor, it is loaded with records, in order to access the records of the
cursor it must be opened using OPEN and the rows are returned using FETCH.
Declare cursor
The T-SQL statement DECLARE CURSOR is used to create and declare cursors. In the declarative part,
the cursor is created and loaded with values.
FOR sql_statement
Open cursor
The FETCH cursor statement retrieves records from a Transact-SQL server cursor.
Close cursor
The CLOSE cursor statement closes an open cursor by releasing the current result set. CLOSE leaves
the records available in cursor and allows the cursor to be reopened.
Deallocate cursor
Cursor exampleIn the example below, we will create a cursor by going through all the steps that make
up the cursor.
In the declarative part we will DECLARE and load the cursor with records and we will also declare
variables to use them to display the information.
Once the cursor is created, we will open it using the OPEN statement, then process the cursor using
the FETCH statement and load variables with values.
CLOSE statement is used to close the cursor, then if it no longer needs to be opened it is destroyed
with DEALLOCATEstatement
Cursor operations
This article describes the basics of backup and restore a SQL Server database.
T-SQL statements allow to back up and restore your SQL SERVER database.
Also, you can export and import security certificates and keys.
BACKUP DATABASE
The T-SQL statement BACKUP DATABASE is used to backup entire database to disk file.
USE model;
GO
TO DISK = 'E:\SQLServerBackup\model.bak'
WITH FORMAT,
MEDIANAME = 'SQLServerBackup',
GO
PARTIAL BACKUPS
The T-SQL statement BACKUP DATABASE READ_WRITE_FILEGROUPS is used to backup partial backup
to disk file.
USE model;
GO
TO DISK = 'E:\SQLServerBackup\model_partial.bak'
GO
The T-SQL statement RESTORE DATABASE is used to restore a SQL Server database.
USE model;
GO
GO
USE model;
GO
TO DISK = 'E:\SQLServerBackup\model_1.bak'
WITH DIFFERENTIAL;
GO
GO
A T-SQL transaction is a single logical unit of work and it is composed of several SQL Server
statements. The transaction begins with the first SQL Server statement executed and ends when the
transaction is saved or rolled back.
The T-SQL statement BEGIN DISTRIBUTED TRANSACTION specifies the start of a distributed
transaction.
[ transaction_name | @transaction_name_variable ] ;
BEGIN Transaction
The T-SQL statement BEGIN TRANSACTION specifies the start of a local transaction.
COMMIT TRANSACTION
The T-SQL statement COMMIT TRANSACTION specifies the end of a successful transaction.
The T-SQL statement ROLLBACK TRANSACTION rollback a transaction to the start of the transaction,
or to a savepoint inside the transaction.
ROLLBACK Work
The T-SQL statement ROLLBACK WORK specifies the rollback of a user specified transaction.
ROLLBACK WORK;
SAVE Transaction
The T-SQL statement SAVE TRANSACTION is used to create a savepoint within a transaction.
Constraints T-SQL
In the Constraints sections you can learn how to create a SQL Primary Key Constraint or add a Foreign
Key to a table. Also you can learn how to use SQL Server commands to enable or disable keys. The
SQL Server constraints are Primary Key, Foreign Key, UNIQUE, CHECK and NOT NULL
The columns of the primary key contain unique values that identify each row in a table.
The maximum number of columns allowed to compose a primary key is 16 columns and a total key
length of 900 bytes.
A FOREIGN KEY is a constraint is a relationship between two tables and used to enforce data
integrity. Foreign Key constraints can reference only tables within the same database on the same
server.
UNIQUE Constraints
UNIQUE constraints are used to prevent duplicate values from being inserted into specific columns in
a table.
CHECK Constraints
CHECK constraints specify the data values that are allowed in one or more columns.
This article describes how to use the T-SQL Expressions in SQL Server database. We will discuss in
detail the three main types of SQL Server expressions namely CASE, COALESCE and NULLIF.
Types of Expressions
CASE
COALESCE
NULLIF
The CASE statement in SQL Server returns a specific output of value based on the condition specified
by the user. The SQL Server CASE statement has at least one pair of WHEN-THEN statements.
The WHEN statement consists of the condition to be applied to the table and tested, and the THEN
statement return the input expression once the WHEN statement returns TRUE. This also has an ELSE
statement, but it is optional. The ELSE statement has the activity to be done once any of the WHEN
statements don't return TRUE. Finally, the case statement ends with the END keyword
ELSE else_result_expression
END AS column_name
FROM Table_name
In SQL Server you can use the CASE statement in WHERE clause.
COALESCE expression in SQL Server has string manipulations. The method of obtaining another form
using the existing data is called String Manipulation.
COALESCE expression will return the data type which has the highest precedence data type. If the
entered expressions are nullable, the output will also be nullable
First, check the integer, consisting of a character expression after the integer, which will give an
integer as an output
NULLIF expression in SQL Server returns a NULL value when the given two parameters are identical,
and if it is not identical, it will return the value of the first parameter.
NULLIF(expression_1, expression_2)
T-SQL Subquery
What is a Subquery
A SQL Subquery(also called an inner query or inner select) is a sql query that is nested inside a
statement(SELECT, INSERT, UPDATE, or DELETE), or inside another subquery.
Subquery basics
The statements that include a SQL Subquery usually use logical operators(in, exists, all, any or
some):
A subquery in SQL Server database comes with the following restrictions that must be followed for
a successful addition to the outer query.
Only one expression or column name can be added to the list of a subquery introduced with a
comparison operator.
When the WHERE clause of a larger query consists of a column name, it shall be join-compatible with
the subquery select list column.
The select list 0 of subqueries does not accommodate the kinds of text, image, and text data.
The subquery that an untainted comparison operator adds cannot have clauses of GROUP BY or
HAVING. The reason is that they must give back a single value.
To those subqueries that include GROUP BY, the DISTINCT keyword cannot be added.
The clauses COMPUTE and INTO clauses cannot be defined.
Subquery examples
IN
The IN operator verify that the value in a specified column matches any value in a subquery or list.
ANY
The ANY operator compares a scalar value with a single-column set of values.
SOME
EXISTS
The Transact-SQL EXISTS operator specifies a subquery to check for the existence of rows.
NOT EXISTS
The Transact-SQL NOT EXISTS operator specifies a subquery to check for the not existence of rows.
Correlated Subquery
In SQL Server, a correlated subquery is a type of subquery that refers to a column from the outer
query, and as a result, the subquery's results are dependent on the values in the outer query. This
type of subquery is also known as a dependent subquery.
A correlated subquery is typically used to retrieve data from one or more related tables based on the
data in the current row being processed in the outer query. It allows for more complex queries to be
performed, and can be particularly useful when dealing with large datasets
T-SQL Variables - Declare and Set variable
One of the key features of SQL Server that helps in managing and manipulating data efficiently is the
use of variables. Variables in SQL Server are used to store data temporarily during the execution of
code. They are essential in writing reusable, readable, and modular code. By using variables,
developers can write more flexible and dynamic SQL queries, enhancing the capability to handle data
dynamically during runtime. Understanding how to declare, initialize, and manipulate variables is
fundamental for anyone looking to master SQL Server programming.
In SQL Server, variables are used to store and manipulate data within a T-SQL script or a stored
procedure. Variables provide a way to store temporary values that can be used in various parts of a
script or procedure. They can hold different data types, such as integers, strings, dates, or other SQL
Server data types.
1. What is a Variable?
A Transact-SQL local variable is an database object that can store a single data value of a specific
type. Variables are particularly useful for temporarily storing data, which can be manipulated or
transferred as needed within batches, stored procedures, or scripts.
The following are the two main types of SQL Server variables:
Local variables. They are declared by the user and start with the '@' symbol. Local variables can be
used within a procedure or batch. The scope of a local variable is limited to the batch or stored
procedure in which it is declared. Once the batch or procedure ends, the variable is de-allocated and
ceases to exist.
Global variables. They are declared by the system beforehand and start with the '@@' symbol.
Global variables can store session information. As these are system-defined, their lifecycle and scope
are managed by SQL Server itself, and they persist across different batches and sessions.
To declare a variable uses the keyword DECLARE, assign a variable name and a data type. The
DECLARE statement of Transact-SQL will declare a variable as per the instruction given by the user.
A data type and length should be assigned. The most used date types are: INT, DATE, VARCHAR.
5. SELECT a Variable
The SELECT statement can be used to select the assigned values by certain criteria as per the
requirement of the user. Syntax for the SELECT statement of one variable or multiple variables:
7. Conclusion
Variables are a fundamental aspect of SQL Server programming, enabling developers to write more
efficient, dynamic, and readable SQL scripts. Understanding how to properly declare, initialize, and
manage variables can significantly enhance your database operations. Practice is key to mastering
their use, so experimenting with different scenarios and applications will build your proficiency and
confidence in handling variables effectively in SQL Server.