T-SQL – SELECT Statement

T-SQL – SELECT Statement ”; Previous Next SQL Server SELECT statement is used to fetch the data from a database table which returns data in the form of result table. These result tables are called result-sets. Syntax Following is the basic syntax of SELECT statement − SELECT column1, column2, columnN FROM table_name; Where, column1, column2…are the fields of a table whose values you want to fetch. If you want to fetch all the fields available in the field, then you can use the following syntax − SELECT * FROM table_name; Example Consider the CUSTOMERS table having the following records − ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 2000.00 2 Khilan 25 Delhi 1500.00 3 kaushik 23 Kota 2000.00 4 Chaitali 25 Mumbai 6500.00 5 Hardik 27 Bhopal 8500.00 6 Komal 22 MP 4500.00 7 Muffy 24 Indore 10000.00 Following command is an example, which would fetch ID, Name and Salary fields of the customers available in CUSTOMERS table − SELECT ID, NAME, SALARY FROM CUSTOMERS; The above command will produce the following output. ID NAME SALARY 1 Ramesh 2000.00 2 Khilan 1500.00 3 kaushik 2000.00 4 Chaitali 6500.00 5 Hardik 8500.00 6 Komal 4500.00 7 Muffy 10000.00 If you want to fetch all the fields of CUSTOMERS table, then use the following query − SELECT * FROM CUSTOMERS; The above will produce the following output. ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 2000.00 2 Khilan 25 Delhi 1500.00 3 kaushik 23 Kota 2000.00 4 Chaitali 25 Mumbai 6500.00 5 Hardik 27 Bhopal 8500.00 6 Komal 22 MP 4500.00 7 Muffy 24 Indore 10000.00 Print Page Previous Next Advertisements ”;

T-SQL – Home

T-SQL Tutorial PDF Version Quick Guide Resources Job Search Discussion T-SQL (Transact-SQL) is an extension of SQL language. This tutorial covers the fundamental concepts of T-SQL such as its various functions, procedures, indexes, and transactions related to the topic. Each topic is explained using examples for easy understanding. Audience This tutorial is designed for those who want to learn the basics of T-SQL. Prerequisites To go ahead with this tutorial, familiarity with database concepts is preferred. It is good to have SQL Server installed on your computer, as it might assist you in executing the examples yourself and get to know how it works. Print Page Previous Next Advertisements ”;

T-SQL – Stored Procedures

T-SQL – Stored Procedures ”; Previous Next The MS SQL Server Stored procedure is used to save time to write code again and again by storing the same in database and also get the required output by passing parameters. Syntax Following is the basic syntax of Stored procedure creation. Create procedure <procedure_Name> As Begin <SQL Statement> End Go Example Consider the CUSTOMERS table having the following records. ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 2000.00 2 Khilan 25 Delhi 1500.00 3 kaushik 23 Kota 2000.00 4 Chaitali 25 Mumbai 6500.00 5 Hardik 27 Bhopal 8500.00 6 Komal 22 MP 4500.00 7 Muffy 24 Indore 10000.00 Following command is an example which would fetch all records from the CUSTOMERS table in Testdb database. CREATE PROCEDURE SelectCustomerstabledata AS SELECT * FROM Testdb.Customers GO The above command will produce the following output. ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 2000.00 2 Khilan 25 Delhi 1500.00 3 kaushik 23 Kota 2000.00 4 Chaitali 25 Mumbai 6500.00 5 Hardik 27 Bhopal 8500.00 6 Komal 22 MP 4500.00 7 Muffy 24 Indore 10000.00 Print Page Previous Next Advertisements ”;

T-SQL – Date Functions

T-SQL – Date Functions ”; Previous Next Following is the list of date functions in MS SQL Server. GETDATE() It will return the current date along with time. Syntax Syntax for the above function − GETDATE() Example The following query will return the current date along with time in MS SQL Server. Select getdate() as currentdatetime DATEPART() It will return the part of date or time. Syntax Syntax for the above function − DATEPART(datepart, datecolumnname) Example Example 1 − The following query will return the part of current date in MS SQL Server. Select datepart(day, getdate()) as currentdate Example 2 − The following query will return the part of current month in MS SQL Server. Select datepart(month, getdate()) as currentmonth DATEADD() It will display the date and time by add or subtract date and time interval. Syntax Syntax for the above function − DATEADD(datepart, number, datecolumnname) Example The following query will return the after 10 days date and time from the current date and time in MS SQL Server. Select dateadd(day, 10, getdate()) as after10daysdatetimefromcurrentdatetime DATEDIFF() It will display the date and time between two dates. Syntax Syntax for the above function − DATEDIFF(datepart, startdate, enddate) Example The following query will return the difference of hours between 2015-11-16 and 2015-11-11 dates in MS SQL Server. Select datediff(hour, 2015-11-16, 2015-11-11) as differencehoursbetween20151116and20151111 CONVERT() It will display the date and time in different formats. Syntax Syntax for the above function − CONVERT(datatype, expression, style) Example The following queries will return the date and time in different format in MS SQL Server. SELECT CONVERT(VARCHAR(19),GETDATE()) SELECT CONVERT(VARCHAR(10),GETDATE(),10) SELECT CONVERT(VARCHAR(10),GETDATE(),110) Print Page Previous Next Advertisements ”;

T-SQL – Functions

T-SQL – Functions ”; Previous Next MS SQL Server has many built-in functions to perform processing on string or numeric data. Following is the list of all useful SQL built-in functions − SQL Server COUNT Function − The SQL Server COUNT aggregate function is used to count the number of rows in a database table. SQL Server MAX Function − The SQL Server MAX aggregate function allows to select the highest (maximum) value for a certain column. SQL Server MIN Function − The SQL Server MIN aggregate function allows to select the lowest (minimum) value for a certain column. SQL Server AVG Function − The SQL Server AVG aggregate function selects the average value for certain table column. SQL Server SUM Function − The SQL Server SUM aggregate function allows selecting the total for a numeric column. SQL Server SQRT Function − This is used to generate a square root of a given number. SQL Server RAND Function − This is used to generate a random number using SQL command. SQL Server CONCAT Function − This is used to concatenate multiple parameters to a single parameter. SQL Server Numeric Functions − Complete list of SQL functions required to manipulate numbers in SQL. SQL Server String Functions − Complete list of SQL functions required to manipulate strings in SQL. Print Page Previous Next Advertisements ”;

T-SQL – String Functions

T-SQL – String Functions ”; Previous Next MS SQL Server String functions can be applied on string value or will return string value or numeric data. Following is the list of String functions with examples. ASCII() Ascii code value will come as output for a character expression. Example The following query will give the Ascii code value of a given character. Select ASCII (”word”) CHAR() Character will come as output for given Ascii code or integer. Example The following query will give the character for a given integer. Select CHAR(97) NCHAR() Unicode character will come as output for a given integer. Example The following query will give the Unicode character for a given integer. Select NCHAR(300) CHARINDEX() Starting position for given search expression will come as output in a given string expression. Example The following query will give the starting position of ”G” character for given string expression ”KING”. Select CHARINDEX(”G”, ”KING”) LEFT() Left part of the given string till the specified number of characters will come as output for a given string. Example The following query will give the ”WORL” string as mentioned 4 number of characters for given string ”WORLD”. Select LEFT(”WORLD”, 4) RIGHT() Right part of the given string till the specified number of characters will come as output for a given string. Example The following query will give the ”DIA” string as mentioned 3 number of characters for given string ”INDIA”. Select RIGHT(”INDIA”, 3) SUBSTRING() Part of a string based on the start position value and length value will come as output for a given string. Example The following queries will give the ”WOR”, ”DIA”, ”ING” strings as we mentioned (1,3), (3,3) and (2,3) as start and length values respectively for given strings ”WORLD”, ”INDIA” and ”KING”. Select SUBSTRING (”WORLD”, 1,3) Select SUBSTRING (”INDIA”, 3,3) Select SUBSTRING (”KING”, 2,3) LEN() Number of characters will come as output for a given string expression. Example The following query will give the 5 for the ”HELLO” string expression. Select LEN(”HELLO”) LOWER() Lowercase string will come as output for a given string data. Example The following query will give the ”sqlserver” for the ”SQLServer” character data. Select LOWER(”SQLServer”) UPPER() Uppercase string will come as output for a given string data. Example The following query will give the ”SQLSERVER” for the ”SqlServer” character data. Select UPPER(”SqlServer”) LTRIM() String expression will come as output for a given string data after removing leading blanks. Example The following query will give the ”WORLD” for the ”   WORLD” character data. Select LTRIM(” WORLD”) RTRIM() String expression will come as output for a given string data after removing trailing blanks. Example The following query will give the ”INDIA” for the ”INDIA   ” character data. Select RTRIM(”INDIA ”) REPLACE() String expression will come as output for a given string data after replacing all occurrences of specified character with specified character. Example The following query will give the ”KNDKA” string for the ”INDIA” string data. Select REPLACE(”INDIA”, ”I”, ”K”) REPLICATE() Repeat string expression will come as output for a given string data with specified number of times. Example The following query will give the ”WORLDWORLD” string for the ”WORLD” string data. Select REPLICATE(”WORLD”, 2) REVERSE() Reverse string expression will come as output for a given string data. Example The following query will give the ”DLROW” string for the ”WORLD” string data. Select REVERSE(”WORLD”) SOUNDEX() Returns four-character (SOUNDEX) code to evaluate the similarity of two given strings. Example The following query will give the ”S530” for the ”Smith”, ”Smyth” strings. Select SOUNDEX(”Smith”), SOUNDEX(”Smyth”) DIFFERENCE() Integer value will come as output of given two expressions. Example The following query will give the 4 for the ”Smith”, ”Smyth” expressions. Select Difference(”Smith”,”Smyth”) Note − If the output value is 0 it indicates weak or no similarity between give 2 expressions. SPACE() String will come as output with the specified number of spaces. Example The following query will give the ”I LOVE INDIA”. Select ”I”&plus;space(1)&plus;”LOVE”&plus;space(1)&plus;”INDIA” STUFF() String expression will come as output for a given string data after replacing from starting character till the specified length with specified character. Example The following query will give the ”AIJKFGH” string for the ”ABCDEFGH” string data as per given starting character and length as 2 and 4 respectively and ”IJK” as specified target string. Select STUFF(”ABCDEFGH”, 2,4,”IJK”) STR() Character data will come as output for the given numeric data. Example The following query will give the 187.37 for the given 187.369 based on specified length as 6 and decimal as 2. Select STR(187.369,6,2) UNICODE() Integer value will come as output for the first character of given expression. Example The following query will give the 82 for the ”RAMA” expression. Select UNICODE(”RAMA”) QUOTENAME() Given string will come as output with the specified delimiter. Example The following query will give the “RAMA” for the given ”RAMA” string as we specified double quote as delimiter. Select QUOTENAME(”RAMA”,”””) PATINDEX() Starting position of the first occurrence from the given expression as we specified ”I” position is required. Example The following query will give the 1 for the ”INDIA”. Select PATINDEX(”I%”,”INDIA”) FORMAT() Given expression will come as output with the specified format. Example The following query will give the ” Monday, November 16, 2015” for the getdate function as per specified format with ”D” refers weekday name. SELECT FORMAT ( getdate(), ”D”) CONCAT() Single string will come as output after concatenating the given parameter values. Example The following query will give the ”A,B,C” for the given parameters. Select CONCAT(”A”,”,”,”B”,”,”,”C”) Print Page Previous Next Advertisements ”;

T-SQL – Useful Resources

T-SQL – Useful Resources ”; Previous Next The following resources contain additional information on T-SQL. Please use them to get more in-depth knowledge on this. Useful Video Courses T-SQL Online Training 45 Lectures 4.5 hours Tutorialspoint More Detail PostgreSQL, PGadmin, and SQL Online Training with Mini Project 36 Lectures 5 hours Karthikeya T More Detail Start A T-Shirt Business | Merch By Amazon, Teespring & more 59 Lectures 3.5 hours Jason Gandy More Detail Grow Your T-Shirt Business With Online Marketing 22 Lectures 1.5 hours Jason Gandy More Detail SQL Programming Training Course 15 Lectures 1.5 hours SUPRIO DUTTA More Detail SQL Básico Para Engenheiro De Dados 40 Lectures 3 hours Vinicius Vale More Detail Print Page Previous Next Advertisements ”;

T-SQL – LIKE Clause

T-SQL – LIKE Clause ”; Previous Next The MS SQL Server LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator − The percent sign (%) The underscore (_) The percent sign represents zero, one, or multiple characters. The underscore represents a single number or character. The symbols can be used in combinations. Syntax Following is the basic syntax of % and _. SELECT *column-list FROM table_name WHERE column LIKE ”XXXX%” or SELECT *column-list FROM table_name WHERE column LIKE ”%XXXX%” or SELECT *column-list FROM table_name WHERE column LIKE ”XXXX_” or SELECT *column-list FROM table_name WHERE column LIKE ”_XXXX” or SELECT *column-list FROM table_name WHERE column LIKE ”_XXXX_” You can combine N number of conditions using AND or OR operators. XXXX could be any numeric or string value. Example Following are a number of examples showing WHERE part having different LIKE clause with ”%” and ”_” operators. Sr.No Statement & Description 1 WHERE SALARY LIKE ”200%” Finds any values that start with 200 2 WHERE SALARY LIKE ”%200%” Finds any values that have 200 in any position 3 WHERE SALARY LIKE ”_00%” Finds any values that have 00 in the second and third positions 4 WHERE SALARY LIKE ”2_%_%” Finds any values that start with 2 and are at least 3 characters in length 5 WHERE SALARY LIKE ”%2” Finds any values that end with 2 6 WHERE SALARY LIKE ”_2%3” Finds any values that have a 2 in the second position and end with a 3 7 WHERE SALARY LIKE ”2___3” Finds any values in a five-digit number that start with 2 and end with 3 Consider the CUSTOMERS table having the following records. ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 2000.00 2 Khilan 25 Delhi 1500.00 3 kaushik 23 Kota 2000.00 4 Chaitali 25 Mumbai 6500.00 5 Hardik 27 Bhopal 8500.00 6 Komal 22 MP 4500.00 7 Muffy 24 Indore 10000.00 Following command is an example, which will display all the records from CUSTOMERS table where SALARY starts with 200. SELECT * FROM CUSTOMERS WHERE SALARY LIKE ”200%”; The above command will produce the following output. ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 2000.00 3 kaushik 23 Kota 2000.00 Print Page Previous Next Advertisements ”;

T-SQL – Quick Guide

T-SQL – Quick Guide ”; Previous Next T-SQL – Overview In 1970”s the product called ”SEQUEL”, structured English query language, developed by IBM and later SEQUEL was renamed to ”SQL” which stands for Structured Query Language. In 1986, SQL was approved by ANSI (American national Standards Institute) and in 1987, it was approved by ISO (International Standards Organization). SQL is a structure query language which is a common database language for all RDBMS products. Different RDBMS product vendors have developed their own database language by extending SQL for their own RDBMS products. T-SQL stands for Transact Structure Query Language which is a Microsoft product and is an extension of SQL Language. Example MS SQL Server – SQLT-SQL ORACLE – SQLPL-SQL T-SQL – Data Types SQL Server data type is an attribute that specifies types of data of any object. Each column, variable and expression has related data type in SQL Server. These data types can be used while creating tables. You can choose a particular data type for a table column based on your requirement. SQL Server offers seven categories including other category of data types for use. Exact Numeric Types Type From To bigint -9,223,372,036,854,775,808 9,223,372,036,854,775,807 int -2,147,483,648 2,147,483,647 smallint -32,768 32,767 tinyint 0 255 bit 0 1 decimal -10^38 &plus;1 10^38 –1 numeric -10^38 &plus;1 10^38 –1 money -922,337,203,685,477.5808 &plus;922,337,203,685,477.5807 smallmoney -214,748.3648 &plus;214,748.3647 Numeric and decimal are Fixed precision and scale data types and are functionally equivalent. Approximate Numeric Types Type From To Float -1.79E &plus; 308 1.79E &plus; 308 Real -3.40E &plus; 38 3.40E &plus; 38 Date and Time Types Type From To datetime(3.33 milliseconds accuracy) Jan 1, 1753 Dec 31, 9999 smalldatetime(1 minute accuracy) Jan 1, 1900 Jun 6, 2079 date(1 day accuracy. Introduced in SQL Server 2008) Jan 1, 0001 Dec 31, 9999 datetimeoffset(100 nanoseconds accuracy. Introduced in SQL Server 2008) Jan 1, 0001 Dec 31, 9999 datetime2(100 nanoseconds accuracy. Introduced in SQL Server 2008) Jan 1, 0001 Dec 31, 9999 time(100 nanoseconds accuracy. Introduced in SQL Server 2008) 00:00:00.0000000 23:59:59.9999999 Character Strings Sr.No Type & Description 1 char Fixed-length non-Unicode character data with a maximum length of 8,000 characters. 2 varchar Variable-length non-Unicode data with a maximum of 8,000 characters. 3 Varchar (max) Variable-length non-Unicode data with a maximum length of 231 characters (Introduced in SQL Server 2005). 4 text Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters Unicode Character Strings Sr.No Type & Description 1 nchar Fixed-length Unicode data with a maximum length of 4,000 characters. 2 nvarchar Variable-length Unicode data with a maximum length of 4,000 characters. 3 Nvarchar (max) Variable-length Unicode data with a maximum length of 230 characters (Introduced in SQL Server 2005). 4 ntext Variable-length Unicode data with a maximum length of 1,073,741,823 characters. Binary Strings Sr.No Type & Description 1 binary Fixed-length binary data with a maximum length of 8,000 bytes. 2 varbinary Variable-length binary data with a maximum length of 8,000 bytes. 3 varbinary(max) Variable-length binary data with a maximum length of 231 bytes (Introduced in SQL Server 2005). 4 image Variable-length binary data with a maximum length of 2,147,483,647 bytes. Other Data Types sql_variant − Stores values of various SQL Server-supported data types, except text, ntext, and timestamp. timestamp − Stores a database-wide unique number that gets updated every time a row gets updated. uniqueidentifier − Stores a globally unique identifier (GUID). xml − Stores XML data. You can store XML instances in a column or a variable (Introduced in SQL Server 2005). cursor − A reference to a cursor. table − Stores a result set for later processing. hierarchyid − A variable length, system data type used to represent position in a hierarchy (Introduced in SQL Server 2008). T-SQL – Create Tables Creating a basic table involves naming the table and defining its columns and each column”s data type. The SQL Server CREATE TABLE statement is used to create a new table. Syntax Following is the basic syntax of CREATE TABLE statement − CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ….. columnN datatype, PRIMARY KEY( one or more columns )); CREATE TABLE is the keyword telling the database system what you want to do. In this case, you want to create a new table. The unique name or identifier for the table follows the CREATE TABLE statement. Then in brackets comes the list defining each column in the table and what sort of data type it is. The syntax becomes clearer to understand with the following example. A copy of an existing table can be created using a combination of the CREATE TABLE statement and the SELECT statement. You can check complete details at Create Table Using another Table. Example In this example, let’s create a CUSTOMERS table with ID as primary key and NOT NULL are the constraints showing that these fields cannot be NULL while creating records in this table − CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID)); You can verify if your table has been created successfully by looking at the message displayed by the SQL server, otherwise you can use the following command − exec sp_columns CUSTOMERS The above command produces the following output. TABLE_QUALIFIER TABLE_OWNER TABLE_NAME COLUMN_NAME DATA_TYPE TYPE_NAME PRECISION LENGTH SCALE RADIX NULLABLE REMARKS COLUMN_DEF SQL_DATA_TYPE SQL_DATETIME_SUB CHAR_OCTET_LENGTH ORDINAL_POSITION IS_NULLABLE SS_DATA_TYPE TestDB dbo CUSTOMERS ID 4 int 10 4 0 10 0 NULL NULL 4 NULL NULL 1 NO 56 TestDB dbo CUSTOMERS NAME 12 varchar 20 20 NULL NULL 0 NULL NULL 12 NULL 20 2 NO 39 TestDB dbo CUSTOMERS AGE 4 int 10 4 0 10 0 NULL NULL 4 NULL NULL 3 NO 56 TestDB dbo CUSTOMERS ADDRESS 1 char 25 25 NULL NULL 1 NULL NULL 1 NULL 25 4 YES 39 TestDB dbo CUSTOMERS SALARY 3 decimal 18 20 2 10 1 NULL NULL 3 NULL NULL 5 YES 106 You can now see that

T-SQL – Joining Tables

T-SQL – Joining Tables ”; Previous Next The MS SQL Server Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each. Consider the following two tables, (a) CUSTOMERS table is as follows − ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 2000.00 2 Khilan 25 Delhi 1500.00 3 kaushik 23 Kota 2000.00 4 Chaitali 25 Mumbai 6500.00 5 Hardik 27 Bhopal 8500.00 6 Komal 22 MP 4500.00 7 Muffy 24 Indore 10000.00 (b) Another table is ORDERS as follows − OID DATE CUSTOMER_ID AMOUNT 100 2009-10-08 00:00:00.000 3 1500.00 101 2009-11-20 00:00:00.000 2 1560.00 102 2009-10-08 00:00:00.000 3 3000.00 103 2008-05-20 00:00:00.000 4 2060.00 Let us join these two tables in our SELECT statement as follows − SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS, ORDERS WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID OR SELECT A.ID, A.NAME, A.AGE, B.AMOUNT FROM CUSTOMERS A inner join ORDERS B on A.ID = B.Customer_ID The above command will produce the following output. ID NAME AGE AMOUNT 2 Khilan 25 1560.00 3 kaushik 23 1500.00 3 kaushik 23 3000.00 4 Chaitali 25 2060.00 It is noticeable that the join is performed in the WHERE clause. Several operators can be used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to join tables. However, the most common operator is the equal symbol. MS SQL Server Join Types − There are different types of joins available in MS SQL Server − INNER JOIN − Returns rows when there is a match in both tables. LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right table. RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left table. FULL JOIN − Returns rows when there is a match in one of the tables. SELF JOIN − This is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the MS SQL Server statement. CARTESIAN JOIN − Returns the Cartesian product of the sets of records from the two or more joined tables. Print Page Previous Next Advertisements ”;