SQL - Training Course - BKACAD
SQL - Training Course - BKACAD
BKACAD
1
2.23 Summary .............................................................................................................................. 29
3.3.5 TCL............................................................................................................................... 32
2
5 SQL Operators ............................................................................................................................ 41
3
5.7.5 OR................................................................................................................................. 57
5.7.9 IN .................................................................................................................................. 59
5.11.2 INTERSECT................................................................................................................. 69
4
6.4 SQL Multi-line Comments .................................................................................................. 73
7.1.8 IN .................................................................................................................................. 77
7.1.20 Summary....................................................................................................................... 84
5
8.2 Insert INTO Statement in SQL ............................................................................................ 85
8.5 Insert data that is not in the same order as the table columns .............................................. 87
8.6 Insert data into a table with columns that have a default value ........................................... 87
8.8.1 INSERT INTO with SELECT and EXECUTE options to insert data from other tables
91
8.8.3 INSERT TOP to limit the data inserted from the source table ..................................... 93
8.9.1 Insert data into a remote table by using a linked server ............................................... 96
8.9.2 Insert data into a remote table by using the OPENQUERY function .......................... 96
8.9.3 Inserts data into a remote table by using the OPENDATASOURCE function ............ 96
8.9.5 Insert data using the OPENROWSET function with BULK to bulk load data into a table
97
6
9.2.1 The UPDATE statement is typically in three parts: ................................................... 100
9.8 UPDATE table with data from another table ..................................................................... 104
9.11 UPDATE The Data Using a system data type ................................................................... 105
9.12 Update - Modifying the value of a property or data member ............................................ 105
9.13 Update - Overriding the Default Behavior of the Query Optimizer by Using Hints ......... 106
10.3 How to replace multiple patterns in a given string statement ............................................ 110
10.4.1 How to perform a simple update to change the keyword create to the Alter table .... 112
7
11.3.1 MAX() ........................................................................................................................ 114
8
13.3 SELECT COUNT DISTINCT statement .......................................................................... 130
9
15.5.1 Drop a Single Column ................................................................................................ 143
16.6 Using with Ties to include rows that match the values in the last row.............................. 148
16.7 Using TOP to limit the number of rows deleted ................................................................ 149
16.8 Using TOP to limit the number of rows inserted ............................................................... 150
16.9 Using TOP to limit the number of rows updated ............................................................... 151
17.4 Using (>) and (<) instead of Between values ................................................................... 155
10
18 SQL Exists Statement ............................................................................................................... 159
18.2.1 How to use Null statement in a subquery to still return a result set? ......................... 159
18.2.3 Using Comparing queries by using Exists and = Any statement ............................... 161
18.2.4 How to Compare queries by using Exits and In a statement? .................................... 162
19.14 How to create a nonclustered index on a table in the current database?............................ 173
11
19.15 How to create a clustered index on a table in another database? ....................................... 173
19.16 How to create a clustered index on a table in another database? ....................................... 173
20.4 Using SQL Server Management Studio in Unique Constraint .......................................... 177
12
22.2 SQL Aggregate Function ................................................................................................... 185
23.5.1 Converting date to other date and time types ............................................................. 194
13
24.7 Using Cast to produce more readable text statement ......................................................... 201
24.8 Using Cast with the Like clause statement ........................................................................ 201
24.9 Using Convert or Cast with typed XML statement ........................................................... 202
24.10 Using Cast and Convert with the DateTime data statement .............................................. 204
24.11 Using Convert with binary and character data statement ................................................. 205
24.13 Using convert with datetime data in different formats ...................................................... 206
14
1 Introduction To Databases
1.1 Introduction
Before starting about SQL we must learn about the Database. So, this chapter will provide
you with an introduction to the database. In this chapter, we will learn about the Database,
its different types, and other terms about the database.
15
Depending upon the usage requirements, there are following types of databases available
in the market:
- Centralized database
- Distributed database
- Personal database
- End-user database
- Commercial database
- NoSQL database
- Operational database
- Relational database
- Cloud database
- Object-oriented database
- Graph database
16
- Reduced updating errors and increased consistency
- Greater data integrity and independence from application programs
- Improved data access to users through the use of host and query languages
- Improved data security
- Reduced data entry, storage, and retrieval costs
The emergence of the first type of DBMS, the hierarchical DBMS. IBM had the first
model, developed on IBM 360 and their (DBMS) was called IMS, originally it was written
17
for the Apollo program. This type of DBMS was based on binary trees, where the shape
was like a tree, and relations were only limited between parent and child records. The
benefits were numerous; less redundant data, data independence, security, and integrity,
which all lead to efficient searches. Nonetheless; there were some disadvantages such as;
complex implementation, which was hard to manage because of the absence of standards,
which made it harder to handle many relationships.
Before databases existed, everything had to be recorded on paper. We had lists, journals,
ledgers, and endless archives containing hundreds of thousands or even millions of records
contained in filing cabinets. When it was necessary to access one of these records, finding
and physically obtaining the record was a slow and laborious task. There were often
problems ranging from misplaced records to fires that wiped out entire archives and
destroyed the history of societies, organizations, and governments. There were also
security problems because physical access was often easy to gain.
The database was created to try and solve these limitations of traditional paper-based
information storage. In databases, the files are called records, and the individual data
elements in a record (for example, name, phone number, date of birth) are called fields.
The way these elements are stored has evolved since the early days of databases.
The earliest systems were called the hierarchical and network models.
The hierarchical model organized data in a tree-like structure, as shown in fig and IBM
developed this model in the 1960s.
18
• 1960: 2 models were in use when the concept of computerized DBMS started. It
was at the same time that the use of computers became the choice for private
organizations. Models used then CODASYL (N/W MODEL) and IMS (IBM’s
hierarchical model). SABRE system by IBM was designed to help American
Airlines manage reservations data.
• 1969: IBM introduced its first-ever mainframe machine as System/360.
• 1970-72: E.F. Codd published a vital paper stating the use of RDBMS wherein he
mentioned the DB schema being disconnected from the physical information
storage; which then became the gold standard for DBMS1970s: 2 major RDBMS
prototypes were designed viz. INGRES by UBC and System R by IBM San Jose.
While INGRES designed query language QUEL which ultimately resulted in
INGRES CORP., MS SQL SERVER, SYBASE, WANG’S PACE, and BRITTON-
LEE; SystemR used the query language ‘SEQUEL’. This then resulted in the
development of SQL/DS, DB2, Allbase, Oracle, and Non-stop SQL.
• 1976: ERD also known as entity-relationship diagrams came into play. These were
proposed by P. Chen. They are also known as the conceptual models which focused
more on the data application rather than logical tabular structure.
• 1980s: SQL became the standard query language. RDBMS was widely popular and
DB2 became a flagship product by IBM. Later on, the introduction of IBM PCs
19
further resulted in several new DB companies and products such as RBASE 5000
and RIM, PARADOX
• Early 90s: post DB industry shakeout, surviving companies sold their products at
high prices. Meanwhile, new client tools for developing applications were released.
These included Oracle Developer, VB, and PowerBuilder. ODBC prototypes and
Excel/Access were also developed within the same timeframe.
• The Mid 90s: Internet became popular which caused the exponential growth of the
DB industry. More people with average desktops started using client/server systems
for legal data.
• Late 90s: investment in online business resulted in internet DB connectors like
FrontPage, Active Server Pages, Java Servlets, Dream Weaver, Oracle Developer
2000, and Enterprise Java Beans. Use of Apache, SQL, and other systems
introduced open-source solutions to the Internet. Gradually, online transaction
processing and analytic processing became popular.
• The 2000s: DB applications were not affected by the decline of the internet industry.
Interactive applications for PDAs, point-of-sale transactions, and consolidation of
vendors were developed.
• Present: Currently, Microsoft, Oracle, and IBM are the leading companies for
Database Systems.
20
In other words, a database management system is a combination of hardware and software
that can be used to set up and monitor a database and can manage the updation and retrieval
of the database that has been stored in it.
There are 4 major types of DBMS. Let's look into them in detail.
• Hierarchical - this type of DBMS employs the "parent-child" relationship of
storing data. This type of DBMS is rarely used nowadays. Its structure is like a tree
with nodes representing records and branches representing fields. The windows
registry used in Windows XP is an example of a hierarchical database.
Configuration settings are stored as tree structures with nodes.
• Network DBMS - this type of DBMS supports many-to-many relations. This
usually results in complex database structures. RDM Server is an example of a
database management system that implements the network model.
• Relational DBMS - this type of DBMS defines database relationships in the form
of tables, also known as relations. Unlike network DBMS, RDBMS does not
support many to many relationships. Relational DBMS usually have pre-defined
data types that they can support. This is the most popular DBMS type in the market.
Examples of relational database management systems include SQL, Oracle, and
Microsoft SQL Server database.
• Object-Oriented DBMS - this type supports the storage of new data types. The
data to be stored is in the form of objects. The objects to be stored in the database
have attributes (i.e. gender, ager) and methods that define what to do with the data.
PostgreSQL is an example of an object-oriented relational DBMS.
21
A hierarchical model represents the data in a tree-like structure in which there is a single
parent for each record. To maintain order there is a sort field that keeps sibling nodes into
a recorded manner. These types of models are designed basically for the early mainframe
database management systems, like the Information Management System (IMS) by IBM.
This model structure allows the one-to-one and a one-to-many relationship between
two/more types of data. This structure is very helpful in describing many relationships in
the real world; table of contents, any nested, and sorting information.
The hierarchical structure is used as the physical order of records in storage. One can
access the records by navigating down through the data structure using pointers which are
combined with sequential access. Therefore, the hierarchical structure is not suitable for
certain database operations when a full path is not also included for each record.
Data in this type of database is structured hierarchically and is typically developed as an
inverted tree. The "root" in the structure is a single table in the database and other tables
act as the branches flowing from the root. The diagram below shows a typical hierarchical
database structure.
A relationship in this database model is represented by the term parent/child. A parent table
can be linked with one or more child tables in this type of relationship, but a single child
22
table can be linked with only one parent table. The tables are explicitly linked via a
pointer/index or by the physical arrangement of the records within the tables.
A user can access the data by starting at the root table and working down through the tree
to the target data. the user must be familiar with the structure of the database to access the
data without any complexity.
The IBM Information Management System (IMS) and the RDM Mobile are examples of
a hierarchical database system with multiple hierarchies over the same data.
2.10 Advantages
2.11 Disadvantages
23
The network model is the extension of the hierarchical structure because it allows many-
to-many relationships to be managed in a tree-like structure that allows multiple parents.
In other words, Network databases are hierarchical databases but unlike hierarchical
databases where one node can have one parent only, a network node can have a relationship
with multiple entities. A network database looks more like a cobweb or interconnected
network of records.
In network databases, children are called members and parents are called occupiers. The
difference between each child or member can have more than one parent.
There are two fundamental concepts of a network model:
1. Records contain fields that need hierarchical organization.
2. Sets are used to define one-to-many relationships between records that contain one
owner, many members.
A record may act like an owner in any number of sets, and a member in any number of
sets.
Some well-known database systems that use the network model include:
• Integrated Data Store (IDS)
• IDMS (Integrated Database Management System)
24
2.13 History of Network Model
The network database structure was invented by Charles Bachman. Some of the popular
network databases are the Integrated Data Store (IDS), IDMS (Integrated Database
Management System), Raima Database Manager, TurboIMAGE, and Univac DMS-1100.
2.14 Advantages
2.15 Disadvantages
25
It is called Relational Database Management System (RDBMS) because it is based on the
relational model introduced by E.F. Codd.
Standard relational databases enable users to manage predefined data relationships across
multiple databases.
Popular examples of relational databases include Microsoft SQL Server, Oracle Database,
SQL, and IBM DB2.
Relational databases work on each table has a key field that uniquely indicates each row,
and that these key fields can be used to connect one table of data to another.
2.18 Advantages
26
2.19 Disadvantages
27
Object-oriented databases use small, recyclable separated from software called objects.
The objects themselves are stored in the object-oriented database. Each object contains
two elements:
1. Piece of data (e.g., sound, video, text, or graphics)
2. Instructions, or software programs called methods, for what to do with the data
Object-oriented database management systems (OODBMs) were created in the early
1980s. Some OODBMs were designed to work with OOP languages such as Delphi, Ruby,
C++, Java, and Python.
Some POPULAR EXAMPLES of OODBMs are TORNADO, Gemstone, ObjectStore,
GBase, VBase, InterSystems Cache, Versant Object Database, ODABA, ZODB, Poet.
JADE, and Informix.
28
2.22 The disadvantages of Object-oriented databases
2.23 Summary
29
3 Introduction To SQL And SQL Commands
3.1 Introduction
3.2 SQL
SQL stands for Structured Query Language. SQL is used to create, remove, alter the
database and database objects in a database management system and to store, retrieve,
update the data in a database. SQL is a standard language for creating, accessing,
manipulating database management system. SQL works for all modern relational database
management systems, like SQL Server, Oracle, SQL, etc.
SQL commands can be categorized into five categories based on their functionality.
3.3.1 DDL
DDL stands for data definition language. DDL commands are used for creating and
altering the database and database object in the relational database management system,
like CREATE DATABASE, CREATE TABLE, ALTER TABLE, etc. The most used
DDL commands are CREATE, DROP, ALTER, and TRUNCATE.
CREATE
CREATE command is used to create a database and database object like a table, index,
view, trigger, stored procedure, etc.
Syntax
CREATE TABLE Employee (Id INT, Name VARHCAR(50), Address VARCHAR (100));
ALTER
ALTER command is used to restructure the database object and the settings in the database.
30
Syntax
TRUNCATE
The TRUNCATE command is used to remove all the data from the table. TRUNCATE
command empties a table.
Syntax
TRUNCATE TABLE Employee;
DROP
DROP command is used to remove the database and database object.
Syntax
DROP TABLE Employee;
3.3.2 DML
DML stands for Data Manipulation Language. DML commands are used for manipulating
data in a relational database management system. DML commands are used for adding,
removing, updating data in the database system, like INSERT INTO TableName, DELETE
FROM TableName, UPDATE tableName set data, etc. The most used DML commands
are INSERT INTO, DELETE FROM, UPDATE.
INSERT INTO
INSERT INTO command is used to add data to the database table.
Syntax
INSERT INTO Employee (Id, Name, Address, Salary) VALUES (1, ‘Arvind Singh’, ‘Pune’, 1000);
UPDATE
UPDATE command is used to update data in the database table. A condition can be added
using the WHERE clause to update a specific row.
Syntax
UPDATE Employee SET Address = ‘Pune India’, Salary = 100 WHERE Id =1;
DELETE
31
DELETE command is used to remove data from the database table. A condition can be
added using the WHERE clause to remove a specific row that meets the condition.
Syntax
DELETE FROM Employee WHERE Id =1;
3.3.3 DQL
DQL stands for the Data Query Language. DQL command is used for fetching the data.
DQL command is used for selecting data from the table, view, temp table, table variable,
etc. There is only one command under DQL which is the SELECT command.
Syntax
SELECT * FROM Employee;
3.3.4 DCL
DCL stands for Data Control Language. DCL commands are used for providing and taking
back the access rights on the database and database objects. DCL command used for
controlling user’s access to the data. Most used DCL commands are GRANT and
REVOKE.
GRANT
GRANT is used to provide access right to the user.
Syntax
GRANT INSERT, DELETE ON Employee TO user;
REVOKE
REVOKE command is used to take back access right from the user, it cancels access rights
of the user from the database object.
Syntax
REVOKE ALL ON Employee FROM user;
3.3.5 TCL
TCL stands for transaction control language. TCL commands are used for handling
transactions in the database. Transactions ensure data integrity in the multi-user
environment. TCL commands can rollback and commit data modification in the database.
32
The most used TCL commands are COMMIT, ROLLBACK, SAVEPOINT, and SET
TRANSACTION.
COMMIT
COMMIT command is used to save or apply the modification in the database.
ROLLBACK
ROLLBACK command is used to undo the modification.
SAVEPOINT
SAVEPOINT command is used to temporarily save a transaction, the transaction can roll
back to this point when it's needed.
Syntax
Just write COMMIT or ROLLBACK or SAVEPOINT;
3.4 Summary
33
4 SQL Data Types
4.1 Introduction
In this chapter, we will discuss different Data Types of SQL, and how to use these data
types.
1. In a database, each column, local variable, expression, and parameter has a related
data type.
2. A data type is an attribute that specifies the type of data that the object can hold.
3. The following are the various data types:
o Integer Types
o Boolean Type
o Decimal Types
o Monetary or Currency Types
o Date and Time Values
o String Values
o Binary Values
o Timestamp
o Uniqueidentifier
o XML
4.2.1 Integer Types
1. Integer Types hold integer values.
2. The Integer Types are tinyint, smallint, int, and bigint data types with sizes 1, 2, 4,
and 8 bytes respectively.
34
Integer Types Bytes
Tinyint 1
Smallint 2
Int 4
Bigint 8
4.2.2 Boolean Type
1. A Boolean Type can hold boolean values
2. It can provide a "bit" data type that can take a value of 1, 0, or NULL.
Note
The string values TRUE and FALSE can be converted to bit values: TRUE is
converted to 1 and FALSE is converted to 0.
4.2.3 Decimal Types
1. Decimal Types hold decimal values.
2. They provide the following types:
o decimal and numeric
o float and real
4.2.3.1 Decimal and numeric
• decimal[ (p[ , s] )] and numeric[ (p[ , s] )]
• p (precision)- The maximum total number of decimal digits that can be stored, both
to the left and to the right of the decimal point. The precision must be a value from
1 through the maximum precision of 38. The default precision is 18.
• s (scale)- The maximum number of decimal digits that can be stored to the right of
the decimal point. The scale must be a value from 0 through p. The scale can be
specified only if the precision is specified. The default scale is 0.
• The storage sizes of Decimal and Numeric types vary, based on the precision, as
shown in the following:
Precision Storage bytes
1 to 9 5
35
10 to 19 9
20 to 28 13
29 to 38 17
Note- numeric is functionally equivalent to decimal.
4.2.3.2 Float and real
• float [ ( n ) ] and real.
36
o smalldatetime
o datetime
4.2.5.1 Smalldatetime
• The smalldatetime data type stores dates and times of day with less precision than
datetime.
• The Database Engine stores smalldatetime values as two 2-byte integers.
• The first 2 bytes store the number of days after January 1, 1900.
• The other 2 bytes store the number of minutes since midnight.
4.2.5.2 Datetime
• Values with the datetime data type are stored internally by the Microsoft SQL Server
37
4.2.6.1 Char
• char [ ( n ) ]
38
4.2.7 Binary Values
1. Binary Values hold binary values like's images, audio clips, and video clips.
2. Binary Values types are:
o binary
o varbinary
o Image
4.2.7.1 Binary
• binary [ ( n ) ]
• Fixed-length binary data with a length of n bytes, where n is a value from 1 through
8,000.
• The storage size is n bytes.
4.2.7.2 Varbinary
• varbinary [ ( n | max) ]
39
5. If no change is made to the row, the timestamp value is the same as when it was
previously read.
4.2.9 Uniqueidentifier
• Uniqueidentifier is a 16-byte GUID that is initialized by using the newid() function
or converting a string constant in the form of xxxxxxxx-xxxx-xxxx-xxx-
xxxxxxxxxxxx that is used to guarantee that rows are uniquely identified across
multiple copies of the table.
4.2.10 XML
1. XML is the data type that stores XML data.
2. You can store XML instances in a column, or a variable of XML type.
3. The stored representation of XML data type instances cannot exceed 2 gigabytes
(GB) in size.
Note
1. Use char, nchar, or binary when the sizes of the column data entries are consistent.
2. Use varchar, nvarchar, or varbinary when the sizes of the column data entries vary
considerably.
3. Use varchar(max), nvarchar(max) or varbinary(max) when the sizes of the column
data entries vary considerably, and the size might exceed 8,000 bytes.
4.3 Summary
In this chapter, we learned about Data types in SQL and how to use these Data types.
40
5 SQL Operators
5.1 Introduction
In this chapter, you will learn SQL operators in detail starting with SQL Operator types,
their usages, and examples in SQL.
A SQL operator is a sign or symbol that can perform an operation between operands or
between two or more than two expressions.
SQL operators can be broken down into the following categories:
1. Arithmetic Operators
2. Assignment Operators
3. Bitwise Operators
4. Comparison Operators
5. Logical Operators
6. Scope Resolution Operator
7. String Concatenation Operators
8. Unary Operators
9. Set Operators
Let us discuss step-by-step each of the operators listed above.
41
Operator Meaning Example
+ Addition 15 + 2 = 17
- Subtraction 15 - 2 = 13
* Multiplication 15 * 2 = 30
/ Division 15 / 2 = 7
% Modulo 15 % 2 = 1 (Reminder)
Example 1.1
1. declare @var1 int,
2. @var2 int,
3. @add int,
4. @sub int,
5. @mul int,
6. @div int,
7. @rem int; -- declaration of var1, var2, add,sub,mul,div
8.
9. set @var1=12;--assigning var1=12
10. set @var2=5;--assigning var1=12
11.
12. set @add = @var1 + @var2;--Addtion
13. set @sub = @var1 - @var2;--Subtraction
14. set @mul = @var1 * @var2;--Multiplication
15. set @div = @var1 / @var2;--Division
16.
17. select @var1 as Variable1,
18. @var2 as Variable2,
19. @add as Addition,
20. @sub as Subtraction,
21. @mul as Multipication,
22. @div as division; --getting the result by using select
By using the code above you will get the following output,
Example 1.2
42
Suppose I have a table named TempTable in which I have 2 columns like a and b, and I
have inserted some values of a and b as in the following,
1. --Creating Table
2. CREATE TABLE #TempTable(
3. a int,
4. b int
5. )
6. --Inseerting Values
7. INSERT INTO #TempTable VALUES(1,2),(12,8),(8,10),(17,3),(11,4),(15,8)
By using the query above you will get a new #TempTable such as the following,
Now you can also use arithmetic operators with your query like,
1. SELECT
2. a as value1,
3. b as value2,
4. (a + b) as ADDITION,
5. (a - b) as SUBTRACTION,
6. (a * b) as MULTIPLICATION,
7. (a / b) as DIVISION,
8. (a % b) as REMINDER
9. FROM #TempTable
The output of the above Query is,
43
The SQL assignment operator is used to assign the value to a variable. We usually see an
assignment operator '='.
Example 2.1
In the following example, I am simply taking a variable and assigning a value.
1. --Declaring variable
2. declare @h int;
3.
4. --Assigning Value
5. set @h=15;
6.
7. --Getting the output with column name Assigned
8. select @h as Assigned
So simply run the code above in T-SQL and you will get the
output: 15 in AssiginedColumn.
The same as in other languages like C, C++, Java, C#, and so on. in T-SQL we
have Shorthand Assignment Operator. The shorthand assignment operators in SQL are +=,
-=, *=, /=, %=. shorthand assignment operators are illustrated in the following table.
Statement With Simple Assignment Operator Statement With Shorthand Assignment Operator
a=a+b a+=b
a=a–b a-=b
a=a*b a*=b
a=a/b a/=b
a=a%b a%=b
44
2. set @j=15;
3. set @j-=10;
4. select @j as Subtraction
The output of the code above is 5 with column name Subtraction.
Example 2.4
1. declare @k int;
2. set @k=15;
3. set @k*=10;
4. select @k as Multiplication
The output of the code above is 150 with column name Multiplication.
Example 2.5
1. declare @L int;
2. set @L=15;
3. set @L/=10;
4. select @L as Divide
The output of the code above is 1 with column name Divide.
Example 2.6
1. declare @m int;
2. set @m=15;
3. set @m%=10;
4. select @m as Reminder
The output of the code above is 5 with column name Reminder.
Example 2.7
Suppose you have a table of Employee_Info in which you have the 3 fields id, Name,
Salary and inside it some data is available like,
45
Then every value of the salary will be set to 10000 and the output of the code above will
be,
As in other languages (like C, C++, Java, C#, and so on), SQL also supports special
operators that are the bitwise operators. Bitwise operators manipulate the data at the bit
level. The operations are used to test and/or the bits. Bitwise operators are only applied for
integer values they cannot be applied for float or doubled value.
There are four Bitwise operators available in T-SQL that are as follows,
Operator Meaning
46
5.5.2 Bitwise OR ( | )
Bitwise logically OR operation is performed between 2 integer values.
Example 3.2
Suppose there are the two integer numbers 2 and 3 and we want to perform 2 | 3 so we first
convert 2 and 3 into binary format. Then after the OR operation is performed on the bits
then the bits will again be converted into the decimal format and that will be our output.
The complete illustration is given below in the figure,
47
5.5.4 Bitwise Not ( ~ )
The Bitwise logical NOT operation is performed on only one integer value.
Example 3.4
Suppose we have the number 2 and we want to perform the operation ~2 then first 2 will
be converted into binary format then after the not operation is performed on the bits then
the bits will again be converted it into decimal format.
Example 3.5
In the following example, I am writing a SQL query for examples 3.1, 3.2, 3.3, and 3.4
explained above.
1. declare @a int;
2. declare @b int;
3.
4. set @a=2;
5. set @b=3;
6.
48
7. select @a & @b as And_Operation,
8. @a | @b as Or_Operation,
9. @a ^ @b as Exclusive_Operation,
10. ~@a as Bitwise_NOT_A,
11. ~@b as Bitwise_NOT_B ;
The output of the preceding query will be,
Example 3.6
In this example, I am showing how to perform bitwise operations on a table. Suppose you
have a temporary table in which you have the two columns val1 and val2, in which some
data is present like,
1. Create table #MyTempTable(
2. val1 int,val2 int
3. )
4. insert into #MyTempTable values(2,3),(5,3),(8,5),(9,4)
= Equal to
< Less than
> Greater than
<= Less than equal to
>= Greater than equal to
<> Not equal to
!= Not equal to(Not ISO Standard)
!< Not less than(Not ISO Standard)
!> Not greater than(Not ISO Standard)
Example 4.1
Suppose you have a table #TempTable (temporary table) in which you have two columns
val1 and val2. Some values are also inserted into it that are like,
1. --Creating a temporary table
2. create table #TempTable(
3. val1 int,
4. val2 int
5. )
6. --Inserting Data
7. insert into #TempTable values(8,10),(17,3),(11,4),(15,8),(8,9),(8,17),(8,8)
50
Now I am showing you how can you fire a query for all comparison operators.
5.6.1 For Equals (=)
1. select val1 as Value1,
2. val2 as Value2
3. from #TempTable
4. where val1=val2
Output
Where val1 and val2 will be the same that rows will be selected.
51
Where val1 will be greater than from val2, those rows will be selected.
52
Output
Where val1 will not be equal to from val2, those rows will be selected.
53
Where val1 will not be greater than from val2, those rows will be selected.
Logical operators in SQL are used to check some condition and returns a boolean value
that may be true or false.
The list of logical operators of SQL is listed below in the table.
Operator Description
All Check for all the set of comparisons.
AND Check that two values are both true.
ANY Check for anyone's set of comparisons.
BETWEEN Check between the range.
EXISTS Check whether or not a sub-query has a row.
IN Check a list of expressions.
LIKE Match the patterns.
NOT Reverse the value of a Boolean value.
OR Check between two values and anyone should be true.
SOME Check that some set of comparisons are true or not
54
Example 5.1
Suppose you have the two tables #tb1, #tb2 and you have inserted a Name and age in both
tables like,
1. create table #tb1(
2. Name varchar(20),
3. age int
4. )
5. create table #tb2(
6. Name varchar(20),
7. age int
8. )
Both tables will look such as in the following:
#tb1
#tb2
55
Because all the sets of comparisons are true with respect to #tb2. But take a scenario where
one age is greater in #tb2 with respect to all the ages of #tb1. Suppose I insert some data
like this,
1. insert into #tb2 values('Monika Dashora',25)
After inserting the row #tb2 will become,
Because the ANY operator compares a set of values not for all.
56
Note
The difference between ALL and ANY is,
ALL works like an AND so if all the comparisons are true then true is returned else it
returns false, ANY works like an OR so if anyone comparison is true then it returns true.
5.7.3 SOME
SOME and ANY are equivalent, both compare a single column's set of values.
5.7.4 AND
This operator is applied between two expressions and can also be applied between more
than two expressions. If all the expression's conditions are true then it returns true
otherwise it returns false.
Example 5.3
Suppose we have the same table that we had in Example 5.1. Now to see how to use
the AND operator see the following query,
1. select * from #tb2 where age>11 AND age<25
By using the query above you will get those tuples from the table (#tb2) that will be less
than 25 but greater than 11 that will be,
5.7.5 OR
This operator also can be applied between two and more than two expressions. If any
condition is true then it will return true.
Example 5.4
Suppose we have the same table that we had in Example 5.1. Now to see how to use
the OR operator see the following query:
1. --The following query return that tuples where age=11 or age=25
2. select * from #tb2 where age=11 OR age=25
By using the above query we will get the following output,
57
5.7.6 NOT
This operator reverses the value of a Boolean value.
Example 5.5
Suppose we have the same table that we had in Example 5.1. As I just said, the NOT
operator reverses the output so I am using the AND operators example above, Example
5.3, but with the NOT operator.
1. -
- Following code will give that tuple where age will be greater than 25 but not be less th
an 25
2. select * from #tb2 where age>11 AND NOT age<25
The output of the code above is,
5.7.7 BETWEEN
This operator returns the value true if and only if the operand is within the range. This
operator works with the AND operator.
Example 5.6
Take the same table #tb2 of Example 5.1. To learn how to use the Between Operator
execute the following query.
1. -- following query will return those tuples where age is between 11-17
2. select * from #tb2 where age Between 11 AND 17
The output of the preceding query is:
58
You can also execute with the NOT operator so the output will be the reverse.
1. select * from #tb2 where age NOT Between 11 AND 17
5.7.8 Exists
The Exists operator will return true when the subquery contains any row.
Example 5.7
Suppose we have the same table that we had in Example 5.1. Now execute the following
query,
1. --following query returns all the ages from the #tb1 if subquery will contain row
2. SELECT AGE FROM #tb1 WHERE EXISTS (SELECT AGE FROM #tb2);
By using the code above the output will be,
59
Suppose we have the same table that we had in Example 5.1, and for the IN operator we
can write the query like this,
1. -- This will return that tuples which have the age 21 and 18
2. SELECT * FROM #tb1 WHERE AGE IN ( 21, 18 );
The output will be,
5.7.10 LIKE
This operator is used with the WHERE clause to search for the specified pattern in the
column.
Example 5.9
Suppose we have a table #TempTable (temporary table) in which you have 2 columns
named First_Name and Last_Name with some values inserted inside it that is as follows,
1. --String Operator
2. create table #TempTable(
3. First_Name varchar(20),
4. Last_Name varchar(20)
5. )
6. --Inserting Values inside the #TempTable
7. insert into #TempTable values
8. ('Sourabh', 'Somani'),
9. ('Shaili', 'Dashora'),
10. ('Swati', 'Soni'),
11. ('Divya', 'Sharma')
60
4. --2nd query (It will select that tuple where Last_Name start with 'd' )
5. select * from #TempTable where Last_Name like 'd%'
6.
7. --3rd query (It will select that tuple where in Last_Name contains 'o' )
8. select * from #TempTable where Last_Name like '%o%'
9.
10. --4th query (It will select that tuple where in Last_Name contains 'om' )
11. select * from #TempTable where Last_Name like '%om%'
Now from the code above, I will get output like this,
By using scope resolution operator (::) we can access static members of a compound
datatype.
Example 6.1
1. DECLARE @hid hierarchyid;
2. SET @hid = hierarchyid::GetRoot();
3. SELECT @hid.ToString() as _Root;
Output
The code above shows how the scope resolution operator accesses the static
member GetRoot() of type hierarchyid.
61
5.9 SQL String Concatenation Operators
The string concatenation operators concat two or more binary strings. There are the
following string concatenation operators available:
Operator Description
+ Concatenate the string
+= Concatenate the string
% Wildcard character(s) matches
[] Wildcard character(s) matches
[^] Wildcard character(s), not matches
_ Match with only one character
5.9.1 + String Concatenation Operators
This operator concatenates two or more strings, characters, or columns into the single
string.
Example 7.1
Suppose we have a table #TempTable (temporary table) in which you have 2 columns
named First_Name and Last_Name and have some values inserted inside it that is as
follows,
1. --String Operator
2. create table #TempTable(
3. First_Name varchar(20),
4. Last_Name varchar(20)
5. )
6. --Inserting Values inside the #TempTable
7. insert into #TempTable values
8. ('Sourabh', 'Somani'),
9. ('Shaili', 'Dashora'),
62
10. ('Swati', 'Soni'),
11. ('Divya', 'Sharma')
Now I am writing the following query in which I am getting a full name from the first
name and last name using the + string concatenation operator.
1. select
2. First_Name,
3. Last_Name,
4. (First_Name+' '+Last_Name) as Full_Name
5. from #Temptable
Output
63
5.9.3 % Wildcard Character(s) match operator
This operator matches zero or more characters. This operator is mainly used in searching.
It is used either as a prefix or suffix or for both sides as in the following:
%Charecter(s) or Charecter(s)% or %Charecter(s)%
Example 7.3
Suppose I have the same table that I had in Example 7.1 and I am searching as in the
following,
1. --1st query (It will select that tuple where First_Name start with 's' )
2. select * from #TempTable where First_Name like 's%'
3.
4. --2nd query (It will select that tuple where Last_Name start with 'd' )
5. select * from #TempTable where Last_Name like 'd%'
6.
7. --3rd query (It will select that tuple where in Last_Name contains 'o' )
8. select * from #TempTable where Last_Name like '%o%'
9.
10. --4th query (It will select that tuple where in Last_Name contains 'om' )
11. select * from #TempTable where Last_Name like '%om%'
Now from the code above, I will get output like this,
64
5.9.4 [ ] Wildcard Character(s) match operator
This operator only matches a single character within the range specified inside the
brackets. This operator is mainly used to match the pattern like a regular expression.
Example 7.4
To understand this operator let's create a table #TempTable (temporary table) with the 3
columns First_Name, LastName and Mobile_Number and then insert data into it like,
1. --Creating Temoporary table(#TempTable) with 3 columns
2. --First_Name
3. --Last_Name
4. --Mobile_Number
5. create table #TempTable(
6. First_Name varchar(20),
7. Last_Name varchar(20),
8. Mobile_Number varchar(10)
9. )
10. --Inserting data into it
11. insert into #TempTable values
12. ('Sourabh', 'Somani',9314543761),
13. ('Shaili', 'Dashora',8892724222),
14. ('Swati', 'Soni',9928486447),
15. ('Divya', 'Sharma',7737334455)
So the #TempTable will look like,
65
After inserting the data to understand the [ ] wildcard character(s) match operator, let's
execute a query like this,
1. -- select number which
2. --1st latter should be 8 or 9
3. --2nd latter should be between 3 to 8
4. select * from #TempTable where Mobile_Number like '[8-9][3-8]%'
After executing the query above the result of the query will be,
66
Example
Let's use the same table that we had in Example 7.4 and execute the following query.
1. --Following query select that tuple that matches from
2. --s_a_l_
3. --or
4. --s_u_a_h
5. --here _ operator represents any character so in output tuple it should be verifry
6. --s<Any Character>a<Any Character>l<Any Character>
7. --or
8. --s<Any Character>u<Any Character>a<Any Character>h
9. select * from #TempTable where First_Name like 's_a_l_%' or First_Name like 's_u_a_h'
The output of the preceding query will be,
The unary operator is the operator that only takes a single operand in an expression or a
statement. There are 3 unary operators available in SQL as listed in the following table:
Operator Description
+ (Unary Plus) Positive numeric value
- (Unary Minus) Negative numeric value
~ (Bitwise NOT) Provide the one's complement of the number
Example 8.1
The following is the unary minus and unary plus example.
1. declare @a int
2. declare @b int
3. set @a=-17
4. set @b=+8
5. select ABS(@a) as Absolute_Value_Of_a , @a as Actual_Value_Of_a,
6. ABS(@b) as Absolute_Value_Of_b , @b as Actual_Value_Of_b
67
Note
I am not explaining Bitwise NOT here because I have already explained about this operator
in the Bitwise Operator section.
These operators combine the results from two or more queries into a single result set. There
are three types of set operators available as listed below,
Operator Description
EXCEPT Returns any distinct value from the left query which does not belong in the right query.
INTERSECT Returns distinct values from which are common in both the queries.
Combine the result of two and more queries into a single result set that belongs to all
UNION
queries in the union.
5.11.1 EXCEPT
This operator returns any distinct value form the left query that does not belong in the right
query.
Example 9.1
Suppose there are the two tables Employee1 and Employee2 as in the following,
1. --1st Table
2. create table Employee1(
3. EmpId int,
4. First_Name varchar(20),
5. )
6. --2nd Table
7. create table Employee2(
8. EmpId int,
9. First_Name varchar(20),
10. )
The following values are inserted into it,
1. --Values for table 1
2. insert into Employee1 values
3. (1,'Sourabh'),
68
4. (2,'Shaili'),
5. (3,'Swati'),
6. (4,'Divya')
7.
8. --Values for table2
9. insert into Employee2 values
10. (1,'Sourabh'),
11. (2,'Shaili'),
12. (3,'Bittu')
If you execute an EXCEPT query like,
1. --EXCEPT Query
2. (select * from Employee1) EXCEPT (select * from Employee2)
Output
5.11.2 INTERSECT
This operator returns any distinct value that is common in both queries.
Example 9.2
In the above example if we use INTERSECT instead of EXCEPT then the output will be,
1. --Intersect Query
2. (select * from Employee1) INTERSECT (select * from Employee2)
Output
Note
INTERSECT Operator is the inverse of EXCEPT.
5.11.3 UNION
Combine the two queries into a single result set and no repetition will exist for UNION.
Example 9.3
69
In the above example if we use UNION instead of EXCEPT/INTERSECT then the output
will be,
5.12 Summary
70
6 SQL Comments Statements
6.1 Introduction
SQL Comments statement can make your application easier for you to read and maintain.
For example, we can include a comment in a statement that describes the purpose of the
statement within your application with the exception of hints, comments within SQL. The
statement does not affect the statement execution. Please refer to using hints on using this
particular form of comment statement.
A comment can appear between any keywords, parameters, or punctuation marks in a
statement. You can include a comment in a statement in two ways:
• Begin the comment with a slash and an asterisk (/*). Proceed with the text of the
comment. This text can span multiple lines.
• End the comment with an asterisk and a slash (*/). The opening and terminating
characters need not be separated from the text by a space or a line break.
• Begin the comment with -- (two hyphens). Proceed with the text of the comment.
This text cannot extend to a new line. End the comment with a line break.
Some of the tools used to enter SQL have additional restrictions. For example, if you are
using SQL*plus, by default you cannot have a blank line inside a multiline comment.
For more information, please refer to the documentation for the tool you use as an interface
to the database. A SQL statement can contain multiple comments of both styles. The text
of a comment can contain any printable characters in your database character set.
The comment statement indicates the user-provided text. Comments can be inserted on a
separate line, nested at the end of a SQL command line, or within a SQL statement. The
server does not evaluate the comment.
71
SQL Comment uses the two hyphens (--) for single-line or nested comments. Comments
inserted with -- are terminated by a new line, which is specified with a carriage return.
Character (U+000A), line feed character (U+000D), or a combination of the two in SQL
comments.
There is no maximum length for comments. The following table lists the keyboard
shortcuts that you can use to comment or uncomment text.
Syntax
1. -- text_of_comment
Example
The following example uses the -- commenting characters.
Syntax
1. -- Choose the sample database.
2. USE sample;
3. GO
4. -- Choose all columns and all rows from the Address table.
5. SELECT *
6. FROM OrderDetails
7. ORDER BY OrderId ASC; -- We do not have to specify ASC because
8. -- that is the default.
Single line comments start with --. Any text between -- and the end of the line will be
ignored (will not be executed). The following example uses a single-line comment as an
explanation.
Syntax
1. --Select all:
2. SELECT * FROM OrderDetails ;
The following example uses a single-line comment to ignore the end of a line.
Syntax
1. SELECT * FROM OrderDetails -- WHERE OrderName='Coffee';
The following example uses a single-line comment to ignore a statement.
Syntax
1. --SELECT * FROM OrderDetails;
72
2. SELECT * FROM OrderDetails ;
SQL Multi-line comments start with /* and end with */. Any text between /* and */ will
be ignored. The following example uses a multi-line comment as an explanation.
Syntax
1. /*Select all the columns
2. of all the records
3. in the OrderDetails table:*/
4. SELECT * FROM OrderDetails;
The following example uses a multi-line comment to ignore many statements.
Syntax
1. /*SELECT * FROM Customers;
2. SELECT * FROM Products;
3. SELECT * FROM Orders;
4. SELECT * FROM Categories;*/
5. SELECT * FROM OrderDetails;
To ignore just a part of a statement, also use the /* */ comment. The following example
uses a comment to ignore part of a line.
Syntax
1. SELECT CustomerName, /*City,*/ Country FROM Customers;
The following example uses a comment to ignore part of a statement
Syntax
1. SELECT * FROM OrderDetails WHERE (OrderName LIKE 'L%'
2. OR OrderName LIKE 'R%' /*OR OrderName LIKE 'S%'
3. OR OrderName LIKE 'T%'*/ OR OrderName LIKE 'W%')
4. AND OrderName ='Mango'
5. ORDER BY OrderrAddress;
6.5 Summary
In the next chapter, we will learn how to use the SQL insert statement.
73
7 SELECT Statement in SQL
7.1.1 Introduction
In this chapter, we will learn how to SELECT SQL works and different options used with
the SELECT statement.
7.1.2 SQL SELECT statement
SQL SELECT statement is used to select data from a database table or tables.
SQL SELECT statement is used to select records from an RDBMS( Relational Database
Management System) data table. The SELECT statement can select all records, select a set
of records based on a condition, filter records, sort records, group by records, and more.
Here are some of the use cases of the SQL SELECT statement.
1. SQL Select *
2. SQL Select Distinct
3. SQL Select Where
4. SQL Select Having
5. SQL Select Order By
6. SQL Select And, Or, Not
7. SQL Select Insert Into
8. Nested SQL Select
9. SQL Select with Case
10. SQL Select with If…Then
7.1.3 SQL SELECT *
SELECT * statement selects all rows from a database table.
1. SELECT * FROM Table Name
SELECT all rows from a table, EmployeeDetail.
The output looks like the following
74
NOTE
SELECT * is not recommended unless you need all the columns data. Use SELECT
Column1, Column2 fromTable_Name format for better performance.
SELECT Column names
The following SELECT statement uses column names to select data from a table.
SQL Example
1. Select EmpName, EmpAddress from EmployeeDetail
The output looks like the following
75
Inside a table, a column may often contain many duplicate values and sometimes you only
want to list the different (distinct) values.
Syntax
1. SELECT DISTINCT column-name
2. FROM table-name
The output looks like the following
76
7.1.7 LIKE
The LIKE operator is used in a WHERE clause statement to search for a specified pattern
in a column in the SQL.
This is used in two wildcards, it is often used in conjunction with the LIKE operator:
• % - The percent sign represents zero, one, or multiple characters
• _ - The underscore represents a single character
The output looks like the following
7.1.8 IN
The IN operator is used to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions in SQL.
The output looks like the following
77
1. SELECT * FROM EmployeeDetail
2. SELECT GROUP BY
7.1.9 SELECT HAVING
HAVING can be used only in the SELECT statement. HAVING is typically used with the
GROUP BY clause. When GROUP BY is not used, there is an implicit single, aggregated
group.
Syntax:
1. SELECT
2. select_list
3. FROM
4. table_name
5. GROUP BY
6. group_list
7. HAVING
8. conditions;
The output looks like the following
78
7.1.11 SQL SELECT AND, OR, NOT
7.1.12 SELECT AND statement:
• SELECT AND statement require two conditions to be true in a WHERE
statement.
• SELECT WHERE statement with NOT negates the specified condition
• SELECT AND statement: A WHERE statement with AND requires that two
conditions are true
Syntax
1. SELECT column1, column2
2. FROM table_name
3. WHERE condition1 AND condition2 AND condition3;
The output looks like the following
79
7.1.13 SELECT OR statement
SELECT OR statement requires that one of two conditions is true in a where statement in
the SQL.
Syntax
1. SELECT column1, column2,
2. FROM table_name
3. WHERE condition1 OR condition2 OR condition3;
The output looks like the following
80
7.1.15 SQL SELECT INSERT INTO
The SQL SELECT INSERT INTO Select statement copies data from one table and insert
data into another table.
Syntax
1. INSERT INTO table2
2. SELECT * FROM table1
3. WHERE condition;
The output looks like the following
81
2. FROM table1 [, table2 ]
3. WHERE column_name OPERATOR
4. (SELECT column_name [, column_name ]
5. FROM table1 [, table2 ]
6. [WHERE])
The output looks like the following
82
7.1.18 SQL SELECT with IF…THAN
The SQL SELECT with IF and THAN statement goes through conditions and returns a
value when the first condition is met (like an IF-THEN-ELSE statement). So, once a
condition is true, it will stop reading and return the result. If no conditions are true, it
returns the value in the ELSE clause.
If there is no ELSE part and no conditions are true, it returns NULL.
Syntax
1. IF <Condition>
2. {Statement | Block_of_statement}
3. [ ELSE
4. {Statement | Block_of_statement}]
7.1.19 Why SQL * Is harmful?
The SQL * is harmful as of the following points
1. Unnecessary I/O
2. Increased network traffic
3. More application memory
83
4. Depends on the column order
5. Fragile views
6. Conflict in a join query
7. Risky while copying data.
7.1.20 Summary
In the next chapter, you will learn how to use SQL SELECT -HAVING BY.
84
8 SQL INSERT INTO Statement
8.1 Introduction
In this chapter, we’ll learn how to INSERT INTO SQL Statement works and different
options used with the INSERT statement.
The SQL INSERT INTO statement is used to insert a single record or multiple records into
a database table using SQL.
SQL INSERT INTO statement adds data of one or more records to a database. Either all
the rows can be inserted, or a subset may be chosen using a condition.
Here is the syntax of the INSERT INTO statement. The INSERT INTO is followed by a
table name with its columns and followed by VALUES and the values of the respective
columns.
Syntax
1. INSERT INTO table
2. (column1, column2, ... )
3. VALUES
4. (expression1, expression2, ... ),
5. (expression1, expression2, ... ),
6. ...;
The following example inserts one row into the EmployeeDetails table in the sample
database.
The columns in this table are EmpId, EmpName, EmpAddress, and EmpCity. Because
values for all columns are supplied and are listed in the same order as the columns in the
table, the column names do not have to be specified in the column list.
Syntax
85
1. Insert into EmployeeDetails values('Ravi','c-
321 Sector55 Noida','Noida','Noida',9978654332)
Example
The INSERT INTO statement can be used to insert multiple rows by grouping the
statement. The following SQL inserts three rows into the EmployeeDetail table in the
sample database. Because values for all columns are supplied and are listed in the same
order as the columns in the table, the column names do not have to be specified in the
column list.
Syntax
1. Insert into EmployeeDetails values('Ravi','c-
321 Sector55 Noida','Noida','Noida',9978654332,'Rohan',
2. 'D-211 NoidaSector44','Noida','GauthamBudhNagar',9865454398,
3. 'Rohit','C-321 Sector 64 Faridabad','Faridabad','OldFaridabad',9892124359)
Example
86
8.5 Insert data that is not in the same order as the table columns
This example uses a column list to explicitly specify the values that are inserted into each
column.
The column order in the EmployeeDetail table in the Sample database is EmpName,
EmpAddress, EmpCity; however, the columns are not listed in that order in column_list.
Syntax
1. Insert into EmployeeDetails values('PriyanK','Indrapuram,','Ghaziabd', 'Ghaziabad',9055345
544, GETDATE());
8.6 Insert data into a table with columns that have a default
value
This statement shows inserting rows into a table with columns that automatically generate
a value or have a default value. Column_1 is a computed column that automatically
generates value by concatenating a string with the value inserted into column_2. Column_2
is defined with a default constraint.
If a value is not specified for this column, the default value is used.
87
Column_3 is defined with the row version data type, which automatically generates a
unique, incrementing binary number.
Column_4 does not automatically generate a value. When a value for this column is not
specified, NULL is inserted. The INSERT statements insert rows that contain values for
some of the columns but not all. In the last INSERT statement, no columns are specified
and only the default values are inserted by using the DEFAULT VALUES clause.
Syntax
1. CREATE TABLE Employee
2. (
3. column_1 AS 'Computed column ' + column_2,
4. column_2 varchar(30)
5. CONSTRAINT default_name DEFAULT ('my column default'),
6. column_3 rowversion,
7. column_4 varchar(40) NULL
8. );
9. GO
10. INSERT INTO Employee (column_4)
11. VALUES ('Explicit value');
12. INSERT INTO Employee (column_2, column_4)
13. VALUES ('Explicit value', 'Explicit value');
14. INSERT INTO Employee (column_2)
15. VALUES ('Explicit value');
16. INSERT INTO Employee DEFAULT VALUES;
17. GO
18. SELECT column_1, column_2, column_3, column_4
19. FROM Employee;
20. GO
INSERT data into an identity column. The first two INSERT statements allow identity
values to be generated for new rows.
The third INSERT statement overrides the IDENTITY property for the column with the
SET IDENTITY_INSERT statement and inserts an explicit value into the identity column.
Syntax
1. CREATE TABLE StudentDetail (
2. StudentID int IDENTITY(1,1),
3. StudentName varchar(50),
88
4. StudentAddress varchar(50),
5. StudentCiy varchar(50)
6. )
7. Go
8.
9. INSERT StudentDetail VALUES ('Ravin','101 Noida Sector 63','Noida');
10. INSERT StudentDetail VALUES ('Rohit','103 Rahul Vihar','NewDelhi');
11. GO
12. SET IDENTITY_INSERT StudnetDetail ON;
13. GO
14.
89
8.8 Insert data into a uniqueidentifier column by using
NEWID()
The uniquidentifier column uses the NEWID() function to obtain a GUID for column_2.
Unlike for identity columns, the Database Engine does not automatically generate values
for columns with the uniqueidentifier data type, as shown by the second INSERT
statement.
Syntax
1. CREATE TABLE CollegeDetail
2. (
3. CollegeId int IDENTITY,
4. CollegeName uniqueidentifier,
5. );
6. GO
7. INSERT INTO dbo.CollegeDetail(CollegeName)
8. VALUES (NEWID());
9. INSERT INTO CollegeDetail DEFAULT VALUES;
10. GO
11. SELECT CollegeId, CollegeName
12. FROM CollegeDetail
Example
90
8.8.1 INSERT INTO with SELECT and EXECUTE options to insert data from
other tables
The following example shows how to insert data from one table into another table by using
the INSERT...SELECT or INSERT...EXECUTE. Each is based on a multi-table SELECT
statement that includes an expression and a literal value in the column list.
The first INSERT statement uses a SELECT statement to derive the data from the source
tables (Employee, EmployeeDetails, and EmployeeDetail) in the Sample database and
store the result set in the EmployeeDetails table. The second INSERT statement uses the
EXECUTE clause to call a stored procedure that contains the SELECT statement, and the
third INSERT uses the EXECUTE clause to reference the SELECT statement as a literal
string.
Syntax
1. CREATE TABLE NewEmployeeDetail
2. (
3. Id int Primary kei Identity(1,1),
4. DataSource varchar(20) NOT NULL,
5. BusinessEntityID varchar(11) NOT NULL,
6. LastName varchar(40) NOT NULL,
7. SalesDollars money NOT NULL
8. );
9. GO
10. CREATE PROCEDURE dbo.uspGetEmployeeSales
11. AS
12. SET NOCOUNT ON;
13. SELECT 'PROCEDURE', sp.BusinessEntityID, c.LastName,
14. sp.SalesYTD
15. FROM Sales.SalesPerson AS sp
16. INNER JOIN Person.Person AS c
17. ON sp.BusinessEntityID = c.BusinessEntityID
18. WHERE sp.BusinessEntityID LIKE '2%'
19. ORDER BY sp.BusinessEntityID, c.LastName;
20. GO
21. --INSERT...SELECT example
22. INSERT INTO dbo.EmployeeSales
23. SELECT 'SELECT', sp.BusinessEntityID, c.LastName, sp.SalesYTD
24. FROM Sales.SalesPerson AS sp
25. INNER JOIN Person.Person AS c
26. ON sp.BusinessEntityID = c.BusinessEntityID
27. WHERE sp.BusinessEntityID LIKE '2%'
91
28. ORDER BY sp.BusinessEntityID, c.LastName;
29. GO
30. --INSERT...EXECUTE procedure example
31. INSERT INTO dbo.EmployeeSales
32. EXECUTE dbo.uspGetEmployeeSales;
33. GO
34. --INSERT...EXECUTE('string') example
35. INSERT INTO dbo.EmployeeSales
36. EXECUTE
37. ('
38. SELECT ''EXEC STRING'', sp.BusinessEntityID, c.LastName,
39. sp.SalesYTD
40. FROM Sales.SalesPerson AS sp
41. INNER JOIN Person.Person AS c
42. ON sp.BusinessEntityID = c.BusinessEntityID
43. WHERE sp.BusinessEntityID LIKE ''2%''
44. ORDER BY sp.BusinessEntityID, c.LastName
45. ');
46. GO
47. --Show results.
48. SELECT DataSource,BusinessEntityID,LastName,SalesDollars
49. FROM dbo.EmployeeSales;
8.8.2 Insert the common table expression to define data
The INSERT statement creates the NewEmployee table in the Sampledatabase. A common
table expression (EmployeeDetails) defines the rows from one or more tables to be inserted
into the NewEmployee table. The INSERT statement references the columns in the
common table expression.
Syntax
1. CREATE TABLE NewEmployee
2. (
3. EmployeeID int NOT NULL,
4. LastName nvarchar(50) NOT NULL,
5. FirstName nvarchar(50) NOT NULL,
6. PhoneNumber Phone NULL,
7. AddressLine1 nvarchar(60) NOT NULL,
8. City nvarchar(30) NOT NULL,
9. State nchar(3) NOT NULL,
10. PostalCode nvarchar(15) NOT NULL,
11. CurrentFlag Flag
12. );
13. GO
14. WITH EmployeeTemp (EmpID, LastName, FirstName, Phone,
15. Address, City, StateProvince,
16. PostalCode, CurrentFlag)
92
17. AS (SELECT
18. e.BusinessEntityID, c.LastName, c.FirstName, pp.PhoneNumber,
19. a.AddressLine1, a.City, sp.StateProvinceCode,
20. a.PostalCode, e.CurrentFlag
21. FROM HumanResources.Employee e
22. INNER JOIN Person.BusinessEntityAddress AS bea
23. ON e.BusinessEntityID = bea.BusinessEntityID
24. INNER JOIN Person.Address AS a
25. ON bea.AddressID = a.AddressID
26. INNER JOIN Person.PersonPhone AS pp
27. ON e.BusinessEntityID = pp.BusinessEntityID
28. INNER JOIN Person.StateProvince AS sp
29. ON a.StateProvinceID = sp.StateProvinceID
30. INNER JOIN Person.Person as c
31. ON e.BusinessEntityID = c.BusinessEntityID
32. )
33. INSERT INTO NewEmployee
34. SELECT EmpID, LastName, FirstName, Phone,
35. Address, City, StateProvince, PostalCode, CurrentFlag
36. FROM EmployeeTemp;
37. GO
8.8.3 INSERT TOP to limit the data inserted from the source table
INSERT creates the table Employee and inserts the name and year-to-date sales data for
the top 5 random employees from the table EmployeeDetails.EmployeeId in the Sample
database. The INSERT statement chooses any 5 rows returned by the SELECT statement.
The OUTPUT clause displays the rows that are inserted into the EmployeeDetails table.
Notice that the ORDER BY clause in the SELECT statement is not used to determine the
top 5 employees.
Syntax
1. CREATE TABLE Employee
2. ( EmployeeID nvarchar(11) NOT NULL,
3. LastName nvarchar(20) NOT NULL,
4. FirstName nvarchar(20) NOT NULL,
5. YearlySales money NOT NULL
6. );
7. GO
8. INSERT TOP(5)INTO employeeDetails
9. OUTPUT inserted.EmployeeID, inserted.FirstName,
10. inserted.LastName, inserted.YearlySales
11. SELECT sp.BusinessEntityID, c.LastName, c.FirstName, sp.SalesYTD
12. FROM Employee AS sp
13. INNER JOIN Person.Person AS c
93
14. ON sp.BusinessEntityID = c.BusinessEntityID
15. WHERE sp.SalesYTD > 250000.00
16. ORDER BY sp.SalesYTD DESC;
8.8.4 Insert data by specifying a view in SQL
INSERT specifies a view name as the target object; however, the new row is inserted in
the underlying base table. The order of the values in the INSERT statement must match
the column order of the view.
Syntax
1. CREATE TABLE Students (StudentID int, StudentName varchar(30));
2. GO
3. CREATE VIEW Student AS
4. SELECT StudentID, StudentName
5. FROM Students
6. GO
7. INSERT INTO Student
8. VALUES (1,'Ravi');
9. GO
10. SELECT StudentID, StudentName from Students
11. GO
12. SELECT StudentID,StudentName
13. FROM Student
14. GO
Example
94
8.8.5 Insert data into a table variable
The INSERT data specifies a table variable as the target object in the Sample database.
Syntax
1. -- Create the table variable.
2. DECLARE @MyTableVar table(
3. LocationID int NOT NULL,
4. CostRate smallmoney NOT NULL,
5. NewCostRate AS CostRate * 1.5,
6. ModifiedDate datetime);
7.
8. -- Insert values into the table variable.
9. INSERT INTO @MyTableVar (LocationID, CostRate, ModifiedDate)
10. SELECT LocationID, CostRate, GETDATE()
11. FROM Production.Location
12. WHERE CostRate > 0;
13.
14. -- View the table variable result set.
15. SELECT * FROM @MyTableVar;
16. GO
95
This section demonstrates how to insert rows into a remote target table by using a linked
server or a rowset function to reference the remote table.
8.9.1 Insert data into a remote table by using a linked server
This INSERTs rows into a remote table. The example begins by creating a link to the
remote data source by using sp_addlinkedserver. The linked server name, MyLinkServer,
is then specified as part of the four-part object name in the
form server.catalog.schema.object.
Syntax
1. USE master;
2. GO
3. -- Create a link to the remote data source.
4. -- Specify a valid server name for @datasrc as 'server_name'
5. -- or 'server_nameinstance_name'.
6.
7. EXEC sp_addlinkedserver @server = N'MyLinkServer',
8. @srvproduct = N' ',
9. @provider = N'SQLNCLI',
10. @datasrc = N'server_name',
11. @catalog = N'Sample';
12. GO
8.9.2 Insert data into a remote table by using the OPENQUERY function
INSERT a row into a remote table by specifying the OPENQUERY rowset function.
The linked server name created in the previous example is used in this example.
Syntax
1. INSERT OPENQUERY (MyLinkServer,
2. 'SELECT EmployeeName, EmployeeAddress
3. FROM Sample.EmployeeDetails')
4. VALUES ('Ravi', 'Noida');
5. GO
8.9.3 Inserts data into a remote table by using the OPENDATASOURCE function
Syntax
1. INSERT INTO OPENDATASOURCE('SQLNCLI',
2. 'Data Source= <server_name>; Integrated Security=SSPI')
3. EmployeeDetail (EmpName, EmpAddress)
4. VALUES ('Rahul', 'Noida63');
5. GO
96
8.9.4 Insert into an external table created using PolyBase
The INSERT can be used to Export data from SQL Server to Hadoop or Azure Storage.
First, we create an external table that points to the destination file or directory.
Then, use INSERT INTO to export data from a local SQL Server table to an external data
source. The INSERT INTO statement creates the destination file or directory if it does not
exist and the results of the SELECT statement are exported to the specified location in the
specified file format.
Syntax
1. CREATE EXTERNAL TABLE [dbo].[CustomerDetails] (
2. [FirstName] char(25) NOT NULL,
3. [LastName] char(25) NOT NULL,
4. [YearlyIncome] float NULL,
5. [MaritalStatus] char(1) NOT NULL
6. )
7. WITH (
8. LOCATION='/old_data/2009/customerdata.tbl',
9. DATA_SOURCE = HadoopHDP2,
10. FILE_FORMAT = TextFileFormat,
11. REJECT_TYPE = VALUE,
12. REJECT_VALUE = 0
13. );
14.
15. -- Export data: Move old data to Hadoop while keeping
16. -- it query-able via an external table.
17.
18. INSERT INTO CustomerDetails
19. SELECT T.* FROM Insured_Customers T1 JOIN CarSensor_Data T2
20. ON (T1.CustomerKey = T2.CustomerKey)
21. WHERE T2.YearMeasured = 2009 and T2.Speed > 40;
8.9.5 Insert data using the OPENROWSET function with BULK to bulk load data
into a table
The INSERT statement inserts rows from a data file into a table by specifying the
OPENROWSET function. The IGNORE_TRIGGERS table hint is specified for
performance optimization. For more examples, see Import Bulk Data by Using BULK
INSERT or OPENROWSET(BULK...) (SQL Server).
Syntax
1. INSERT INTO HumanResources.Department WITH (IGNORE_TRIGGERS) (Name, GroupName)
97
2. SELECT b.Name, b.GroupName
3. FROM OPENROWSET (
4. BULK 'C:SQLFilesDepartmentData.txt',
5. FORMATFILE = 'C:SQLFilesBulkloadFormatFile.xml',
6. ROWS_PER_BATCH = 15000)AS b ;
8.9.6 The TABLOCK hint to specify a locking method
The following specifies that an exclusive (X) lock is taken on the EmployeeDetail and is
held until the end of the INSERT statement.
Syntax
1. INSERT INTO Production.Location WITH (XLOCK)
2. (Name, CostRate, Availability)
3. VALUES ( N'Final Inventory', 15.00, 80.00);
8.9.7 Insert data using the SELECT option
The INSERT data shows how to insert multiple rows of data using an INSERT statement
with a SELECT option. The first INSERT statement uses a SELECT statement directly to
retrieve data from the source table and then to store the result set in
the EmployeeTitles table.
Syntax
1. CREATE TABLE EmployeeData
2. ( EmployeeKey INT NOT NULL,
3. LastName varchar(40) NOT NULL,
4. Title varchar(50) NOT NULL
5. );
6. INSERT INTO EmployeeData
7. SELECT EmployeeKey, LastName, Title
8. FROM EmployeeData
9. WHERE EndDate IS NULL;
8.10 Summary
In the next chapter, we will learn the basics of the SQL UPDATE statement and how it
works with SQL Statements.
98
9 SQL UPDATE Statement Tutorial
9.1 Introduction
In the previous chapter, we learned about INSERT INTO Statement in SQL and how to
use INSERT INTO Statement.
In this chapter, we will learn how to UPDATE SQL works and different options used with
the UPDATE statement.
The SQL UPDATE statement is used to modify the existing data records in a table. The
SQL UPDATE statement is used to update data from a database table or tables.
SQL UPDATE statement changes the data of one or more records in a table. Either all the
rows can be updated, or a subset may be chosen using a condition.
The SQL UPDATE statement has the following form SQL Update statement is used to
update records from an RDBMS( Relational Database Management System) data table.
The SQL UPDATE statement can be UPDATE records, UPDATE a set of records based
on a condition, filter records, sort records, group by records, and more.
Here are some of the use cases of the SQL UPDATE statement.
Note: The UPDATE statement is used to update records in a table! Notice the WHERE
clause in the UPDATE statement.
The WHERE clause specifies which record(s) that should be updated. If you omit the
WHERE clause, all records in the table will be updated!
Syntax
1. UPDATE table_name
2. SET column1 = value1, column2 = value2, ...
3. WHERE condition;
99
9.2.1 The UPDATE statement is typically in three parts:
1. The tableName to update
2. The SET clause which specifies the columns to update
3. The WHERE clause, which specifies which rows to include in the update open
Example
This is the WHERE clause that determines how many records will be updated
The following SQL statement will update the empName to "Manoj" for all records where
EmpCity is "Noida"
Syntax
1. USE Sample;
2. GO
3. UPDATE EmployeeDetail
4. SET EmpName='Manoj' Where EmpAddress='Noida'
5. GO
Example
100
UPDATE the WHERE clause
In this example, you can use the WHERE clause to specify which rows to update.
This statement updates the value in the EmpName of the EmployeeDetail
EmployeDetail table for all rows that have an existing value of 'Noida' in the
EmpAddress and have a value in theEmpName column that starts with EmpAddress
1. USE Sample;
2. GO
3. UPDATE EmployeeName.Name
4. SET EmpName = 'Rahul'
5. WHERE Name LIKE N'R' AND Address= 'Noida';
6. GO
The TOP Statement to limit the number of rows that are modified in an UPDATE
statement. When a TOP (n) clause is used with UPDATE, the update operation is
performed on a random selection of 'n' number of rows.
The following example updates the top 3 random rows in the EmployeDetails table
Syntax
1. UPDATE top (3) EmployeeDetail set EmpAddress = 1
Example
101
The TOP Statement applies updates in a meaningful chronology, you must use TOP
together with ORDER BY in a subselect statement.
The following example updates the TOP 3 EmpAddress.
102
9.6 UPDATE - Specifying a computed value
The following examples use computed values in an UPDATE statement. The example
doubles the value in the EmployeeName column for all rows in the EmployeeDetails table.
Syntax
1. UPDATE EmployeeDetail
2. SET EmpName = 'Rohan'
3. WHERE EmpId = 1;
Example
The Specifying Compound operators execute some operation and set an original value to
the result of the operation.
For example, if a variable @x equals 34, then @x += 2 takes the original value of @x,
adds 2, and sets @x to that new value (36).
Syntax
103
9.8 UPDATE table with data from another table
The UPDATE statement is performing a traditional update or updating one table with
data from another table.
Syntax
1. UPDATE table1
2. SET column1 = (SELECT expression1
3. FROM table2
4. WHERE conditions)
5. [WHERE conditions];
Example
104
The UPDATE rows in a remote target table by using a linked server or a rowset function
to reference the remote table.
The UPDATE statement has used the data in the file system file. We do not recommend
this method for streaming large amounts of data to a file. Use the appropriate Win32
interfaces. The following example replaces any text in the file record with the text Xray 1.
For more information,
1. UPDATE Name.EmployeeDetail
2. SET [Chart] = CAST('Xray 1' as varbinary(max))
3. WHERE [EmployeeDetail] = 2;
The UPDATE modifies a UDT by modifying the value of a registered property or public
data member of the user-defined type.
The expression supplying the value must be implicitly convertible to the type of the
property. The following example modifies the value of property X of user-defined type
Point.
105
1. UPDATE EmployeeDetail
2. SET EmpCity.X = 23.5
3. WHERE EmpName = 'Manoj';
This section demonstrates how to use tables and query hints to temporarily override the
default behavior of the query optimizer when processing the UPDATE statement.
CAUTION
The SQL SERVER query optimizer typically selects the best execution plan for a query,
we recommend that hints be used only as a last resort by experienced developers and
database administrators.
Note: Be careful when updating records. If you omit the WHERE clause, ALL records
will be updated!
Syntax
1. UPDATE table1
2. SET column1 = (SELECT expression1
3. FROM table2
4. WHERE conditions)
5. [WHERE conditions];
Example
106
9.15 Summary
In the next chapter, we will learn how to use SQL Replace Statement.
107
10 SQL Replace Statement
10.1 Introduction
In this chapter, we will learn about the REPLACE Statement in SQL and how to use the
REPLACE Statement in SQL to replace the data in the database.
The Replace statement is used to replace all occurrences of a specified string value with
another string value. The Replace statement inserts or replaces values in a table. Use the
Replace statement to insert new rows in a table and/or replace existing rows in a table.
Replace statement will search a table for a match based on any one of the unique keys
defined for that table.
A unique key is defined as either a Primary key constraint or a Unique constraint.
• If this statement does not find a match, it will insert a new row into the table.
• If this statement finds a match, it will replace that row with the column values
provided.
• If the Replace statement finds a match of more than one row, it will replace the
first row and it will delete all other matching rows in this table.
The Values clause must return a value for every column in the table column_name list in
that same order.
Replace statements can be used to merge two tables based on common column values.
The table referenced as Replace[INTO] is the primary table and must have at least one
column defined as a unique key to be used for matching. If columns referenced by the
"values" clause are not of the same data type as the columns defined in the Replace table,
automatic data type conversion is attempted.
Note
The Replace statement performs a replacement that is not case-sensitive.
108
The Replace statement also removes extra records that match query values, insert, update,
and delete privileges that are required for the target table.
Syntax
1. REPLACE ( string_expression , string_pattern , string_replacement )
So all occurrences of string_expression and/or string_pattern will be replaced with
string_to_replacement regardless of the case of string_expression and/or string_pattern or
string_replacement in the replace statement
Syntax
1. SELECT REPLACE('DEFULTSFFG','HIJ','KLM');
2. GO
This example selects and replaces all the data.
Example
The above query will select and replace the COLLATE Latin1_General BIN file to desk.
109
We can use Replace to insert or replace rows with or without the column list.
Syntax
1. CREATE TABLE Students
2. (Id int PRIMARY KEY identity(1,1),
3. StudentId int)
4. REPLACE INTO Students (Id,StudentId) VALUES (1);
The above query creates a table with the name "Students" and column name id as studentid,
and then replaces the data in the Students table where the value is one.
The following example uses the SQL replace function to replace multiple patterns of the
expression 3*[4+5]/{6-8}.
Syntax
1. SELECT REPLACE(REPLACE(REPLACE(REPLACE('2*[5+5]/{7-
8}', '[', '('), ']', ')'), '{', '('), '}', ')');
Example
We can see that the Replace function is nested and it is called multiple times to replace the
corresponding string as per the defined positional values within the SQL Replace function.
In this case, when you migrate a database, the dependent objects also need to be migrated;
for example, a linked server or specific column values of specific tables that reference a
renamed table.
110
Let’s get in-depth about the process of handling such changes dynamically using the SQL
Replace function with SQL. In one complex database migration project, the server has
multiple Linked Server configurations.
These linked servers were referred to and mentioned in multiple stored procedures. It is a
matter of fact to find and replace the stored procedure scripts but the intent is to automate
the entire process to make sure that we are not going to do any manual updates.
Let me take you through the simple steps.
Step 1
In this case, the search pattern is an employee. Also, you see that the custom escape
character is used to escape special characters ‘[‘and ‘]’ in the search pattern
Syntax
1. DECLARE @searchPattern VARCHAR(100)= 'EmployeeDetails';
2. SELECT DISTINCT
3. 'sp_helptext '''+OBJECT_SCHEMA_NAME(id)+'.'+OBJECT_NAME(id)+''' '
4. FROM syscomments
5. WHERE TEXT LIKE '%'+REPLACE(REPLACE(@searchPattern, ']', '\]'), '[', '\[')+'%' ESCAPE '\'
The above query declares searchPattern column name from EmployeeDetails table and
select DISTINCT sp_helptext for OBJECT_SCHEMA_NAME column name In
syscomments table and where TEXT contains the searchPattern column for % and '\'
statement, which is further arranged according to sp_helptext and
the OBJECT_SCHEMA_NAME(id) and the OBJECT_NAME(id) function
111
10.4.1 How to perform a simple update to change the keyword create to the Alter
table
This way the script is ready to execute on the target database. In some cases, you just need
to retain the script. That is still fine but don’t run this step.
Syntax
1. UPDATE @sp_EmployeeDetails
2. SET
3. storedProcedureText = REPLACE(REPLACE(storedProcedureText, 'CREATE PROCEDURE', 'ALTER
PROCEDURE'), @searchpattern, @replacestring);
4. SELECT storedProcedureText
5. FROM @sp_EmployeeDetails;
6.
This above query updates the sp_EmployeeDetails from EmployeeDetails table Name
hence setting the storeProcedureText to Replace the storeProcedureText and selecting the
storedProceduretext from EmployeeDetails table.
10.5 Summary
In the next chapter, we will learn how to work with the SQL DROP statement.
112
11 SQL SELECT GROUP BY Statement
11.1 Introduction
In this chapter, we will learn about SELECT- GROUP BY SQL Statement and its uses into
the SQL.
The SQL GROUP BY clause is used in a SELECT statement to collect data across multiple
records and group the results by one or more columns.
The SQL GROUP BY returns only one result per group of data the GROUP BY clause
always follows the where clause and the GROUP BY clause always precedes the ORDER
BY statement
A SELECT statement clause that divides the query result into groups of rows, usually for
the purpose of performing one or more aggregations on each group.
Important points
• GROUP BY statement is used with the SELECT statement
• In the query, GROUP BY statement is placed after the WHERE clause
• In the query, GROUP BY clause is placed before ORDER BY clause if used any
Syntax
1. SELECT column_name(s)
2. FROM table_name
3. WHERE condition
4. GROUP BY column_name(s)
This clause works with the select specific list of items, and we can use HAVING, and
ORDER BY clauses. group by clause always works with an aggregate function like MAX,
MIN, SUM, AVG, COUNT
Syntax
1. Create table CarSale
2. (
113
3. Id int primary key identity(1,1) ,
4. Model varchar(200),
5. Price money
6. )
7.
8. Insert into CarSale values('Baleno', 900000),('M551', 950000),('M551', 950000),('L551', 95
0000),
9. ('L538', 650000),('L538', 900000),('BWW', 8000000),('8530', 450000),('L530',380000), ('L54
5', 280000)
Example
This function returns the maximum value of the numeric column of specified criteria
Syntax
1. Select max(Price) As 'MaximumCostOfModel' from CarSale
Example
114
11.3.2 MIN()
This function returns the minimum of the numeric column of specified criteria
Syntax
1. Select Min(Price) As 'MinimumCostOfModel' from CarSale
Example
11.3.3 SUM()
This function returns the total sum of a numeric column of specified criteria
Syntax
1. Select SUM(Price) As 'SumCostOfAllModel' from CarSale
Example
115
11.3.4 AVG()
the function returns the average value of a numeric column of specified criteria
Syntax
1. Select AVG(Price) As 'AverageCostOfModel' from CarSale
Example
11.3.5 COUNT()
This function returns the number of rows that match specified criteria
Syntax
1. Select Count(Price) As 'TotalVehicleModels' from CarSale
Example
116
11.4 Distinct clause
The distinct clause is used to filter unique records out of the duplicate records that satisfy
the query criteria
Syntax
1. Select Distinct(Model), Price from CarSale
Example
117
The SQL GROUP BY statement list the number of Employee in each EmployeeId, sorted
high to low
Syntax
1. SELECT COUNT(EmployeeId), EmployeeName
2. FROM EmployeeDetails
3. GROUP BY EmployeeName
4. ORDER BY COUNT(EmployeeID) DESC;
Example
118
11.6 SELECT GROUP BY clause with multiple tables
The SELECT GROUP BY statement retrieves the number of employees for each
EmployeeName from the EmployeeDetails table joined to the EmployeeDetail table
This example uses a sample.
Syntax
1. SELECT EmployeeName
2. FROM EmployeeDetails
3. INNER JOIN EmployeeDetail
4. ON EmployeeDetails.EmployeeID=EmployeeDetail.EmpId GROUP BY EmployeeName ORDER BY Employee
Name;
Example
The SELECT GROUP BY statement retrieves the total EmployeeDetails by using the
function. The same expression must be present in both the SELECT list and GROUP BY
clause statement.
Syntax
1. SELECT COUNT(EmployeeID), EmployeeName
2. FROM EmployeeDetails
3. GROUP BY EmployeeName;
Example
119
11.8 SELECT GROUP BY statement with a HAVING clause
The SELECT GROUP BY statement uses the HAVING clause to specify which of the
groups generated in the GROUP BY clause should be included in the result set.
Syntax
1. SELECT COUNT(EmployeeID)EmployeeAdress
2. FROM EmployeeDetails
3. GROUP BY EmployeeName
4. HAVING COUNT(EmployeeID)> 1;
Example
120
11.9 SELECT GROUP BY basic use
The SELECT GROUP BY clause finds the total EmployeeID, EmployeeName for
EmployeeDetails.
Syntax
1. SELECT COUNT(EmployeeID), EmployeeName from EmployeeDetails GROUP BY EmployeeName
Example
The SELECT the DISTRIBUTED_AGG query hint to force the appliance to shuffle the
table on the EmployeeDetails column before performing the aggregation.
Syntax
1. SELECT COUNT(EmployeeID), EmployeeName , EmployeeAddress
2. FROM EmployeeDetails
3. GROUP BY EmployeeName WITH (DISTRIBUTED_AGG), EmployeeAddress
4. ORDER BY EmployeeName DESC
Example
121
11.11 SELECT Variations for GROUP BY statement
The SELECT variations for GROUP BY statement is the select list has no aggregations,
each column in the select list must be included in the GROUP BY list. computed columns
in the select list can be listed, but are not required, in the GROUP BY list. These are
examples of syntactically valid SELECT statements:
Syntax
1. SELECT EmployeeName, EmployeeAddress FROM EmployeeDetails GROUP BY EmployeeName, EmployeeA
ddress;
2. SELECT EmpName FROM EmployeeDetail GROUP BY EmpName, EmpAddress;
Example
122
11.12 SELECT GROUP BY with multiple GROUP BY
expressions
The following example groups result using multiple GROUP BY EmployeeName If,
within each EmployeeId group
Syntax
1. SELECT COUNT(EmployeeId), EmployeeName
2. FROM EmployeeDetails
3. GROUP BY EmployeeName
4. ORDER BY COUNT(EmployeeID) DESC;
Example
123
11.13 SELECT GROUP BY clause with a HAVING clause
The GROUP BY HAVING clause uses the clause to specify the groups generated in the
GROUP BY clause that should be included in the result set
Syntax
1. SELECT COUNT(EmployeeId), EmployeeName
2. FROM EmployeeDetails
3. GROUP BY EmployeeName
4. ORDER BY COUNT(EmployeeID) DESC;
Example
11.14 Summary
In the next chapter, we will learn the basics of the SQL SELECT HAVING statement.
124
12 SQL SELECT HAVING Statement
12.1 Introduction
In this chapter, we will learn about SQL SELECT- HAVING Statement in SQL with
various options.
SQL Having is a statement that specifies a search condition for a group or an aggregate.
Having can be used only with the select statement. Having is typically used with a group
by clause. When a group by is not used, there is an implicit single, aggregated group.
The Having statement enables you to specify conditions that filter which group results
appear in the results.
The Where clause places conditions on the selected columns, whereasthe HAVING clause
places conditions on groups created by the Group By the clause in Having a statement.
Having statement filters records that work on summarized Group By results. The Having
Statement applies to summarized group records, whereas Where applies to individual
records, only the groups that meet the Having criteria will be returned. Having requires
that a Group by clause is the present statement. Where and Having can be in the same
query in a SQL Statement.
A Having statement is like a Where clause, but applies only to groups as a whole (that is,
to the rows in the result set representing groups), whereas the Where clause applies to
individual rows. A query can contain both a Where clause and a Having clause in that case.
• The Where statement is applied first to the individual rows in the tables or table-
valued objects in the Diagram pane. Only the rows that meet the conditions in the
Where clause are grouped.
• The Having statement is then applied to the rows in the result set, only the groups
that meet the Having conditions appear in the query output. You can apply a
125
Having clause only to columns that also appear in the Group By statement or in an
aggregate function.
The Having clause was added to SQL because the where keyword could not be used with
aggregate functions in SQL Select statement.
Syntax
1. SELECT column_name(s)
2. FROM table_name
3. WHERE condition
4. GROUP BY column_name(s)
5. HAVING condition
6. ORDER BY column_name(s);
The following SQL statement lists the OrderId, OrderName in OrderDetails. Only include
OrderId with more than 1 OrderDetails.
Syntax
1. SELECT COUNT(OrderId), OrderName
2. FROM OrderDetails
3. GROUP BY OrderName
4. HAVING COUNT(OrderId) >1;
Example
The following SQL statement lists the OrderId, OrderName in OrderDetails, sorted high
to low (only include OrderId with more than 2 OrderDetails).
Syntax
1. SELECT COUNT(OrderId), OrderName
2. FROM OrderDetails
3. GROUP BY OrderName
4. HAVING COUNT(OrderId) >2
5. ORDER BY COUNT(OrderName) DESC;
126
Example
The following SQL statement lists the employees that have registered more than 10 orders.
Syntax
1. SELECT OrderName COUNT(OrderId) as TotalOrders
2. FROM OrderDetails
3. Inner Join EmployeeDetail on Orderdetails.OrderName=EmployeeDetail.EmpId
4. GROUP BY OrderName
5. HAVING COUNT(EmpId) >10
The following SQL statement lists if the Employees "Davolio" or "Noida" have registered
more than 10 orders.
Syntax
1. SELECT OrderName, OrderAddress COUNT(OrderId) AS NumberOfOrders
2. FROM OrderDetails
3. INNER JOIN EmployeeDetail ON Orders.EmpID = Employees.EmpName
127
4. WHERE EmpName = 'Davolio' OR EmpAddress = 'Noida'
5. GROUP BY LastName
6. HAVING COUNT(OrderId) > 10;
12.5 Summary
In the next chapter, we will learn how to use a SQL Select Distinct statement with various
options.
128
13 SQL SELECT DISTINCT Statement
13.1 Introduction
In this chapter, we will learn about the basics of the SQL SELECT DISTINCT statement
129
13.3 SELECT COUNT DISTINCT statement
The SELECT DISTINCT COUNT() function returns the number of rows that matches a
specified criteria
The following SQL statement lists the number of different (DISTINCT)EmployeeDetails
EmpId
Syntax
1. SELECT COUNT(DISTINCT EmpId) FROM EmpDetail;
Example
The AVG DISTINCT () function returns the average value of a numeric column
The following SQL statement lists the number of different (DISTINCT)EmployeeDetails
EmpId
Syntax
1. SELECT AVG(DISTINCT EmpId)
2. FROM EmployeeDetail
3. WHERE EmpId= EmpId
Example
130
13.5 SELECT MAX DISTINCT statement
The SELECT MAX DISTINCT function returns the largest value of the selected column
Syntax
1. SELECT MAX(DISTINCT EmpId)
2. FROM EmployeeDetail
3. WHERE EmpId= EmpId
Example
NOTE
This example above will not work in Firefox and Microsoft edge! Because
COUNT(DISTINCT column_name) is not supported in Microsoft access databases
Firefox and Microsoft Edge is using Microsoft access in our examples.
Here is the workaround for ms access.
131
Syntax
1. SELECT DISTINCT EmpName,EmpAddress,EmpCity FROM EmployeeDetail Where EmpId=5
Example
The following SQL statement selects all (including the duplicates) values from the
EmpName column in the EmployeeDetail table
Syntax
1. SELECT * FROM EmployeeDetail
Example
13.8 Summary
In the next chapter, we will learn the basics of the SQL TOP statement.
132
133
14 Table In SQL
14.1 Introduction
In this chapter, we will learn about SQL Table. In this, we will discuss about how to Create,
Insert, Select, Update, and Delete the table in SQL.
The CREATE TABLE statement is used to create a new table in a database. In that table,
if you want to add multiple columns, use the below syntax.
Syntax
1. CREATE TABLE table_name (
2. column1 datatype,
3. column2 datatype,
4. column3 datatype,
5. ....
6. );
The column parameters specify the names of the columns of the table.
The data type parameter specifies the type of data the column can hold (e.g. varchar,
integer, date, etc.).
Create Table Example
1. CREATE TABLE Employee(
2. EmpId int,
3. LastName varchar(255),
4. FirstName varchar(255),
5. Address varchar(255),
6. City varchar(255)
7. );
The EmpId column is of type int and will hold an integer.
The LastName, FirstName, Address, and City columns are of type varchar and will hold
characters and the maximum length for these fields is 255 characters.
134
The INSERT INTO statement is used to insert new records in a table.
It is possible to write the INSERT INTO statement in two ways.
Syntax
The first way specifies both the column names and the values to be inserted.
If you are adding values for all the columns of the table, then no need to specify the column
names in the SQL query. However, make sure that the order of the values is in the same
order as the columns in the table.
1. INSERT INTO table_name (column1, column2, column3, ...)
2. VALUES (value1, value2, value3, ...);
3.
4. '2nd way
5. INSERT INTO table_name
6. VALUES (value1, value2, value3, ...);
Example
Insert value in a 1st way. The column names are used here
1. INSERT INTO Employee (EmpId,LastName,FirstName,ADDRESS,City)
2. VALUES (1, 'XYZ', 'ABC', 'India', 'Mumbai' );
3. INSERT INTO Employee (EmpId,LastName,FirstName,ADDRESS,City)
4. VALUES (2, 'X', 'A', 'India', 'Pune' );
Insert value in a 2nd way.
1. INSERT INTO Employee
2. VALUES (3, 'XYZ', 'ABC', 'India', 'Mumbai' );
135
2.
3. Select * from Employee;
It is the WHERE clause that determines how many records will be updated.
1. UPDATE Employee
2. SET City='Pune'
The DELETE statement is used to delete existing records in a table for a particular Record.
Syntax
1. DELETE FROM table_name WHERE condition;
Example
1. DELETE FROM Employee WHERE EmpId=1;
In Employee table EmpId = 1 record gets deleted.
136
It is possible to delete all rows in a table without deleting the table. This means that the
table structure, attributes, and indexes will be intact,
1. DELETE FROM table_name;
2.
3. DELETE From Employee ;
When the above query is executed, only table Data gets deleted.
14.9 Summary
In this chapter, we learned about how to Create, Insert, Select, Update, and Delete the table
in SQL.
137
15 DROP in SQL
15.1 INTRODUCTION
In this tutorial, I am going to explain about SQL DROP Statements with examples. This
article covers the following topics.
1. Introduction to the Drop Statement
2. SQL DROP Database
3. SQL DROP Table
4. SQL DROP Index Statement
5. SQL ALTER Table Statement
6. Conclusion
In this section, I will explain how to use SQL DROP DATABASE statement to delete a
database.
Dropping or deleting a SQL database is easy. The drop statement command is used when
we have to no longer use one of the SQL databases on the server. It will remove
permanently and is very easy to drop an existing SQL table. But we need to be very careful
while deleting any existing database because data lost will not be recovered after deleting
a database.
Here, we use the following syntax to drop the database on the server.
Syntax
DROP DATABASE <Database_name>;
Example
1. DROP DATABASE CSharpCornerdb;
138
Note:
If you try to drop a database that does not exist in the server, then SQL will issue an error.
To prevent this, you can use the following syntax.
Syntax
DROP DATABASE [IF EXISTS] <Database_name>;
Example
1. DROP DATABASE IF EXISTS CSharpCornerdb;
In this section, I will explain how to use SQL DROP TABLE statement to delete a table
from a database.
DROP TABLE statement is used to remove one or more tables from the database. We must
have the DROP advantages for each table. All table data and the table definition are
removed. DROP TABLE permanently removes the table definition, all of its partitions,
and all of the data which was stored in those partitions.
139
The DROP TABLE statement is used to drop the table permanently. Here, we use the
following syntax to drop tables from the database.
Syntax
DROP TABLE [IF EXISTS] <table_name>;
Without wasting time, let’s take some examples.
15.3.1 DROP a Single Table
15.3.2 DROP Multiple Tables
First, we have to create a few dummy tables for testing purposes.
1. CREATE TABLE GetResortsDetails(
2. R_ID INT PRIMARY KEY AUTO_INCREMENT,
3. R_Name VARCHAR(50),
4. R_Address VARCHAR(200)
5. );
6.
7. CREATE TABLE GetCompanyDetails(
8. C_ID INT,
9. C_Name VARCHAR(50),
10. C_Address VARCHAR(200),
11. C_Description VARCHAR(250),
12. C_BusinessModel VARCHAR(50)
13. );
Now, execute the DROP TABLE statement to drop both the tables from the database.
1. DROP TABLE GetResortsDetails, GetCompanyDetails;
140
1. DROP TABLE GetCompanyDetails;
To prevent this, use the following syntax when dropping the table.
Syntax
DROP TABLE IF EXISTS <table_name>;
Example
1. DROP TABLE IF EXISTS GetCompanyDetails;
The DROP INDEX Statement is used to delete an index in a table. Use the following below
syntax to do this.
Syntax
ALTER TABLE <table_name>
DROP INDEX <index_name>;
Example
First, we have to create a dummy table without any index. Let’s see.
141
1. CREATE TABLE GetCompanyDetails(
2. C_ID INT,
3. C_Name VARCHAR(50),
4. C_Address VARCHAR(200),
5. C_Description VARCHAR(250),
6. C_BusinessModel VARCHAR(50)
7. );
Now, you can check the result by typing the following command.
1. DESCRIBE GetCompanyDetails;
In this section, I will explain you how to use SQL DROP COLUMN statement to drop a
column from a table.
Syntax
ALTER TABLE <table_name>
142
DROP COLUMN <column_name>;
Example
First, we have to create a dummy table for testing purposes. Now, let’s see.
1. DROP TABLE IF EXISTS GetCompanyDetails;
2.
3. CREATE TABLE GetCompanyDetails(
4. C_ID INT PRIMARY KEY auto_increment,
5. C_Name VARCHAR(50),
6. C_Address VARCHAR(200),
7. C_Description VARCHAR(250),
8. C_BusinessModel VARCHAR(50),
9. C_Revenue BIGINT
10. );
143
1. DESCRIBE GetCompanyDetails;
Note
All table data and the table definition can be removed, so be careful with DROP statement.
15.6 CONCLUSION
In this article, I have discussed the concept of SQL DROP Statements with various
examples.
I hope you enjoyed this article. Follow C# Corner to learn more new and amazing things
about SQL.
Thanks for reading this article!
144
16 SQL TOP Statement
16.1 Introduction
In this chapter, we will learn about SQL TOP Statement and how TOP Statement is used
with different options in SQL.
The SQL TOP statement is used to retrieve records from one or more tables in a database
and limit the number of records returned based on a fixed value or percentage.
The SQL TOP statement limits the rows returned in a query result set to a specified
number of rows or percentage of rows in SQL Server.
When you use TOP with the ORDER BY clause, the result set is limited to the
first N number of ordered rows. otherwise, TOP returns the first N number of rows in an
#ff0000 order.
SQL TOP statement uses this clause to specify the number of rows returned from a
SELECT statement. or, use TOP to specify the rows affected by an INSERT, UPDATE,
MERGE, or DELETE statement.
Syntax
1. SELECT TOP (top_value) [ PERCENT ]
2. expressions
3. FROM tables
4. WHERE conditions]
5. ORDER BY expression [ ASC | DESC ]];
The following examples use a constant value to specify the number of employees that are
returned in the query result set. In the first example, the first 10 #ff0000 rows are returned
because an ORDER BY clause isn't used.
145
In the second example, an ORDER BY clause is used to return the top 10 OrderName.
Syntax
1. USE sample ;
2. GO
3. -- Select the first 10 random employees.
4. SELECT TOP(10)EmpName
5. FROM EmployeeDetail;
6. GO
7. --Select the first 10 order Orderdetails most recently.
8. SELECT TOP(10) OrderName, orderAddress, OrderDate
9. FROM OrderDetails
10. ORDER BY OrderId DESC;
11. GO
Example
147
16.6 Using with Ties to include rows that match the values in the
last row
The following example gets the top 10 percent of all OrderDetails with the highest and
returns them in descending order according to their orderderails. Specifying with Ties
ensures that OrderName is with OrderDetails.
Syntax
1. USE sample
2. GO
3. SELECT TOP(10) PERCENT WITH TIES pp.OrderName, e.EmpName, e.EmpAddress
4. FROM OrderDetails AS pp
5. INNER JOIN EmployeeDetail AS e
6. ON pp.OrderId = e.EmpId
7. INNER JOIN EmployeeDetails class="keyword">AS r
8. ON r.EmployeeID = e.EmpId
9. ORDER BY OrderId DESC;
10. GO
Example
148
16.7 Using TOP to limit the number of rows deleted
When you use a TOP (n) clause with DELETE, the delete operation is done on an
undefined selection of n number of rows. That is, the DELETE statement chooses any (n)
number of rows that meet the criteria defined in the WHERE clause. The following
example deletes 20 rows from the OrderDetails table that have due dates earlier than July
1, 2019.
Syntax
1. USE sample ;
2. GO
3. DELETE TOP (20)
4. FROM OrderDetails
5. WHERE OrderDate < '20190701';
6. GO
If you want to use TOP to delete rows in a meaningful chronological order, use TOP with
ORDER BY in a subselect statement. The following query deletes the 10 rows of
the OrderDetails table that have the earliest due dates.
To ensure that only 10 rows are deleted, the column specified in the subselect statement
(OrderId) is the primary key of the table. Using a non-key column in the subselect
149
statement may result in the deletion of more than 10 rows if the specified column contains
duplicate values.
Syntax
1. USE sample;
2. GO
3. DELETE FROM OrderDetails
4. WHERE OrderId IN
5. (SELECT TOP 10 EmployeeID
6. FROM EmployeeDetails
7. ORDER BY OrderDate class="keyword">ASC);
8. GO
The following example creates the table EmployeeSales and inserts the name and year-to-
date sales data for the top five employees from the EmployeeSales. The
INSERT statement chooses any five rows returned by the SELECT statement that meets
the criteria defined in the WHERE clause.
The output clause displays the rows that are inserted into the EmployeeSales table Notice
that the ORDER BY clause in the SELECT statement isn't used to determine the top five
employees.
Syntax
1. USE sample
2. GO
3. IF OBJECT_ID ('OrderDetails', 'U') IS NOT NULL
4. DROP TABLE dbo.EmployeeSales;
5. GO
6. CREATE TABLE dbo.EmployeeSales
7. ( EmployeeID nvarchar(11) NOT NULL,
8. LastName nvarchar(20) NOT NULL,
9. FirstName nvarchar(20) NOT NULL,
10. YearlySales money NOT NULL
11. );
12. GO
13. INSERT TOP(5)INTO dbo.EmployeeSales values(1,'Gupta','Singh',2008)
14. SELECT sp.OrderId, sp.OrderName,sp.orderAddress
15. FROM OrderDetails AS sp
16. INNER JOIN EmployeeDetail AS c
17. ON sp.OrderId = c.EmpId
150
18. WHERE sp.OrderId > 250000.00
19. ORDER BY sp.OrderId DESC;
20. GO
If you want to use TOP to insert rows in a meaningful chronological order, use TOP with
ORDER BY in a subselect statement. The following example shows how to do this.
The output clause displays the rows that are inserted into the OrderDetails table. Notice
that the top five employees are now inserted based on the results of the ORDER BY clause
instead of undefined rows.
Syntax
1. SELECT TOP(10) PERCENT WITH TIES pp.OrderName, e.EmpName, e.EmpAddress
2. FROM OrderDetails AS pp
3. INNER JOIN EmployeeDetail AS e
4. ON pp.OrderId = e.EmpId
5. INNER JOIN EmployeeDetails AS r
6. ON r.EmployeeID = e.EmpId
7. ORDER BY OrderId DESC;
8. GO
The following example uses the TOP clause to update rows in a table. When you use a
TOP (n) clause with UPDATE, the update operation runs on an undefined number of rows.
That is, the UPDATE statement chooses any (n) number of rows that meet the criteria
defined in the WHERE clause. The following example assigns 10 OrderDetails from
OrderId to another.
Syntax
1. USE sample ;
2. UPDATE TOP (10) OrderDetails
3. SET OrderId = 31
4. WHERE OrderId = 2;
5. GO
If you have to use TOP to apply updates in a meaningful chronology, you must use TOP
together with ORDER BY in a subselect statement. The following example updates the
orderId 10 orderDetails with the orderId.
Syntax
151
1. UPDATE OrderDetails
2. SET orderAddress = OrderId
3. FROM (SELECT TOP 10 OrderName FROM OrderDetails
4. ORDER BY OrderDate ASC) AS th
5. WHERE OrderId = OrderId;
6. GO
16.10 Summary
In the next chapter, we will learn how to use a SQL BETWEEN statement with various
options.
152
17 SQL BETWEEN Statement
17.1 Introduction
In this chapter, we will how to use a SQL Between statement with various options.
The SQL Between statement selects values within a given range. The values can be
numbers, text, or dates.
It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
The SQL Between condition will return the records where expression is within the range
of value1 and value2.
The Between statement is inclusive -- begin and end values are included.
SQL Between operator is almost like SQL IN operators used in a sequential manner.
The values defined as part of the Between range are inclusive; i.e., the values that are
mentioned in the range are included at the start and end values.
Let’s discuss in detail about the Between operator,
Syntax
1. SELECT * FROM EmployeeDetail
2. WHERE EmpId BETWEEN 1 AND 4
Example
153
17.3 Using Between in SQL
The following example returns information about the database roles in adatabase. The first
query returns all the roles, and the second example usesthe Between clause to limit the
roles to the specified EmpId values.
Syntax
1. SELECT principal_id, name
2. FROM sys.database_principals
3. WHERE type = 'R'
4. SELECT principal_id, name
5. FROM sys.database_principals
6. WHERE
7. AND principal_id BETWEEN 16385 AND 16390;
8. GO
Example
154
17.4 Using (>) and (<) instead of Between values
The following example uses greater than (>) and less than (<) operators and, because these
operators are not inclusive, return one rows instead of ten that were returned in the previous
example
Syntax
1. SELECT EmpId,EmpName
2. FROM EmployeeDetail e
3. JOIN EmployeeDetails ep
4. ON e.EmpId = ep.EmployeeID
5. WHERE ep.EmployeeID > 4 >AND ep.EmployeeID < 30
6. ORDER BY ep.EmployeeName;
7. GO
Example
The following example finds all rows outside a specified range of 27 through 30.
Syntax
1. SELECT EmpId,EmpName
2. FROM EmployeeDetail e
3. JOIN EmployeeDetails ep
4. ON e.EmpId = ep.EmployeeID
5. WHERE e.EmpId NOT BETWEEN 27 AND 30
6. ORDER BY EmpAddress ;
7. GO
Example
155
17.6 Using Between with datetime values
The following SQL statement retrieves rows in which datetime values are
Between '2019/04/11' and '2019/07/11' inclusive
Syntax
1. SELECT OrderName, orderAddress, OrderDate
2. FROM OrderDetails
3. WHERE OrderDate BETWEEN '20190411' class="op">AND '20190711';
Example
156
An operator allows you to easily test if the expression matches any value in the list of
values. It can be used to remove the need for multiple OR conditions in SELECT, INSERT,
UPDATE, or DELETE. You can also use NOT IN to exclude the rows in your list.
The following SQL statement selects all OrderDetails with an orderId Between 4 and 5. In
addition do not show pr with an orderId of 1,2, or 3.
Syntax
1. SELECT* FROM OrderDetails
2. WHERE OrderId BETWEEN 4 AND 5
3. AND NOT OrderId IN (1,2,3);
Example
The following example selects orderDetails with a orderName Between apple and banana.
Syntax
1. SELECT *
2. WHERE OrderName BETWEEN 'Apple' AND 'Banna'
3. ORDER BY orderAddress
Example
157
17.9 Using not Between text values
The following SQL statement selects all products with an orderName BETWEEN apple
and banana.
Syntax
1. SELECT * FROM OrderDetails
2. WHERE OrderName NOT BETWEEN 'Apple' AND 'Banna'
3. ORDER BY orderAddress
Example
17.10 Summary
In the next chapter, we will learn how to use a SQL EXISTS statement with various
options.
158
18 SQL Exists Statement
18.1 Introduction
In this chapter, we learned how to use a SQL Select Exists statement with various options.
SQL or sequence query language is a mechanism that we use to interact with the database.
SQL Exists statement specifies a subquery to test for the existence of row(s), or in other
words, the SQL Exists statement is used to test for the existence of any record in a
subquery.
The SQL Exists statement returns true if the subquery returns one or more records.
SQL Exists statement is a restricted Select statement The "into" Keyword is not allowed
to be used the SQL Exists statement.
Syntax
1. SELECT column_name(s)FROM table_nameWHERE EXISTS(SELECT column_name FROM table_name WHERE
condition);
Note
• A sample database has been attached for your reference. You can download it, or
can create your own database.
• I am using Microsoft SQL Server 2019, you can use any other SQL providers.
18.2.1 How to use Null statement in a subquery to still return a result set?
The following example returns a result set with Null specified in the subquery and which
evaluates to true by using Exists statement. You can see that although we are using Null,
we are still getting an output.
Syntax
1. --Uses sample
2. SELECT OrderID,OrderName, orderAddress From OrderDetail
3. Where EXISTS (SELECT NULL)
159
4. ORDER BY OrderName ASC
Output
The output of the above command will be data from column names OrderID, OrderName,
OrderAddress, if and only if data is present in all mentioned columns, in ascending order
and OrderName.
The following example compares two queries that are semantically equivalent, i.e
Programmatically they should result in the same output. The first query uses SQL Exists
statement and the second query uses SQL In a statement.
Syntax
1. -- Uses sample
2. SELECT a.OrderName, a.orderAddress,a.OrderDate
3. FROM OrderDetails AS a
4. WHERE EXISTS
5. (SELECT *
6. FROM OrderDetails AS b
7. WHERE a.OrderId = b.OrderId
8. AND a.OrderName = 'Mango');
9. GO
Output
160
The output of the above command will be data from OrderName, OrderAddress,
OrderDate if and only OrderName is 'Mango' and OrderId is the same.
The following example shows two queries to find stores whose name is the same name as
a vendor. The first query uses Exists and the second uses "=Any" statement.
SQL any operator returns if any of the subquery values meet the condition.
Syntax
1. -- Uses sample
2. SELECT DISTINCT s.OrderName
3. FROM OrderDetails AS s
4. WHERE EXISTS
5. (SELECT *
6. FROM EmployeeDetail AS v
7. WHERE s.OrderName = v.EmpName) ;
8. GO
The above query will distinguish OrderName from the OrderDetails table and select all
data in the EmployeeDetail table and where the Column name is orderName and
EmpName in this statement, if sub-query returns anything, the subquery will return data
from EmployeeDetails if OrderName is the same EmpName.
The following query uses ="Any"
Syntax
161
1. -- Uses sample
2. SELECT DISTINCT s.EmpName
3. FROM EmployeeDetail AS s
4. WHERE s.EmpName = ANY
5. (SELECT v.orderAddress
6. FROM OrderDetails AS v ) ;
7. GO
The following query will return distinct values from EmpName, and from the
EmployeeDetail table if the subquery returns data. The subquery will return data if the
OrderDetails table has some not null values.
The following example shows queries to find employees of departments that start with P.
Syntax
1. -- Uses sample
2. SELECT p.OrderName, p.orderAddress
3. FROM OrderDetails AS p
4. JOIN EmployeeDetail AS e
5. ON e.EmpId = p.OrderId
6. WHERE EXISTS
7. (SELECT *
8. FROM OrderDetails AS d
9. JOIN Employee_Details AS edh
10. ON d.OrderId = edh.OrderDate
11. WHERE e.EmpId = edh.OrderName
12. AND d.OrderName LIKE 'T%');
13. GO
The following query will return OrderAddress from the OrderDetails table and we are
using Join to ease our task of getting identical data. You can read about join on Csharp
Corner.
The subquery will return data if OrderName starts with "T" and EmpId and OrderName
are the same.
The following query uses In.
Syntax
1. -- Uses sample
2. SELECT p.OrderName, p.orderAddress
3. FROM OrderDetails AS p
4. JOIN EmployeeDetail AS e
5. ON e.EmpId = p.OrderId
162
6. JOIN EmployeeDetail AS edh
7. ON e.EmpId = edh.EmpId
8. WHERE edh.EmpId IN
9. (SELECT OrderId, OrderName, orderAddress
10. FROM OrderDetails
11. WHERE OrderName LIKE 'P%'); GO
The following query will return orderName, orderAddress from orderDetails table and we
are using Join to case our task of getting identical data. The subquery will return
OrderName, OrderAddress table if OrderName starts with"P"
The Not Exists statement works the opposite of Exists. The Where clause in Not Exists is
satisfied if no rows are returned by the subquery.
The following example finds EmployeeDetail who are not in departments which have
names that start with P.
Syntax
1. -- Uses sample
2. SELECT p.OrderName, p.orderAddress
3. FROM OrderDetails AS p
4. JOIN EmployeeDetail AS e
5. ON e.EmpId = p.OrderId
6. WHERE NOT EXISTS
7. (SELECT *
8. FROM OrderDetails AS d
9. JOIN EmployeeDetail AS edh
10. ON d.OrderId = edh.EmpId
11. WHERE e.EmpId = edh.EmpId
12. AND d.OrderName LIKE 'P%')
13. ORDER BY EmpName,OrderName
The above query will return orderName, orderAddress from orderDetails table and we are
using Join to case our task of getting identical data. The subquery will return OrderName,
OrderAddress table if OrderName starts with P.
The following example finds rows in the OrderDetails table where the OrderName
and EmpId does not match any entries in the EmployeeDetail table.
Syntax
163
1. -- Uses sample
2. SELECT a.OrderName, a.orderAddress
3. FROM OrderDetails AS a
4. WHERE NOT EXISTS
5. (SELECT *
6. FROM EmployeeDetail AS b
7. WHERE (a.OrderName = b.EmpId) AND (a.orderAddress = b.EmpAddress));
The above query will return OrderName, OrderAddress from OrderDetails if the subquery
does not result in any output.
The above example identifies whether any rows in the OrderName,OrderAddress table
could be matched to rows in the EmployeeDetail table.
18.5 Summary
In the next chapter, we will learn how to use a SQL INDEX statement with various options.
164
19 SQL Index Statement
19.1 Introduction
In this chapter, we learned how to use a SQL Create Index statement with various options.
The SQL Create statement is used to create indexes in tables. Indexes are used to retrieve
data from indexes rather than otherwise. Users can not see indexes, they are only used to
speed up searches/queries in SQL.
It creates an index on a table. Duplicate values are allowed. It creates a relational index on
a table or view. It's also called a rowstore index because it is either a clustered or
nonclustered B-tree index. You can create a rowstore index before there is data in the table.
Use a rowstore index to improve query performance, especially when the queries select
from specific columns or require values to be sorted in a particular order in database tables.
Note
SQL Data Warehouse and Parallel Data Warehouse currently do not support unique
constraints. Any examples referencing unique constraints are only applicable to SQL
Server and SQL Database.
Syntax
1. CREATE INDEX index_name
2. ON table_name (column1, column2, ...);
The following examples create a nonclustered index on the OrderId column of the
OrderDetails table.
Syntax
1. CREATE INDEX ProductId ON orderDetails (OrderId);
165
2. CREATE INDEX ProductId ON OrderDetails (OrderId DESC, OrderName ASC, OrderAddress DESC);
The following example creates a nonclustered composite index on the OrderName and
OrderAddress columns of the OrderDetails table.
Syntax
1. CREATE NONCLUSTERED INDEX ProductId ON OrderDetails (OrderName, OrderAddress);
The following example creates index IX_FF with two columns from the OrderDetails table
The next statement rebuilds the index with one more column and keeps the existing name.
Syntax
1. CREATE INDEX ProductOrder ON OrderDetails (OrderName ASC, OrderAddress ASC);
2.
3. -- Rebuild and add the OrganizationKey
4. CREATE INDEX ProductOrder ON dbo.OrderDetails (OrderName,OrderAddress, Orderdate DESC)
5. WITH (DROP_EXISTING = ON);
Syntax
1. CREATE UNIQUE INDEX ProductId ON OrderDtails(OrderId);
166
The following query tests the uniqueness constraint by attempting to insert a row with the
same value as that in an existing row.
The following example creates a unique nonclustered index on theOrderName column of
the orderDetails of the table in the sample database. The index will enforce uniqueness on
the data inserted into the OrderName column.
Example
1. SELECT OrderName FROM OrderDetails WHERE OrderName = 'Apple';
2. GO
3.
4. INSERT INTO OrderDetails(OrderName, orderAddress,OrderDate)
5. VALUES ('guava', 'NoidaSector150', GETDATE());
Example
The above query is created to select the OrderName from OrderDetails Table and where
clause for OrderName='Apple' and Insert the OrderName, OrderAddress, OrderDate.
167
1. CREATE TABLE ProductDetails (ProductId INT, ProductName NVARCHAR(10),ProductAddres NVARCHA
R(50), ProductCity DATETIME);
2. GO
3.
4. CREATE UNIQUE INDEX AK_Index ON ProductDetails(ProductAddres)
5. WITH (IGNORE_DUP_KEY = ON);
6. GO
7.
8. INSERT INTO ProductDetails VALUES (N'Mnago', N'Apple', GETDATE());
9. INSERT INTO ProductDetails SELECT * FROM OrderDetails;
10. GO
11.
12. SELECT COUNT(*) AS [Number of rows] FROM ProductDetails;
13. GO
14.
15. DROP TABLE ProductDetails;
16. GO
• The above query will create a table named ProductDetails
• Notice that the rows inserted from the ProductDetails table that did not violate the
uniqueness constraint were successfully inserted. A warning was issued and the
duplicate row ignored, but the entire transaction was not rolled back.
• The same statements are executed again, but with IGNORE_DUP_KEY set
to OFF.
The following example drops and re-creates an existing index on the OrderId column of
the OrderDetails table in the sample database by using the DROP_EXISTING option. The
options FILLFACTOR and PAD_INDEX are also set.
Syntax
1. CREATE NONCLUSTERED INDEX OrderName
2. ON OrderDetails (OrderId)
3. WITH (FILLFACTOR = 80,
4. PAD_INDEX = ON,
5. DROP_EXISTING = ON);
6. GO
168
The following example creates a view and an index on that view. Two queries are included
that use the indexed view.
Syntax
1. SET NUMERIC_ROUNDABORT OFF;
2. SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT,
3. QUOTED_IDENTIFIER, ANSI_NULLS ON;
4. GO
5.
6. -- Create view with schemabinding
7. IF OBJECT_ID ('Sales.vOrders', 'view') IS NOT NULL
8. DROP VIEW Sales.vOrders;
9. GO
10.
11. CREATE VIEW Product.vOrders
12. WITH SCHEMABINDING
13. AS
14. SELECT SUM( * OrderQty * (1.00 - UnitPriceDiscount)) AS Revenue,
15. OrderDate, ProductID, COUNT_BIG(*) AS COUNT
16. FROM Sales.SalesOrderDetail AS od, SalesOrderHeader AS o
17. WHERE od.SalesOrderID = o.SalesOrderID
18. GROUP BY OrderDate, ProductID;
19. GO
20.
21. -- Create an index on the view
22. CREATE UNIQUE CLUSTERED INDEX IDX_V1
23. ON Sales.vOrders (OrderDate, ProductID);
24. GO
25.
26. -- This query can use the indexed view even though the view is
27. -- not specified in the FROM clause.
28. SELECT SUM(UnitPrice * OrderQty * (1.00 - UnitPriceDiscount)) AS Rev,
29. OrderDate, ProductID
30. FROM Sales.SalesOrderDetail AS od
31. JOIN Sales.SalesOrderHeader AS o ON od.SalesOrderID = o.SalesOrderID
32. AND ProductID BETWEEN 500 AND 600
33. AND OrderDate >= CONVERT(DATETIME, '11/01/2020', 104)
34. GROUP BY OrderDate, ProductID
35. ORDER BY Rev DESC;
36. GO
37.
38. -- This query can use the above indexed view
39. SELECT OrderDate, SUM(UnitPrice * OrderQty * (1.00 - UnitPriceDiscount)) AS Rev
40. FROM Sales.SalesOrderDetail AS od
41. JOIN Sales.SalesOrderHeader AS o ON od.SalesOrderID = o.SalesOrderID
42. AND DATEPART(mm, OrderDate) = 3
43. AND DATEPART(yy, OrderDate) = 2020
169
44. GROUP BY OrderDate
45. ORDER BY OrderDate ASC;
46. GO
• The above query creates an index with included (non-key) columns statement
• The following example creates a nonclustered index with one key column
(OrderId) and three non-key columns (ordername, orderaddress, orderdate)
• A query that is covered by the index follows. To display selected optimizer, on
the query menu in SQL server management studio, select "display" actual
execution plan" before executing a query.
Syntax
1. CREATE NONCLUSTERED INDEX New_OrderDetails
2. ON OrderDetails (OrderId)
3. INCLUDE (OrderName, OrderAddress, OrderDate);
4. GO
5.
6. SELECT OrderName,orderAddress,OrderDate
7. FROM OrderDetails
8. WHERE OrderId BETWEEN 8 and 10;
9. GO
Example
The above query will create NONCLUSTER INDEX ON OrderDetails table and add the
OrderName, OrderAddress, OrderDate and select the columnName
170
OrderName, orderAddress, OrderDate from OrderDetails Table and Where statement
OrderId Between 8 To 10.
The following example creates a filtered index on the OrderDetails table in the sample
database. The filter predicate can include columns that are not key columns in the filtered
index. The predicate in this example selects only the rows where EndDate is non-NULL.
Syntax
1. CREATE NONCLUSTERED INDEX Product_List
2. ON OrderDetails (OrderId, OrderName, OrderAddress)
3. WHERE OrderDate IS NOT NULL;
171
Syntax
1. CREATE CLUSTERED INDEX Product_Details
2. ON OrderDetails (OrderId)
3. WITH (DATA_COMPRESSION = ROW);
4. GO
The following example creates an index on a partitioned table by using page compression
on partition 1 of the index and row compression on partitions 2 through 4 of the index.
Syntax
1. CREATE CLUSTERED INDEX Product_Details
2. ON OrderDetails (OrderId)
3. WITH (
4. DATA_COMPRESSION = PAGE ON PARTITIONS(1),
5. DATA_COMPRESSION = ROW ON PARTITIONS (2 TO 4)
6. );
7. GO
Create, resume, pause, and abort resumable index operations
Syntax
1. -- Execute a resumable online index create statement with MAXDOP=1
2. CREATE INDEX OrderId ON OrderDetails (OrderId) WITH (ONLINE = ON, MAXDOP = 1, RESUMABLE =
ON);
3.
4. -
- Executing the same command again (see above) after an index operation was paused, resume
s automatically the index create operation.
5.
6. -
- Execute a resumable online index creates operation with MAX_DURATION set to 240 minutes.
After the time expires, the resumable index creates operation is paused.
7. CREATE INDEX OrderId ON EmployeeDetail (EmpName) WITH (ONLINE = ON, RESUMABLE = ON, MAX_
DURATION = 240);
8.
9. -- Pause a running resumable online index creation
10. ALTER INDEX EmpId ON employeDetail PAUSE;
11. ALTER INDEX EmpName ON EmployeeDetail PAUSE;
12.
13. -- Resume a paused online index creation
14. ALTER INDEX EmpId ON employeDetail RESUME;
15. ALTER INDEX EmpName ON EmployeeDetail RESUME;
16.
17. -- Abort resumable index create an operation which is running or paused
18. ALTER INDEX EmpId ON employeDetail ABORT;
19. ALTER INDEX EmpName ON EmployeeDetail ABORT;
172
The above query will create Index OrderId from EmployeeDetail table name from
EmpName with Online=on, Resumable= on, MAX_DURATION=240, And the ALTER
INDEX to add column name EmpId, EmpName on EmployeeDetail Table name PAUSE,
RESUME, ABORT statement.
The following example creates a nonclustered index on the OrderId column of the
OrderDetails table.
Syntax
1. CREATE INDEX OrderName
2. ON OrderDetails (OrderID);
The following example creates a nonclustered index on the OrderId column of the
OrderDetails table.
Syntax
1. CREATE INDEX NewOrderDetails
2. ON OrderDetails(OrderId);
The following example creates a nonclustered index on the OrderName column of the
OrderDetails table.
Syntax
1. CREATE CLUSTERED INDEX Order_Id
2. ON OrderDetail (OrerName);
173
19.17 Summary
In the next chapter, we will learn how to use a SQL UNIQUE statement with various
options.
174
20 SQL UNIQUE Constraint
20.1 Introduction
In this chapter, we will how to use a SQL Unique Constraint statement with various
options.
The Unique constraint statement ensures that all values in a column are different. Both the
Unique and Primary Key constraints provide a guarantee for uniqueness for a column or
set of columns. A Primary key constraint automatically has a unique constraint in SQL.
However, you can have many unique constraints per table, but only one primary key
constraint per table.
We can create a unique constraint in SQL Server 2019 (15.x) by using SQL server
management studio or SQL to ensure no duplicate values are entered in specific columns
that do not participate in a primary key. Creating a unique constraint automatically creates
a corresponding unique index in SQL.
SQL Server Unique constraints allow you to ensure that the data stored in a column, or a
group of columns, is unique among the rows in a table.
Syntax
1. CREATE TABLE EmployeeName (
2. EmpID int NOT NULL UNIQUE,
3. EmpName varchar(255) NOT NULL,
4. );
The above query creates a table with the name "EmployeeName" and column name
EmpID which is both Not Null and Unique(i.e we cannot have empty or duplicate data)
and EmpName
Using Unique constraint on create table statement
Syntax
175
1. CREATE TABLE Employee (
2. EmpID int NOT NULL UNIQUE,
3. EmpName varchar(255) NOT NULL,
4. EmpFirstName varchar(255),
5. EmpLastname varchar(255),
6. EmpAge int
7. );
The above query created a table with the name "Employee" and the first column name
EmpId is Not NULL and UNIQUE, other column names EmpName, EmpFirstName,
EmpLastname, EmpAge
Using Unique constraint on the alter table
Syntax
1. ALTER TABLE Employee
2. ADD UNIQUE (EmpID);
The above query with add a column EmpID and make it UNIQUE.
"Unique" is used to signify a Unique constraint, and also to define a unique name a Unique
constraint,on multiple columns.
Syntax
1. ALTER TABLE Employee
2. ADD CONSTRAINT UC_Employee UNIQUE (EmpID,EmpLastName);
The above query will add EmpID and EmpLastName columns into the UC_Employee
table, with the Unique Constraint
The above query will remove the "Unique" Constrain from the Employee table.
176
20.4 Using SQL Server Management Studio in Unique
Constraint
177
20.6 To create a unique constraint on an existing table
178
The above query uses the sample database and creates a table with the name
"Production.TransactionHistoryArchive2" and column name TransactionID and
CONSTRAINT AK_TransactionID UNIQUE column name is TransactionID.
20.8 Summary
In the next chapter, we will learn how to use a SQL Count statement with various options.
179
21 SQL COUNT Statement
21.1 Introduction
In this chapter, we learned how to use a SQL COUNT statement with various options.
This statement is used to return the number of items found in a group Count operates like
the COUNT_BIG function. These statements differ only in the data types of their return
values. Count always returns an int data type value. COUNT_BIG always returns a bigint
data type value.
The Count() function returns the number of rows in a table satisfying the criteria specified
in the WHERE clause. It sets the number of rows or non NULL column values. Count()
returns 0 if there were no matching rows.
Syntax
1. SELECT COUNT(column_name)
2. FROM table_name
3. WHERE condition;
This example is the general SQL 2019 ANSI standard syntax. It helps us understand the
way in which the SQL Count() Function is used. Different database vendors may have
different ways of applying the Count() function.
Below, you can see that SQL, PostgreSQL, and Microsoft SQL Server follow the same
syntax as given above, but DB2 and oracle differ slightly.
Overall, you can use * or ALL or distinct or some expression along with the count, in order
to count the number of rows for some condition or all of the rows, depending upon the
arguments you are using along with the count() function.
180
This example returns the number of different titles that a Sample in OrderDetails can hold.
Syntax
1. SELECT COUNT(DISTINCT OrderName )
2. FROM OrderDetails
3. GO
Example
Note
The Count statement * is used for Count(), all records ( rows ) are Counted if some content
NULL but Count(column_name) does not Count a record if its field is NULL
The following query counts the number of rows from two different tables (here we use
EmployeeDetail and OrderDetails) using the Count(*) command.
Syntax
1. SELECT(
2. SELECT COUNT(*)
3. FROM EmployeeDetail
4. ) AS Total_Employees,
5. (SELECT COUNT(*)
6. FROM OrderDetails
7. ) AS OrderName
8. FROM OrderDetails
Example
182
21.7 Select Count(*) with other aggregates
This example shows that Count(*) works with other aggregate functions in the Select list.
The example uses the Sample database.
Syntax
1. SELECT COUNT(*),AVG(OrderId)
2. FROM OrderDetails
3. Where OrderId>5;
4. GO
Example
This example uses the Min, Max, Avg, and Count functions with the Over clause, to return
aggregated values for each department in the Sample database OrderDetails table.
183
Syntax
1. SELECT DISTINCT OrderName
2. , MIN(OrderId) OVER (PARTITION BY edh.OrderId) AS OrderDetails
3. , MAX(EmpId) OVER (PARTITION BY edh.OrderId) AS EmployeeDetail
4. , AVG( EmployeeID) OVER (PARTITION B edh.OrderId) class="string">"keyword">AS Emp
loyeeDetails
5. ,COUNT(OrderId) OVER (PARTITION BY edh.OrderId) class="keyword">AS OrderDetails
In this section, we have discussed how to apply to count() withvarious SQL clauses for
those applications, we have used Oracle 10g express edition.
Count with Distinct page discusses how to apply the count function with distinct and also
discusses how to apply the count function with All clause. unlike using *,when all is used,
Null values are not selected.
Count Having page discusses how to apply the count function with the Having clause and
group by.
Count with Group by page discusses how to apply the Count function with Group By in
ascending order and in descending order.
21.10 Summary
In this chapter, we learned how to use a SQL DATE TIME statement with various options.
184
22 SQL Aggregate Statement
22.1 Introduction
In this chapter, we will learn how to use a SQL Aggregate statement with various options.
The Aggregate function is used to perform calculations on a set of values and return a
single value, ignoring all null values.
The Aggregate functions are often used with the group by clause of the select statement in
SQL
The database management aggregate function is a function in which the values of multiple
rows are grouped together as input on certain criteria to form a single value of more
significant meaning
All aggregate statements are deterministic In other words, aggregate functions return the
same value each time that they are called when called with a specific set of input values.
See Deterministic and Nondeterministic Functions for more information about function
determinism The over clause may follow all aggregate functions, except the
STRING_AGG, grouping, or GROUPING_ID functions
Aggregate functions can we use the expressions only in the following situations
• The select list of a select statement (either a subquery or an outer query).
• A having clause.
22.3 Functions
SQL provides the following aggregate functions based off of the following Student table
Syntax
1. SELECT * FROM Student;
Example
185
22.4 APPROX_COUNT_DISTINCT()
This statement returns the approximate number of unique non-null values in a group.
Approx_count_distinct expression evaluates an expression for each row in a group and
returns the approximate number of unique non-null values in a group.
This function is designed to provide aggregations across large data sets where
responsiveness is more critical than absolute precision.
Approx_count_distinct is designed for use in big data scenarios and is optimized for the
following conditions
• Access of data sets that are millions of rows or higher and
• Aggregation of a column or columns that have many distinct values
This function implementation guarantees up to a 2% error rate within a 97%
probability.Approx_count_distinct requires less memory than an exhaustive count distinct
operation, given the smaller memory footprint
Approx_count_distinct is less likely to spill memory to disk compared to a precise count
distinct operation.
To learn more about the algorithm used to achievethis, see hyperloglog.
Syntax
1. SELECT Count (StudentId) AS Approx_Distinct_OrderKey
2. FROM Student;
186
Example
22.5 AVG ()
187
22.6 CHECKSUM_AGG()
This statement returns the checksum of the values in a group. CHECKSUM_AGG ignores
null values.
The over clause can follow CHECKSUM_AGG
CHECKSUM_AGG can detect changes in a table
The CHECKSUM_AGG result does not depend on the order of the rows in the table. Also,
CHECKSUM_AGG functions allow the use of the Distinct keyword and the Group By
clause
If an expression list value changes, the list checksum value list will also probably change.
However, a small possibility exists that the calculated checksum will not change
Syntax
1. SELECT CHECKSUM_AGG(CAST(StudentID AS int))
2. FROM Student;
3. GO
Example
22.7 COUNT()
188
Count always returns an int data type value.COUNT_BIG always returns a bigint data type
value.
Syntax
1. SELECT COUNT (StudentName) from Student
Example
22.8 COUNT_BIG ()
This statement returns the number of items found in a group.COUNT_BIG operates like
the count function. These functions differ only in the data types of their return values.
COUNT_BIG always returns a bigint data type value. Count always returns an int data
type value.
The COUNT_BIG(*) returns the number of items in a group. This includes null values and
duplicates.
The COUNT_BIG (all expression) evaluates the expression for each row in a group and
returns the number of nonnull values.
COUNT_BIG (distinct expression) evaluates the expression for each row in a group and
returns the number of unique, nonnull values.
Syntax
1. SELECT COUNT(*)
2. FROM Student
3. GO
Example
189
22.9 GROUPING ()
190
22.10 GROUPING_ID statement ()
This function computes the level of grouping. GROUPING_ID can be used only in the
SELECT <select> list, HAVING, or ORDER BY clauses when GROUP BY is specified.
Syntax
1. SELECT GROUPING_ID(StudentId, StudentName)
2. FROM Student
3. GROUP BY CUBE(StudentId, StudentName)
Example
22.11 Summary
In this chapter, we learned how to use a SQL CAST and CONVERT statement with various
options.
191
23 SQL DATE TIME Statement
23.1 Introduction
In this chapter, we will learn how to use SQL Date and Time Data with various options.
When working with SQL Date the most difficult part is to be sure that the format of the
date you are trying to insert, matches the format of the date column in the database in SQL
Server
As long as your data contains only the date portion, your queries will work as expected.
However, if a time portion is involved, it gets more complicated in SQL.
The SQL Date defines a date that is combined with a time of day with fractional seconds
that is based on a 24-hour clock
Note
Use the time date datetime2 and datetimeoffset data types for new work. These types align
with the SQL standard
They are more portable times; datetime2 and datetimeoffset provide more seconds;
precisiondatetimeoffset provides time zone support for globally deployed applications
SQL Server - SQL Server comes with the following data types for storing a date or a
date/time value in the database
• DATE - format YYYY-MM-DD
• DATETIME - format: YYYY-MM-DD HH:MI: SS
• SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
• TIMESTAMP - format: a unique number
192
The date types are chosen for a column when you create a new table in your database
You can compare two dates easily if there is no time component involved
We have the following OrderDetails table
Syntax
1. Select * from OrderDetails
Example
Now we want to select the records with an OrderDate of 2019-04-11 from the table above
We use the following Select statement
Syntax
1. SELECT FROM OrderDetails WHERE OrderDate='2019-04-11'
Example
193
Converting date and time data is when you convert to date and time data types, SQL Server
rejects all values.
It doesn't recognize as dates or times for information about using the cast and convert
functions with date and time data, see the cast and convert in SQL.
23.5.1 Converting date to other date and time types
This section describes what occurs when you convert a date data type to other date and
time data types.
When the conversion is to time(n), the conversion fails, and error message 206 is raised
and there is an operand type clash: date is incompatible with time.
If the conversion is to datetime, the date is copied. The following code shows the results
of converting a date value to a datetime value
Syntax
1. DECLARE @date date = '12-21-16';
2. DECLARE @datetime datetime = @date;
3. SELECT @datetime AS '@datetime', @date AS '@date';
Example
The datetime is defined when the conversion is from time(n), the time component is
copied, and the date component is set to '1900-01-01'.
When the fractional precision of the time(n) value is greater than three digits, the value
will be truncated to fit.
The following example shows the results of converting a time(4)value to a datetime value.
Syntax
1. DECLARE @time time(4) = '12:10:05.1237';
194
2. DECLARE @datetime datetime = @time;
3. SELECT @datetime AS '@datetime', @time AS '@time';
Example
The SQL date time conversion is from smalldatetime the hours and minutes are copied.
The seconds and fractional seconds are set to 0.
The following code shows the results of converting a smalldatetime value.
Syntax
1. DECLARE @smalldatetime smalldatetime = '12-01-19 12:32';
2. DECLARE @datetime datetime = @smalldatetime;
3. SELECT @datetime AS '@datetime', @smalldatetime AS '@smalldatetime';
Example
The SQL date-time is defined as when the conversion is from datetimeoffset(n)the date
and time components are copied.
The time zone is truncated. When the fractional precision of the datetimeoffset(n)value is
greater than three digits, the value will be truncated.
The following example shows the results of converting a datetimeoffset(4) value to
a datetime value.
Syntax
195
1. DECLARE @datetimeoffset datetimeoffset(4) = '1968-10-23 12:45:37.1234 +10:0';
2. DECLARE @datetime datetime = @datetimeoffset;
3.
4. SELECT @datetime AS '@datetime', @datetimeoffset AS '@datetimeoffset';
Example
The Datetime is defined as when the conversion is from datetime2(n), the date and time
are copied. when the fractional precision of the datetime2(n) value is greater than three
digits, the value will be truncated.
The Datetime is defined as when the conversion is from datetime2(n), the date and time
are copied.
When the fractional precision of the datetime2(n) value is greater than three digits, the
value will be truncated.
The following example shows the results of converting a datetime2(4)value to a
datetimevalue.
The following example shows datetime and datetime2 in SQL server
Syntax
1. DECLARE @datetime2 datetime2(4) = '1968-10-23 12:45:37.1237';
2. DECLARE @datetime datetime = @datetime2;
3. SELECT @datetime AS '@datetime', @datetime2 AS '@datetime2';
Example
196
The following example compares the results of casting a string to each date and data type.
Syntax
1. SELECT
2. CAST'2019-05-18 12:35:29. 1234567 +12:15' AS "keyword">time(7)) AS 'time'
3. ,CAST'2019-05-18 12:35:29. 1234567 +12:15' AS date AS 'date'
4. ,CAST('2019-05-18 12:35:29.123' >AS smalldatetime) AS
5. 'smalldatetime'
6. ,CAST'2019-05-18 12:35:29.123' AS datetime) >AS 'datetime'
7. ,CAST('2019-05-18 12:35:29. 1234567 +12:15' >AS datetime2(7)) AS
8. 'datetime2'
9. ,CAST'2019-05-18 12:35:29.1234567 +12:15' AS datetimeoffset(7)) AS
10. 'datetimeoffset';
Example
23.6 Summary
In this chapter, we learned how to use SQL Aggregate statements with various options.
197
24 SQL Cast And Convert Statement
24.1 Introduction
In this chapter, we will learn how to use a SQL Cast and convert statements with various
options.
The Cast statement is used to convert a data type variable or data from one data type to
another data type. If the conversion fails, the function will return an error. Otherwise, it
will return the converted value. The Cast statement provides a data type to a dynamic
parameter (?) or a NULL value in SQL.
Syntax
1. CAST(expression AS datatype(length))
The Convert statement is used to convert expressions from one type to another, in many
cases there will be a need within a stored procedure or another routine to convert data from
a datetime type to a varchar type. The Convert statement is used for such things. The
Convert() function can be used to display date/time data in various formats in SQL
datatype.
Syntax
1. CONVERT(data_type(length), expression, style)
These examples retrieve the name of the OrderName for those OrderDetails that have a 1
as the first digit of OrderName, and converts their OrderId values to int.
Syntax
198
1. -- Use CAST
2. USE sample;
3. GO
4. SELECT SUBSTRING(OrderName, 1, 40) AS OrderName, orderAddress
5. FROM OrderDetails
6. WHERE CAST( OrderId AS int) LIKE '10%';
7. GO
8.
9. -- Use CONVERT.
10. USE sample;
11. GO
12. SELECT SUBSTRING(OrderName, 1, 40) AS OrderName , orderAddress
13. FROM OrderDetails
14. WHERE CONVERT(int, OrderId) LIKE '8%';
15. GO
Example
199
In this example, we can calculate a single column computation (Computed) by dividing
the total OrderId by the OrderDetails. This value is rounded to the nearest whole number
and is then Cast to a data type.
Syntax
1. USE sample ;
2. GO
3. SELECT CAST(ROUND(OrderId, 0) AS int) AS Computed
4. FROM OrderDetails
5. WHERE OrderId != 0;
6. GO
Example
This example concatenates noncharacter expressions by using Cast. It uses the Sample
database.
Syntax
1. SELECT 'The Order Details ' + CAST(OrderName AS varchar(12)) AS OrderCity
2. FROM OrderDetails
3. WHERE OrderId BETWEEN 8 AND 10;
Example
200
24.7 Using Cast to produce more readable text statement
This example uses Cast in the Select list, to convert the OrderName column to
a char(50) column.
Syntax
1. SELECT DISTINCT CAST(OrderName AS char(50)) AS Name
2. FROM OrderDetails
3. WHERE OrderName LIKE 'Mango';
Example
201
6. ON s.OrderId = s.OrderId
7. WHERE CAST(CAST(s.OrderId AS int) AS char(200)) LIKE '1%';
8. GO
Example
These examples show the use of Convert to convert data to typed XML by using the XML
data type and columns SQL Server.
202
This statement converts a string with white space text and markup into typed XML and
removes all insignificant white space (boundary white space between nodes).
Syntax
1. SELECT CONVERT(XML, '<root><child/></root>')
Example
This example converts a similar string with white space, text, and markup into typed XML
and preserves insignificant white space boundary white space between nodes in the
Convert statement.
Syntax
1. SELECT CONVERT(XML, '<root> <child/> </root>', 1)
This example casts a string with white space, text, and markup into typed XML
Example
This example casts a string with white space, text, and markup into typed XML in SQL.
Example
203
24.10 Using Cast and Convert with the DateTime data
statement
The cast and convert Starting with Getdate() values, this example displays the current date
and time, uses Cast to change the current date and time to a character dataType, and then
uses Convert to display the date and time in the ISO 8601 format in SQL
Syntax
1. SELECT
2. GETDATE() AS UnconvertedDateTime,
3. CAST(GETDATE() AS nvarchar(40)) AS UsingCast,
4. CONVERT(nvarchar(40), GETDATE(), 126) AS UsingConvertTo_ISO8601 ;
5. GO
Example
204
Syntax
1. SELECT
2. '2006-04-25T15:50:59.997' AS UnconvertedText,
3. CAST('2006-04-25T15:50:59.997' AS datetime) AS UsingCast,
4. CONVERT(datetime, '2006-04-25T15:50:59.997', 126) AS UsingConvertFrom_ISO8601 ;
5. GO
Example
This example shows the results of binary and character data conversion, using different
styles.
Syntax
1. SELECT CONVERT(char(8), 0x4E616d65, 0) AS [Style 0, binary to character];
Example
This example shows that style 1 can force a truncation result. The characters 0x in the
result set force the truncation.
Syntax
205
1. SELECT CONVERT(char(8), 0x4E616d65, 1) AS [Style 1 binary to character]
Example
This example shows the conversion of date, time, and datetime data types. ]]
Syntax
1. DECLARE @d1 date, @t1 time, @dt1 datetime;
2. SET @d1 = GETDATE();
3. SET @t1 = GETDATE();
4. SET @dt1 = GETDATE();
5. SET @d1 = GETDATE();
6. -- When converting date to datetime the minutes portion becomes zero.
7. SELECT @d1 AS [date], CAST (@d1 AS datetime) AS [date as datetime];
8. -- When converting time to datetime the date portion becomes zero
9. -- which converts to January 1, 1900.
10. SELECT @t1 AS [time], CAST (@t1 AS datetime) AS [time as datetime];
11. -- When converting datetime to date or time non-applicable portion is dropped.
12. SELECT @dt1 AS [datetime], CAST (@dt1 AS date) AS [datetime as date],
13. CAST (@dt1 AS time) AS [datetime as time];
Starting with getdate() values, this example uses Convert to display of all the date and time
styles in section Date and Time styles of this article.
Effects of data type precedence in the allowed conversions statement.
The following example defines a variable of type Varchar, assigns an integer value to the
variable, then selects a concatenation of the variable with a string.
Syntax
1. DECLARE @string varchar(10);
2. SET @string = 1;
3. SELECT @string + ' is a string.' AS Result
Example
206
The int value of 1 was converted to varchar.
This example shows a similar query using an int variable instead.
Syntax
1. DECLARE @notastring int;
2. SET @notastring = '1';
3. SELECT @notastring + ' is not a string.' AS Result
In this case, the Select statement will throw the following error.
Example
This statement In order to evaluate the expression @notastring + is not a string SQL Server
statement and needs to follow the rules of data type precedence to complete the implicit
conversion before the result of the expression can be calculated.
Because int has higher precedence than varchar SQL Server attempts to convert the string
to an integer and fails because this string cannot be converted to an integer.
If we provide a string that can be converted this statement will succeed, as seen in the
following example.
Syntax
1. DECLARE @notastring int;
2. SET @notastring = '1';
3. SELECT @notastring + '1
207
In this case, the string '1' can be converted to the integer value 1 so this Select statement
will return the value 2. When the data types provided are integers, the + operator becomes
an additional mathematical operator, rather than a string concatenation in SQL statement.
24.14 Summary
In this chapter, we learned how to use SQL Stored Procedures with various options.
208
25 Create Stored Procedure In SQL
25.1 Introduction
In this chapter, we will learn about how to create a stored procedure in the SQL database.
For the stored procedure, we will use the SQL Database.
A stored procedure in a relational database is a collection of SQL statements that are saved
on the database server and executed on the server itself. Any SQL query including Insert,
Update, Delete can be a part of a stored procedure. Stored procedures are a secure way to
access and manipulate data. Stored procedures also provide high-performance results
compare to embedded SQL queries in your code.
Let's see how to create a stored procedure in SQL database.
Syntax to create a Stored Procedure:
1. CREATE
2. [DEFINER = { user | CURRENT_USER }]
3. PROCEDURE sp_name ([proc_parameter[,...]])
4. [characteristic ...] routine_body
Let's look at this step by step.
Step 1- Create a Table
1. CREATE TABLE `employees` (
2. `id` int(11) NOT NULL AUTO_INCREMENT,
3. `employeeNumber` int(11) NOT NULL,
4. `lastname` varchar(50) NOT NULL,
5. PRIMARY KEY (`id`)
6. )
Step 2- For insertion create a stored procedure:
1. delimiter $$
2. CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_inser`
3. (IN `employeenum` int
4. , IN `lastname` varchar(200)
5. )
6. begin
7. insert into employees (employeeNumber,lastname) values(employeenum,lastname);
209
8. END$$
Step 3- Call stored procedure
1. call sp_inser(123,'rajeev')
25.3 Summary
In the next chapter, we will learn how to create Trigger in SQL Database.
210
26 Triggers in SQL
26.1 Introduction
In the previous chapter, we learned how to work with GROUP BY, WHERE, and
HAVING clauses in SQL and how to use them with various options.
In this chapter, we will learn about Trigger in SQL, Types of Triggers, and to use Triggers
in SQL with various conditions.
26.2 Triggers
Triggers are stored programs that are automatically executed or fired when some events
occur. It is a database object that is bound to a table and is executed automatically. We
cannot explicitly call any trigger. Triggers provide data integrity and used to access and
check data before and after modification using DDL or DML query.
Triggers are used in the following events
1. DML (Data manipulation Language)(Insert ,Update ,Delete).
2. DDL (Data Definition Language)(Create, Alter, Drop).
3. Database Operation such as LOGON, LOGOFF, SERVERERROR,
SHUTDOWN, STARTUP.
Now we will understand what is triggers and how it works?
First, create a table as in the following:
1. Create Table Student
2. (
3. IId int Not Null primary key,
4. Name Nvarchar(MAX) Not NUll,
5. Age Int Not Null,
6. Class int not Null
7. )
Now insert some values into the table as in the following:
1. Insert Into Student
2. Select 1,'A',12,10 Union All
3. Select 2,'B',16,11 Union All
211
4. Select 3,'C',15,9 Union All
5. Select 4,'D',13,12 Union All
6. Select 5,'E',14,11 Union All
7. Select 6,'F',17,8 Union All
8. Select 7,'G',12,7 Union All
9. Select 8,'H',17,12
Now the table will look like the following:
212
26.3.1 After Triggers
After triggers are invoked after DML (insert, update and delete) operations. They are not
supported by views. An after the trigger is also divided into the following 3 parts:
• After Insert
• After Delete
• After Update
26.3.2 After Insert
Example
An After Insert Trigger is called after any data is inserted into the table.
1. Create Trigger My_Trigger On Student
2.
3. AFTER Insert
4. AS
5. Declare @IId int ;
6. Declare @Name Nvarchar(50) ;
7. Declare @Age Int;
8. Declare @Class int;
9.
10. Select @IId= Tab.IId From inserted Tab;
11. Select @Name= Tab.Name From inserted Tab;
12. Select @Age= Tab.Age From inserted Tab;
13. Select @Class= Tab.Class From inserted Tab;
14.
15. Set @IId=@IId+1;
16. Insert Into Student(IId,Name , Age ,Class) Values (@IId,@Name,@Age,@Class)
17. Print 'Inserted Successfully'
Now we will insert some values into the Student Table.
Insert Into Student(IId,Name,Age,Class) values(10,'Pankaj',21,12)
Output
(1 row(s) affected)
Inserted Successfully
(1 row(s) affected)
In the preceding example, we will create a trigger for an insert query so when any data is
inserted into the student table, then after the insert query this trigger will be invoked and
213
some desired operation will be done. In the insert trigger, we use the “INSERTED” magic
table.
26.3.3 After Delete
After Delete Triggers are called after any data is deleted from the table.
1. Create Trigger After_Delete On Student
2. AFTER Delete
3. AS
4. Declare @IId int ;
5. Declare @Name Nvarchar(50) ;
6. Declare @Age Int;
7. Declare @Class int;
8.
9. Select @IId= Tab.IId From Deleted Tab;
10. Select @Name= Tab.Name From Deleted Tab;
11. Select @Age= Tab.Age From Deleted Tab;
12. Select @Class= Tab.Class From Deleted Tab;
13. if @IId>10
14. begin
15. Insert Into Student(IId,Name , Age ,Class) Values (@IId,@Name,@Age,@Class)
16. Print 'Data Deleted Successfully'
17. End
18. else
19. Begin
20. Print 'Data not Deleted Successfully'
21. End
Now we will delete some data from the table:
Delete from Student Where IId=99
Output
(1 row(s) affected)
Data Deleted Successfully
(1 row(s) affected)
Now we will take another example:
Delete from Student Where IId=9
Output
Data not Deleted Successfully
(0 row(s) affected)
214
In the After Delete trigger we used the “Deleted” magic table. This table contains all the
data that was deleted by the query.
26.3.4 After Update
An After Update Trigger is called after any type of update is done on the table.
1. Create Trigger After_Update On Student
2. AFTER Update
3. AS
4. Declare @IId int ;
5. Declare @Name Nvarchar(50) ;
6. Declare @Age Int;
7. Declare @Class int;
8.
9. Declare @IId1 int ;
10. Declare @Name1 Nvarchar(50) ;
11. Declare @Age1 Int;
12. Declare @Class1 int;
13.
14. Select @IId= Tab.IId From Deleted Tab;
15. Select @Name= Tab.Name From Deleted Tab;
16. Select @Age= Tab.Age From Deleted Tab;
17. Select @Class= Tab.Class From Deleted Tab;
18.
19. Select @IId1= Tab.IId From inserted Tab;
20. Select @Name1= Tab.Name From inserted Tab;
21. Select @Age1= Tab.Age From inserted Tab;
22. Select @Class1= Tab.Class From inserted Tab;
23. Set @IId1=@IId1+1;
24. if @IId>10
25. begin
26. Delete From Student Where IId=@iid
27. Insert Into Student(IId,Name , Age ,Class) Values (@IId1,@Name1,@Age1,@Class1)
28. Print 'Data Updated Successfully'
29. End
30. else
31. Begin
32. Print 'Data not Updated Successfully'
33. End
215
(1 row(s) affected)
(1 row(s) affected)
Data Updated Successfully
(1 row(s) affected)
The preceding example shows that in an After Update trigger we can use both the
“Inserted” and “Deleted” magic tables. The Update query also does two steps, the first is
to delete data from the table. In that case, the “Deleted” magic table contains the deleted
data and the second step is the insertion of the data into the table. In that step, the “Inserted”
magic table contains the inserted data.
So we can use both magic tables in an “After Update” trigger.
These can be used as an interceptor for anything that anyone tries to do on our table or
view. This type of trigger fires before SQL Server starts the execution of the action that
fired it. We can have an INSTEAD OF insert/update/delete trigger on a table that was
successfully executed but does not include the actual insert/update/delete to the table.
Assume we have an Instead Of Trigger for a Delete operation on a table. When any data
is deleted from the table then this trigger will execute first but after the execution of this
trigger, the data will not delete from the table unless we issue another delete instruction
from within the trigger.
26.4.1 Types of Instead Of Triggers
1. Instead Of Insert
2. Instead Of Update
3. Instead Of Delete
Example
The table before the execution of an “Instead Of Delete”.
216
Now we create an “Instead Of Trigger“.
1. Create Trigger Insted_Delete On Student
2. Instead Of Delete
3. as
4. begin
5. Declare @IId int ;
6. Declare @Name Nvarchar(50) ;
7. Declare @Age Int;
8. Declare @Class int;
9.
10. Select @IId= Tab.IId From Deleted Tab;
11. Select @Name= Tab.Name From Deleted Tab;
12. Select @Age= Tab.Age From Deleted Tab;
13. Select @Class= Tab.Class From Deleted Tab;
14. Set @IId=@IId+1;
15. Insert Into Student(IId,Name , Age ,Class) Values (@IId,@Name,@Age,@Class)
16. Print 'Data Updated Successfully'
17. End
Then we try to delete some data from the data and examine the result.
217
We can see that we execute the query for the delete of the student record from the table
that have an IId equal to 8 but in the result record with IId =3 it is not deleted because the
data will not delete from the table unless we issue another delete instruction from within
the trigger.
Now we create another trigger that contains a Delete Command.
1. Create Trigger Insted_Delete1 On Student
2. Instead Of Delete
3. as
4. begin
5. Declare @IId int ;
6. Declare @Name Nvarchar(50) ;
7. Declare @Age Int;
8. Declare @Class int;
9.
10. Select @IId= Tab.IId From Deleted Tab;
11. Select @Name= Tab.Name From Deleted Tab;
12. Select @Age= Tab.Age From Deleted Tab;
13. Select @Class= Tab.Class From Deleted Tab;
14. Delete From Student Where IId=@IId
15. Set @IId=@IId+1;
16. Insert Into Student(IId,Name , Age ,Class) Values (@IId,@Name,@Age,@Class)
17. Print 'Data Updated Successfully'
18. End
Now we execute a delete operation on the table.
218
26.5 Cyclic Cascading in a Trigger
This is an undesirable situation where more than one trigger enters into an infinite loop.
When creating a trigger we should ensure that such a situation cannot happen. This
situation can occur when two triggers generate a call for each other.
Let us create two triggers as in the following:
• The first trigger is for an insert as in the following:
1. Create Trigger [dbo].[Insert_] On [dbo].[Student]
2. For Insert
3. as
4. begin
5. Declare @IId int ;
6. Declare @Name Nvarchar(50) ;
7. Declare @Age Int;
8. Declare @Class int;
9.
10. Select @IId= Tab.IId From inserted Tab;
11. Select @Name= Tab.Name From inserted Tab;
12. Select @Age= Tab.Age From inserted Tab;
13. Select @Class= Tab.Class From inserted Tab;
14.
15.
16. Update Student set Name=@Name ,Age=@Age where IId=@IId
17. Print 'Data Inserted Successfully'
219
18. End
• And the second trigger is for an update as in the following:
1. Create Trigger [dbo].[Update_] On [dbo].[Student]
2. For Update
3. as
4. begin
5. Declare @IId int ;
6. Declare @Name Nvarchar(50) ;
7. Declare @Age Int;
8. Declare @Class int;
9.
10. Select @IId= Tab.IId From inserted Tab;
11. Select @Name= Tab.Name From inserted Tab;
12. Select @Age= Tab.Age From inserted Tab;
13. Select @Class= Tab.Class From inserted Tab;
14. Set @IId=@IId+1;
15. Insert Into Student(IId,Name , Age ,Class) Values (@IId,@Name,@Age,@Class)
16. Print 'Data Updated Successfully'
17. End
Now we insert some data into the table and check what will happen.
Insert into Student values(9000,'A',32,5000)
Output
Msg 217, Level 16, State 1, Procedure Update_, Line 15
Maximum stored procedure, function, trigger, or view nesting level exceeded
(limit 32).
The first trigger (Insert_) contains an update statement. When this statement executes it
creates a call for Update_ trigger that contains an insert statement so when this statement
executes it will create a call for the Insert_ trigger. So an infinite loop will occur.
Note
During the creation of a trigger, we must be sure to remove such a condition because this
cyclic situation continues and will enter into an infinite loop that will crash the database.
26.6 Summary
In this chapter, we learned about what is Trigger in SQL and how to use Triggers in SQL
with various options.
220