0% found this document useful (0 votes)
221 views204 pages

SQL Server Tutorial NEW

SQL Server is a relational database developed by Microsoft that allows users to create, maintain, and analyze databases. It supports the SQL language and can be used to perform tasks like creating databases, generating reports, and carrying out ETL processes. The document discusses the different versions, advantages of using instances, and provides details on the various data types supported in SQL Server like numeric, date/time, character, and Unicode string types.

Uploaded by

Tanusha hande
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
221 views204 pages

SQL Server Tutorial NEW

SQL Server is a relational database developed by Microsoft that allows users to create, maintain, and analyze databases. It supports the SQL language and can be used to perform tasks like creating databases, generating reports, and carrying out ETL processes. The document discusses the different versions, advantages of using instances, and provides details on the various data types supported in SQL Server like numeric, date/time, character, and Unicode string types.

Uploaded by

Tanusha hande
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 204

What is SQL Server?

 It is a software, developed by Microsoft, which is implemented from the specification of


RDBMS.
 It is also an ORDBMS.
 It is platform dependent.
 It is both GUI and command based software.
 It supports SQL (SEQUEL) language which is an IBM product, non-procedural, common
database and case insensitive language.

Usage of SQL Server


 To create databases.
 To maintain databases.
 To analyze the data through SQL Server Analysis Services (SSAS).
 To generate reports through SQL Server Reporting Services (SSRS).
 To carry out ETL operations through SQL Server Integration Services (SSIS).

Versions of SQL Server

Version Year Code Name

6.0 1995 SQL95

6.5 1996 Hydra

7.0 1998 Sphinx

8.0 (2000) 2000 Shiloh

9.0 (2005) 2005 Yukon

10.0 (2008) 2008 Katmai

10.5 (2008 R2) 2010 Kilimanjaro

11.0 (2012) 2012 Denali

12 (2014) 2014 Hekaton (initially), SQL 14 (current)

Advantages of Instances
 To install different versions in one machine.
 To reduce cost.
 To maintain production, development, and test environments separately.
 To reduce temporary database problems.
 To separate security privileges.
 To maintain standby server.

SQL Server Data Types


A datatype ensures which type of data our column or variable can store in SQL Server. When we
create any table or variable, it is required to specify the type of data it will store in addition to the
name of each column. For example, in SQL Server, each table has many columns and contains specific
data types for each column that should be integer, float, varchar, Boolean, etc.

How to use datatypes?

o We are required to specify the data type in advance for each column of a table to ensure which
type of data it can store. The data type specification also prevents the user from entering any
unexpected or invalid information.
o When we assign the appropriate data type to a column, we can make efficient use of memory
by allocating only the amount of system memory required for the data in the relevant column.

We can use the following characteristics to define data type in SQL Server:

o The type of values (fixed or variable) it represents.


o The storage space depends on the values, which are a fixed-length or variable length.
o Its storage value can be indexed or not.
o How SQL Server performs a comparison of values of a particular data type.

Why use data types?


We can understand the importance of data type in SQL Server by taking a simple Sign-up page to
create a new google account (only for reference purposes). This page shows the following input
fields: First Name, Last Name, User Name, and Password.
These fields require the following data type characteristics:

o First name and Last name: These fields should require only alphabets.
o Username: This field can accept letters, numbers, and periods.
o Password: This field must contain alphabets, numbers, and special characters.

Some other examples are:

o Contact Number: This field must be numeric.


o Pin Code: It can take both alphabets and numeric fields.

SQL Server supports a broad category of SQL standard data types based on the user's needs.
These data types can be broken into the following categories:

o Exact numeric
o Approximate numeric
o Date and time
o Character strings
o Unicode character strings
o Binary strings
o Other data types

Exact numeric data type


This data type will store exact numbers such as integer, decimal, and money. They have their own
lower, upper limit, and memory requirements. They have their own memory needs, as well as a lower
and upper limit. It is also necessary to use the lowest data type to save memory requirements. For
example, the bit data type can be used to store true (1) or false (0) values. SQL Server categorizes
this data type into nine types, which are given below:

Data Descriptions Storage


Type

bit It is an integer type that allows us to store 0, 1, and NULL values. 1 byte

tinyint It allows us to store whole numbers from 0 to 255. 1 byte

smallint It allows us to store whole numbers between -32768 to 32767. 2 byte

int It allows to store whole numbers between -2,147,483,648 and 4 byte


2,147,483,647

bigint It allows to store whole numbers between -9,223,372,036,854,775,808 8 byte


and 9,223,372,036,854,775,807

Decimal(p, s) It is used for scale and fixed precision numbers. 5 to 17 bytes


The p parameter indicates the maximum total number of digits that
can be stored (both to the left and the right of the decimal point). By
default, it is 18 but can be in a range of 1 to 38.
The s parameter indicates the maximum number of digits stored to the
right of the decimal point. By default, its value is 0 but can be from 0
to p.

Numeric(p, s) It is similar to the decimal data type because both are synonyms. 5 to 17 bytes.

smallmoney It allows storing monetary or currency values. 4 byte

money It allows to store monetary or currency values. 8 byte

Approximate numeric data types


This data type is used to store floating-point and real values. It is mainly used in scientific calculations.

Data Type Storage Precision

float(n) It depends on n. 4 or 8 bytes 7 digit

real 4 byte 15 digit

Date and Time data types


We use these data types to hold the temporal values such as date and time, including time offset in a
column. We can categories this data type into six types, which are summarized in below table:

Data Type Descriptions Storage

date It is used to store dates in SQL Server. By default, its format is 3 bytes
YYYY-MM-DD, and its value is 1900-01-01.

datetime It is used to store date and time with fractional seconds. Its 8 bytes
default value is 1900-01-01 00:00:00. Its accuracy is in the
increment of .000, .003, or .007 seconds. It is recommended to
avoid this data type and use datetime2 instead.

datetime2 It specifies date and time with fractional seconds and an accuracy 6 to 8 bytes
of 100 nanoseconds. It provides precision from 0 to 7 digits. By
default, its precision is 7, and the format is YYYY-MM-DD hh:mm:
ss[.fractional seconds].

datetimeoffset It is the same as datetime2 with the addition of a time zone 10 bytes
offset. Its timezone offset value is between -14:00 through
+14:00.

smalldatetime It specifies a date along with the time of day and an accuracy of 1 4 bytes
minute. Here time is calculated on a 24-hour clock, with seconds
starting at zero (:00) and no fractional seconds.

time It specifies time data only with an accuracy of 100 nanoseconds. It 3 to 5 bytes
is based on a 24-hour clock without time zone awareness. By
default, its format is hh:mm:ss[.nnnnnnn].

Character string data type


This data type allows us to define the character data type only, which can be fixed or variable in
length. The following table illustrates all character string data type support in SQL Server:

Data Type Descriptions Storage

char(n) It is used to store fixed-length non-Unicode character data. n bytes

varchar(n) It is used to store variable-length non-Unicode character data. n bytes + 2


bytes

varchar(max It is a data type that stores variable-length data. It is n bytes + 2


) recommended to avoid this data type unless required because bytes
of its huge memory storage.

text It is a variable-length character string. It is also recommended n bytes + 4


to avoid this data type because it would be deprecated in future bytes
releases.

Unicode character string data types


This data type allows us to define the full range of Unicode character sets encoded in the UTF-16
character set. The following table illustrates all Unicode character string data type support in SQL
Server:

Data Type Descriptions Storage

nchar It is used to store fixed- 0 characters


length Unicode character data.

nvarchar It is used to store variable-length Unicode n bytes + 2


character data. bytes

ntext It is used to store variable-length Unicode string 2 times the


data. It is recommended to avoid this data type string length
because it would be deprecated in future
releases.

Binary data types


This data type allows storing image, audio, and video files of fixed and variable length into a database
location. It stores information in 0 and 1 format. The following table illustrates all binary string data
type support in SQL Server:

Data Descriptions Storage


Type

binary It is used to store fixed-length binary strings. n bytes

varbinary It is used to store variable-length binary string. The actual length of data
entered + 2 bytes

image It is similar to the varbinary data type that can store up


to 2 GB. It is recommended to avoid this data type
because it would be deprecated in future releases.

Special data types


SQL Server also provides some special data types that can be used according to our requirements.
The below table illustrates all special datatypes:

Data Type Descriptions

cursor It is an object data type used for variable and stored procedure OUTPUT
parameters containing a reference to a cursor. In addition, it stores temporary
table information.. Its output is a column of sp_cursor_list and sp_describe_cursor
that returns the name of the cursor variable.

rowversion It's a data type that returns automatically generated unique binary numbers
within a database. It is commonly used for version-stamping table rows. Its
memory storage is 8 bytes. It's an increasing number that doesn't preserver time
and date.

hierarchyid It is a system data type with variable length representing a position in a hierarchy.
Its value represents the position in a tree hierarchy.

uniqueidentifier This data type indicates the 16 byte GUID. It is used to convert a string constant
in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. Here, x is a hexadecimal digit
(0-9 and a-f).

XML This data type is used to store XML data in a SQL Server table. Its storage limit is
2 GB.

Spatial Geometry It is a spatial planar data type used to represents data in a flat (Euclidean)
Types coordinate system.

Spatial It is a geography spatial data type used for storing ellipsoidal (round-earth) data,
Geography Types such as GPS latitude and longitude coordinates.

sql_variant This data type is used to store values of other SQL Server data types.

table It is a spatial data type used to store the temporary result in a table-valued
function. This data is used for later processing. We can use it by using the syntax
as DECLARE @local_variable. It can also be used in functions, stored procedures,
and batches.
SQL Server Login Database
SQL Server login database is a simple creadential which is used to access SQL Server.

What is credential?
Credentials are simply a username and a password that you provide your username and password
when logging on to Windows or even your e-mail account. This username and password builds up the
credentials.

There are four types of logins provided by SQL Server:

o A login based on Windows credentials.


o A login specific to SQL Server.
o A login mapped to a certificate.
o A login mapped to asymmetric key.

Logins based on Windows credentials facilitates you to log in to SQL Server using a Windows
username and password. If you want to create your own credentials (username and password,) you
can create a login specific to SQL Server.

To create, alter, or remove a SQL Server login, you can take one of two approaches:

o Using SQL Server Management Studio.


o Using T-SQL statements.

Using SQL Server Management Studio


Open SQL Server management studio

Go to Security:
Open Security. You will see "Logins". Right click on Logins and you will get "New Login"?
It will open a new page:
Here you can set a login name and password.

SQL Server CREATE DATABASE


A database is an organized collection of data that is structured into tables, rows, columns, and
indexes. It helps the user to find the relevant information frequently. It enables the user to access and
manage the records through the database very easily. Usually, each database in SQL Server stores all
files in the form of tables.

Why we need a database?


Most companies and organizations need a database because it maintains all of its relevant
information, such as employee records, transactional records, salary information, etc. The following
are the popular reasons for the need for the database:
Manages large amounts of data: Each database can store and manage a large volume of data at a
single place on a daily basis. There are no other tools available, including a spreadsheet, to do the
same.

Accurate: Each database can store the data accurately because it provides built-in constraints, checks,
and other features. Therefore, database information is almost always guaranteed to be correct.

Easy to update: A user can easily update the database using various Data Manipulation languages
(DML) commands such as SQL, SQL Server, etc.

Security: Each database enables users to ensure the security of data using various methods. For
example, a login is required to access the database or give the rights to access only specific parts of
the database, not all.

Data integrity: Each database ensures that the stored data is accurate and consistent. A user can do
this by using various constraints for data or conform to ACID property rules.

Easy to research data: A database enables users to search and find the relevant information quickly
using the Data Query Languages (DQL).

SQL Server provides two types of database:

1. System databases
2. User Databases
System Databases: The system databases are created automatically while installing the MS SQL
Server on our system. It plays an essential role in the server such database run perfectly. The following
are the list of system databases in SQL Server:

o Master
o Model
o MSDB
o Tempdb

User Databases: The user databases are created by database users like DBAs and testers who can
access a database also.

We can create a database in SQL Server mainly in two ways:

o Transact-SQL Command
o SQL Server Management Studio

Let us discuss them one by one in detail.

CREATE DATABASE using T-SQL Command


The below syntax enables the users to create a new database in SQL Server:

1. CREATE DATABASE database_name

In the above syntax, the database_name indicates the name of a new database.

Rules to create a new database

We must follow the following rules for creating a new database:

o The name of a new database should be unique within a particular server instance.
o Each database should have a maximum of 128 characters.
o The CREATE DATABASE command should be executed in auto-commit mode.

Example
Let us understand how to create a database in SQL Server through an example. To do this, first, open
the Management Studio and connect with the database engine by giving the server address and the
authentication details. Then, click a new query from the standard bar.

Once the connection becomes successful, execute the below statement to create a new database
named DemoDb:
1. CREATE DATABASE DemoDb;

We can see the newly created database in the Object Explorer once the statement has been
successfully executed. If it does not show here, we need to click the refresh button or pressing
the F5 on our keyboard to update the object list. See the below image:

SQL Server allows the user to list all databases stored in the database engine by using the following
command:

1. SELECT name FROM master.sys.databases ORDER BY name;

Executing the statement will display the list of all databases:

SQL Server allows the stored procedure statement to list all databases stored in the database engine
as below:

1. SELECT name FROM master.sys.databases ORDER BY name;


Executing the stored procedure will display the list of all databases, including its size and remarks if
any. Otherwise, this field is shown NULL.

CREATE DATABASE using SQL Server Management Studio


SQL Server Management Studio is a GUI tool that enables DBA to configure, manage, and administer
all components of SQL Server instead of using the command line. We can create a database in SSMS
with the help of the following steps:

Step 1: Open the SSMS in administrator mode to avoid any permission issue. We will see the below
screen where we will first connect with the server. Here, we must fill in the server name, server type,
authentication information and then click on Connect button to continue.

Step 2: Once the connection becomes successful, the Object Explorer window will appear on the
left-hand side of the screen. The server we are connected to is shown at the top of the Object
Explorer. To see the Database folder, click the "+" button if it isn't extended.
Step 3: The next step is to right-click on the Databases folder and choose a New Database from the
dropdown list to create a database.

Step 4: The next step will open the New Database dialog box. Here we can configure the database
before creating it. Now, type the database name, change the setting if required, and then click the Ok
button. In most cases, the DBA leaves the settings at their default.
Step 5: Once the database creation is successful, we can see them by expanding the Databases folder
under the Object Explorer. The database icon has a cylinder icon.

This article will explain the complete overview of creating a new database in SQL Server using the SQL
Server Management Studio (SSMS) and SQL command.
MS SQL Server Select Database
SQL Server select database specifies your database in which you want to create your table and further
operations.

SQL Server DROP Database


Sometimes a database is not relevant or obsolete on our server instance. In that case, we can delete
or remove them from the server. When we remove the database, it will also permanently delete all the
tables, indexes, and constraints. Therefore, we should have to be very careful while dropping the
database because we will lose all the data available in the database. If the database is not available on
the server instance, SQL Server will throw an error message.

We can drop a database in SQL Server mainly in two ways:

o Transact-SQL Command
o SQL Server Management Studio

Let us discuss them one by one in detail.

DROP database using T-SQL Command


SQL Server enables users to remove the database from the server instance by using the below syntax:
1. DROP DATABASE [IF EXIST] database_name

If we want to delete more than one database within a single command, we can use the comma-
separated list of database names as below:

1. DROP DATABASE [ IF EXISTS ] database_name , database_name2, ...;

In this syntax, the database_name indicates the name of a database we want to remove from the
server instance. The IF EXIST is an optional clause indicating the database will be deleted if it already
exists in the server.

We must remember the following points before deleting a database:

1. The DROP DATABASE command will delete the database as well as the database's physical disc
files. As a result, we are required to keep a database backup if we need to recover it in the
future.
2. The DROP DATABASE statement should be run in auto-commit mode. It cannot be used in a
transaction, either explicit or implicit, as auto-commit is the default transaction management
mode.
3. We are unable to delete the currently active database. If we will do this, SQL Server issues the
following error:

Example
Let us understand how to delete a database, which is no longer required on the server instance. First,
we will list all databases stored in the database engine by using the following command:

1. SELECT name FROM master.sys.databases ORDER BY name;

Executing the statement will display the list of all databases:


If we want to delete a 'DemoDb' database, we can use the statement as follows:

1. DROP DATABASE IF EXISTS DemoDb;

After executing the command, click the refresh button or pressing the F5 on our keyboard to update
the object list. We can see that the DemoDb database is no longer available:

DROP Database using SQL Server Management Studio


We can drop a database in SSMS with the help of the following steps:

Step 1: Open the SSMS in administrator mode to avoid any permission issue. We will see the below
screen where we need to click on Connect button to continue.
Step 2: Once the connection becomes successful, the Object Explorer window will appear on the
left-hand side of the screen. To see the Database folder, click the "+" button if it isn't extended.

Step 3: The next step is to expand the Databases folder by clicking on the plus(+) button. We will see
all available databases in the current server instance.
Step 4: The next step is to delete the desired database. Suppose we want to delete the DemoDb
database. To do this, right-click on the selected database and choose the Delete option from the
context menu. See the below image:

Step 5: Once we click the Delete option, we will see a Delete Model Object box to confirm the
deletion process. Click on the OK button to delete the database from the SQL Server permanently.
Step 6: If everything is correct, the selected database will be deleted. We can verify this by clicking the
refresh button or pressing the F5 on our keyboard to update the object list. We can see that the
DemoDb database is no longer available:

SQL Server CREATE TABLE


A table enables the user to store data and display information in the database. It arranges the data in rows and
columns. It can have several rows and columns, and each column has a data type associated with it that
specifies the type of data it can store, such as numbers, strings, or temporal data. It is similar to worksheets in
the spreadsheet application. Three items are needed for table creation:

o Name of the table


o Names of fields
o Definitions for each field

We can create a table in SQL Server mainly in two ways:

o Transact-SQL Command
o SQL Server Management Studio

Let us discuss them one by one in detail.

CREATE TABLE using T-SQL command


We can create a table in the selected database by using the CREATE TABLE command. We can use this
statement only when we have ALTER permission on the schema where the table is created and CREATE
TABLE permission in the database. The following is a generic syntax that enables the users to create a new
table in SQL Server:

1. CREATE TABLE [database_name.][schema_name.]table_name (


2. column_definition1,
3. column_definition2,
4. ........,
5. table_constraints
6. );

Parameter Explanation
The parameter descriptions of the above syntax are as follows:

00:00/02:28

database_name: It is the database name in which we are going to create a table. It must be existing in the
defined database. Otherwise, it will assume the current database by default.

schema_name: It indicates the schema to which our newly created table belongs.

table_name: It is the name of the new table and must be unique in the selected database. It should be a
maximum of 128 characters.

column_definition: It indicates the column names of the table along with data types for each column. These
data types can be int, float, char, varchar, text, datetime, and Boolean. The columns in the table definition are
separated by the comma operator.

table_constraints: It indicates the table constraints such as PRIMARY KEY, UNIQUE KEY, FOREIGN
KEY, CHECK, etc.
We should provide a primary key column for each table. It can have single or multiple columns. Usually, we
use the first column as a primary key and then other columns. If we define only one primary key column in a
table, we should use the PRIMARY KEY keywords. Otherwise, it is advised to define a PRIMARY KEY as a
table constraint. A column can have single or multiple constraints, such as CHECK, UNIQUE, and NOT
NULL.

Example
Let us understand how we can create a table in SQL Server with the help of an example. Here, we are going to
create a table named "Student" using the following statement:

1. CREATE TABLE TestDB.dbo.Student(


2. Id INT IDENTITY PRIMARY KEY,
3. Name VARCHAR(65) NOT NULL,
4. Gender VARCHAR(20),
5. Age INT,
6. Marks INT
7. )

In the above statement, we have created a 'Student' table in the 'TestDB' database under the 'dbo' schema.
This table contains five columns Id, Name, Gender, Age, and Marks. Here, we have defined the id column as
a primary key. The IDENTITY data type generates integer numbers that automatically begin with one and
increase by one for each new row.

After the successful execution of this statement, we will get the below output. Now, we can add records to this
table by using the INSERT statement.

CREATE TABLE using SQL Server Management Studio


We can create a table in SSMS by using the Table Designer. The following steps explain the creation of a
table using Table Designer:

Step 1: Open the SSMS in administrator mode to avoid any permission issue. We will see the below screen
where we need to click on Connect button to continue.
Step 2: Once the connection becomes successful, the Object Explorer window will appear on the left-hand
side of the screen. If the Database folder isn't visible, click the "+" icon to expand it.

Step 3: Next, expand the Databases folder by clicking on the plus (+) button. We will see all available
databases in the current server instance.

Step 4: The next step is to select the desired database in which you want to create a table and expand it. It will
display the sub-menu such as Database Diagrams, Tables, Views, and, as shown in the below screen.
Step 5: The next step is to select the Tables folder, right-click on it, we will get the pop menu. Clicking on
the New option will display a drop-down list where we will choose the Table option. See the below image:

Step 6: Once we click the Table option, we will get the Table Designer window. This window will include
the column name, data types, and Not Null constraint to select whether to allow nulls or not for each column.
For example, we want to create a table named 'Person' that will store four columns:

o FirstName
o LastName
o Mobile
o City
o Age

We can create this table by filling these column names and their data types as shown in the below image:

Step 7: If you want to define more properties for any specific column like IDENTITY or COMPUTED column
values, then clicking on the desired column will display the column properties tab. Here you can choose the
appropriate properties.

If you want to define the column as a primary key, right-click the desired column and select Set Primary Key, as
shown below:
If you want to define a foreign key relationship, check constraints, or indexes, you need to right-click anywhere
in the Table Designer pane and select the desired option from the context menu as shown below:

Step 8: A table stored in the dbo schema by default. If you want to store the table in a different schema, you
need to right-click anywhere in the Table Designer pane and select Properties. We will see the below drop-
down list where we can select the appropriate schema.
Step 9: Once we have done, navigate to the File menu, and choose the Save table name.

When we click the save button, SQL Server will display a box to choose the name of a table. Write your desired
name for the table and click OK. For example, we have given a Person name for our table:

Step 10: Once the table creation is successful, we can see them by expanding the Tables folder under the
Object Explorer and press the F5 button on our keyboard to refresh the list of objects. Now, we can see the
new table (Person) in the list of tables.

This article will explain the complete overview of creating a new table in SQL Server using the T-SQL
statement and SQL Server Management Studio (SSMS).

SQL Server DELETE or DROP Table


SQL Server allows DBA to remove a table, which is not relevant or obsolete in our database. When we
remove a table, the complete data and the whole structure or definition are deleted permanently
from the table. Therefore, we should have to be very careful while dropping a table from the specified
database. If the SQL Server does not find the target database table, it will throw an error message.
SQL Server provides mainly two ways to remove a table:

o Transact-SQL Command
o SQL Server Management Studio

Let us discuss them one by one in detail.

DROP TABLE using T-SQL command


We can use the following syntax to remove a table in SQL Server:

1. DROP TABLE [IF EXISTS] [database_name.][schema_name.]table_name;

In the above syntax,

Competitive questions on Structures in HindiKeep Watching

o We need first to write the table name that we want to remove. Next, we need to specify the database
name in which the table is stored, and the schema name indicates to which this table belongs. It
should note that the database name is optional. If we omit this, this query will remove the table from
the currently connected database.
o The IF EXIST is an optional clause indicating the table will be deleted only if it already exists in the
database. This clause is available since SQL Server 2016 13.x.

If we want to delete more than one table within a single command, we can use the comma-separated
list of table names as below:

1. DROP TABLE [IF EXISTS] [database_name.][schema_name.]table_name1,


2. [schema_name.]table_name2.....
3. [schema_name.]table_nameN;

When we remove a table in SQL Server, it also erases all of the table's data, triggers, constraints, and
permissions. This query does not allow deletion of the views, user-defined functions, and stored
procedures explicitly referencing the dropped table. Hence, we should use the DROP
VIEW and DROP PROCEDURE statements if we want to remove these objects explicitly.

We must remember the following points before deleting a table:

1. The DROP TABLE query will delete the table, including its physical disc files. Therefore, we must keep a
backup if we need to recover it in the future.
2. If a foreign key constraint references the table, this query does not drop a table. If we want to do this,
we will first remove the referencing foreign key constraint or the table. Also, we first list the referencing
table in an event when the reference table and the primary key table are both being deleted in the
same DROP TABLE statement.
3. This statement does not remove the data stored in the file system when the table has a varbinary (max)
column with the FILESTREAM

NOTE: We must have an ALTER privilege on the schema to which the table belongs and
CONTROL privilege on the table to execute the DROP TABLE statement.

Example
This example specifies how we can drop an existing table from the database. Suppose our database
has a table named "student_data" containing the following data:

If we want to drop this table from the database, we can use the statement as follows:

1. DROP TABLE [dbo].[student_data]

It will remove the table permanently. If we re-access this table, we will get an error message as shown
in the below output:

If we try to remove a table that does not exist in the database, SQL Server will through the following
error message:
However, if we try to delete a table that is not available in the database with the IF EXISTS clause, SQL
Server does not show any error or warning message. See the below output:

DROP TABLE using SQL Server Management Studio


We can also use the SSMS to drop a table from the database. The following steps explain how to
delete a table using SSMS:

Step 1: Open the SSMS and then navigate to the Object Explorer-> Database -> Tables folder. It
will show all available tables.

Step 2: Select your desired table that is no longer required in your database and right-clicks on it to
get the pop menu. Now, select the Delete option from the appeared menu. See the below image:
Step 3: Once we click on the Delete option, we will see the Delete Model Object box to confirm the
deletion process. Click on the OK button to delete the database from the SQL Server permanently.
Step 6: If everything is correct, the selected table will be removed from the database. We can verify
this by clicking the refresh button or pressing the F5 on our keyboard to update the object list. We
can see that the 'backup_employee' table is no longer available.

SQL Server Insert Data


INSERT statement in SQL Server is used for adding records in a table within the specified database.
SQL Server performs insertion operation in two ways within a single query:

o Add data in a single row


o Add data in multiple rows

Syntax:
The following syntax of INSERT INTO command allows us to add single row in a table:

1. INSERT INTO [database_name].[dbo].[table_name]


2. (column_name1, column_name2, ... )
3. VALUES
4. (value1, value2, ... );
Parameter Explanation
The parameter descriptions of the above syntax are as follows:

o database_name: It indicates the database name that stored the table in which we are going to insert
data. If we do not specify the database name, it will assume the current database by default.
o schema_name: It indicates the schema to which table belongs.
o table_name: It is the table name in which we want to add data.
o column_name1, column_name2…column_nameN: It is the name of our table columns.
o Value1, value2…valueN: It represents the list of values corresponding to the column's name after the
VALUES clause.

NOTE: The column name is optional. However, if we want to specify partial values, we need to
specify its name mandatory. It also ensures that the column name and values and their position
should be the same.

If we want to insert multiple records within a single command, we can use the following syntax:

1. INSERT INTO [database_name].[dbo].[table_name]


2. VALUES
3. ( value1, value2,...valueN )
4. ( value1, value2,...valueN )
5. ...........
6. ( value1, value2,...valueN );

SQL Server will add these values automatically to a column that exists in the table but doesn't appear
in the INSERT command's column list:

o If the column has an IDENTITY property, it will add the next incremental value.
o If we define a default value for a column, it will add that value.
o If we have specified the column's data type as a timestamp data type, it will add the current timestamp
value.
o If the column is nullable, it will add the NULL value.
o If the column is a computed value, it will add the calculated value.

SQL Server Insert Data Example


Let us understand how INSERT statements work in SQL Server with the help of multiple examples.
First, we will create a table "Student" in the database using the following command:

1. CREATE TABLE dbo.Student(


2. Id INT IDENTITY PRIMARY KEY,
3. Name VARCHAR(65) NOT NULL,
4. Gender VARCHAR(20),
5. Age INT,
6. Marks INT
7. )

Let's insert data into this table as follows:

1. f we want to store single records for all fields, use the syntax as follows:

1. INSERT INTO Student (Name, Gender, Age, Marks)


2. VALUES ('Peter Huges', 'Male', 32, 450);

Here, we have not specified the Id column because it has an identity property that automatically
inserts numeric data and increments each row. However, if we insert data for all columns, it is optional
to specify the column names. Therefore, the INSERT statement can also be written as:

1. INSERT INTO Student


2. VALUES ('Johnny Paul', 'Male', 35, 470);

We can verify the data using the SELECT statement:

2. SQL Server also allows the user to insert more than one record within a single statement. The
following command inserts three records at the same time:

1. INSERT INTO Student


2. VALUES ('Jolly Evans', 'Female', 28, 475),
3. ('Alan Simmons', 'Male', 32, 405),
4. ('Laura Bennet', 'Female', 30, 435);

Verifying the data will display the below output:


3. Sometimes, we want to store records without giving all column's names. In that case, we can use
the following statement where we specify only partial fields. All unspecified fields will add NULL value
except the identity column.

1. INSERT INTO Student (Name, Gender)


2. VALUES ('Diego Bennet', 'Male');

This statement is executed successfully. Verifying the data will display the below output:

INSERT with SELECT statement:


SQL Server also allows us to insert records from one table into another table using the INSERT INTO
SELECT statement. Suppose we want to insert 'Student' table data into 'Student_info'. We can do
this by using the following statement:

1. INSERT INTO Student_info


2. SELECT Name, Gender, Marks FROM Student;

This statement is executed successfully. Verifying the data will display the below output:
To read more information, click here.

How to insert and return inserted values?


SQL Server provides the OUTPUT clause for capturing the inserted values into a defined table. We can
explain this concept by using the below statement that inserts a new record into the 'Student' table
and returns the inserted value of the 'Marks' column:

1. INSERT INTO Student (Name, Gender, Age, Marks )


2. OUTPUT inserted.Marks
3. VALUES ('J P Dumini', 'Male', 32, 450);

Here is the output:

If we want to capture inserted values from multiple columns, we are required to specify the columns
in the output as follows:

1. INSERT INTO Student (Name, Gender, Age, Marks )


2. OUTPUT inserted.Name,
3. inserted.Age,
4. inserted.Marks
5. VALUES ('Greme Smith', 'Male', 36, 455);

Here is the output:


How to insert explicit values into the identity column?
We know that SQL Server does not specify a value for the identity column explicitly because they
automatically provide the value for this column. If we try to do this, we will get the following error
message:

"Cannot insert explicit value for identity column in table 'student' when IDENTITY_INSERT is set
to OFF."

However, SQL Server allows inserting a value into the identity column explicitly in some situations,
such as data migration. We can do this by executing the below statement before inserting a value
into the identity column explicitly:

1. SET IDENTITY_INSERT table_name ON;

Let's execute the following statements to insert a value for the identity column in the Student table:

1. INSERT INTO Student (Id, Name, Gender, Age, Marks )


2. VALUES (9, 'Maria Smith', 'Feale', 32, 465);

After executing this statement, we can see that the statement is executed correctly.

Now, we can execute the below statement to switch the identity insert off:

1. SET IDENTITY_INSERT table_name OFF;


SQL Server Update Data
UPDATE statement in SQL Server is a DML statement used to update or modify the already existing
records into a table or view. This statement is required in the real-life scenario where our data stored
in the table changes regularly. This article helps to learn how the UPDATE statement works with the
tables or views in SQL Server with different options.

The UPDATE query is always recommended to use with the SET and WHERE clause. We can modify
or update the single or multiple columns at a time. It should note that this query does not display any
result set. Also, we cannot undo the modification once it is executed. However, if we accidently do the
updation, we need first to find the changes using the SELECT statement and then execute the UPDATE
query by applying the same criteria. Therefore, it is advised to keep the backup copies of all the tables
that help to recover the wrongly updated data.

Syntax
The following syntax illustrates the UPDATE statement in SQL Server:

1. UPDATE [database_name].[ schema_name].table_name


2. SET column1 = new_value1,
3. column2 = new_value2, ...
4. [WHERE Clause]

Parameter Explanation
The above syntax parameter description is given below:

Parameter Descriptions

database_name It is the database name in which our table is stored.

schema_name It indicates the schema to which the specified table belongs

table_name It is the name of an existing table in which we want to perform modifications or updation.

SET It indicates the column's names and their values to be updated. If there is a need to update
multiple columns, separate the columns with a comma operator by specifying the value in
each column.
WHERE It is an optional clause that indicates the row name in which we are going to perform
updation. It is recommended to use this clause because sometimes we want to update only a
single row, and if we omit this clause, the whole records of the table will be updated.

Example
Let us understand the UPDATE statement with the help of various examples. Suppose we have a table
"Student" within the "javatpoint" database that contains the following data:

Update Single Column


If we want to update the 'Marks' of the student name 'Alan Simmons', we can do this by using the
following query:

1. UPDATE Student
2. SET Marks = 492
3. WHERE Name = 'Alan Simmons';

After successful execution, we will verify the table using the below statement:

1. SELECT * FROM Student;

We will see the below output where we can see that our table is updated as per our conditions.
Update Multiple Column
The UPDATE statement can also use to update more than one column within a single statement. For
example, the below query will update the 'Age' and 'Marks' of the student name 'Diego
Bennet' that contains a NULL value:

1. UPDATE Student
2. SET Age = 28, Marks = 492
3. WHERE Name = 'Diego Bennet';

After successful execution, we will use the SELECT statement again to verify the updation. We will see
the below output where we can see that our table is updated as per our conditions.

UPDATE with SQL Server Management Studio (SSMS)


We can also use the SSMS to update the table's data. The following steps explain how to update data
in a table using SSMS:

Step 1: Open the SSMS and then navigate to the Object Explorer-> Database -> Tables folder. It will
show all available tables.

Step 2: Select your desired table in which you want to make changes and right-click on it to get the
pop menu. Now, select Script Table as -> UPDATE to -> New Query Editor Window options from
the drop-down list. See the below image:

Step 3: Once we click on "New Query Editor Window", we will see the following query page:
Next, use the following command to update the table:

1. UPDATE [dbo].[Student]
2. SET [Name] = 'Peter Huges'
3. ,[Gender] = 'Male'
4. ,[Age] = 26
5. ,[Marks] = 478
6. WHERE [Id] = 1

Executing the statement, we can see that 1 row is affected.


After execution, we can see that the above records are now updated:

SQL Server DELETE Data


In SQL Server database, DELETE statement is used to delete records from the table.
Syntax:

1. SELECT TOP 1000 [ID]


2. ,[NAME]
3. ,[AGE]
4. ,[SALARY]
5. FROM [javatpoint].[dbo].[STUDENT]

Use the SQL Server management Studio:

Follow the management studio screenshots given below:


Use the following command:

1. DELETE FROM [javatpoint].[dbo].[STUDENT]


2. WHERE ID =3;
Here one row is deleted where ID=3. You can verify it:

Output:
SQL Server DELETE Top Statement
In SQL Server, DELETE TOP statement is used to delete the records from a table and limit the number
of records deleted regarding a fixed value or percentage.

Syntax:

1. DELETE TOP (top_value) [ PERCENT ]


2. FROM [database_name].[dbo].[table_name]
3. [WHERE conditions];

Parameter explanation
table: It specifies a table that you want to delete records from.

WHERE conditions: It is optional. The conditions that must be met for the records to be deleted.

x
TOP (top_value): It is used to delete the top number of rows in the result set based on top_value. For
example, TOP(10) would delete the top 10 rows matching the delete criteria.

PERCENT: It is optional. It is used to delete the percentage of of top rows. For example, TOP(10)
PERCENT would delete the top 10% of the records matching the delete criteria.

DELETE using TOP keyword


TOP keyword is used with DELETE statement to delete the specified top rows of a table.

Example:

We have a table "Employees", having the following data.


Delete top 2 rows from the table "Employees" where salary is greater than or equal to 20000.

Syntax:

1. DELETE TOP(2)
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE salary >= 20000;
You can see that 2 rows are affected. Now see the output:

Output:
DELETE using TOP Percent Keyword
TOP percent keyword is used to delete the rows according to the percentage.

Example:

Delete TOP 25% rows from the table where salary is greater than 20000.

1. DELETE TOP(25) PERCENT


2. FROM [javatpoint].[dbo].[Employees]
3. WHERE salary > 20000;
You can see that 3 rows are affected. 3 is exactly 25% of 12 which is the number of inserted rows.

Output:
SQL Server ALTER Table
ALTER command in SQL Server is used to make modifications in an existing table. These
alterations can be adding a column, deleting a column, changing the size, modifying the data type,
adding or removing indexes, and adding or deleting constraints in a table definition. It also allows us
to rename and rebuild partitions and disable and enable constraints and triggers. This article will
explain all the alterations possible in a table with various examples.

We are going to take a table named 'Student' for demonstration of all examples.
SQL Server Add New Column
A database developer several times need to add a new column to the existing table. They can do this
by using the ALTER TABLE ADD COLUMN command. It will always add the new column at the last
position in the table. The syntax to add a new column is given below:

1. ALTER TABLE table_name ADD column_name data_type column_constraints;

In this syntax, we will first specify the table name that we want to modify. Then, we will specify
the new column name that we want to add to the table. Finally, we will specify the data type and
constraints for the column.

00:00/01:27

If we want to add more than one column, we can use the following syntax:

1. ALTER TABLE table_name


2. ADD column_name1 column_definition,
3. ADD column_name2 column_definition;

Example

Suppose we want to add a new column 'Phone_number' into the Student table. We can do this by
using the below command:

1. ALTER TABLE Student ADD Phone_number VARCHAR(20) NULL;

We can verify the newly inserted column in the table using the SELECT statement. See the below
image where the column is added as the last column in the table:
SQL Server Delete Column
We can also use the ALTER command to remove single or multiple columns from the table. SQL
Server provides the ALTER TABLE DROP COLUMN statement to delete the existing column from the
table. To do this, we can use the following syntax:

1. ALTER TABLE table_name DROP COLUMN column_name;

In this syntax, we will first specify the table name in which we want to make the modification. Then, we
will specify the column name that we want to remove from the table after the DROP COLUMN clause.

If we want to delete more than one column, we can use the following syntax:

1. ALTER TABLE table_name


2. DROP COLUMN column_name1, DROP COLUMN column_name2...

Example

Suppose we want to drop a 'Phone_number' column from the Student table. We can do this by
using the below command:

1. ALTER TABLE Student DROP COLUMN Phone_number;

We can verify whether this column is deleted or not from the table using the below statement:

1. EXEC sp_help 'dbo.Student';

See the below image where the phone_number column is no longer available in the table:
SQL Server Modify Column Data Type
We can also use the ALTER command to change the column's data type into the specified table. SQL
Server provides the ALTER TABLE ALTER COLUMN statement to modify the column data type. We
can do this by using the following syntax:

1. ALTER TABLE table_name ALTER COLUMN column_name new_data_type(size);

In this syntax, we will first specify the table name in which we want to make the modification. Then, we
will specify the column name that we are going to modify and finally define its new data type with
size.

We must ensure that old and new column data types must be compatible. Otherwise, SQL Server
gives a conversion error if the column contains a value.

Example

We have already defined the 'Gender' column's datatype of the 'Student' table as 'VARCHAR' and
length 20. Now, we want to change it from VARCHAR to NVARCHAR, and the size is 10. To do this,
we will use the following syntax:

1. ALTER TABLE [Student] ALTER COLUMN Gender NVARCHAR(10);

We can verify whether this column is changed or not from the table design option in SQL Server
Management Studio as below:

See the below image where we can see that the Gender column data type is changed successfully in
the table:
Add Constraint on the Column
We can also use the ALTER command to add or remove the constraints into the specified table. SQL
Server provides the ALTER TABLE ADD CONSTRAINT statement for adding a constraint to the
specified column. The following syntax illustrates this alteration:

1. ALTER TABLE table_name


2. ADD CONSTRAINT [constraint_name] PRIMARY KEY ([column_name])

In this syntax, we will first specify the table name in which we want to make the modification. Next,
we will specify the constraint name after the ADD keyword. Next, specify the constraint type such as
PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK, and DEFAULT, and finally define
the column name.

Example

Suppose we want to add a PRIMARY KEY constraint on the Id column into the Student table. We
can do this by using the below statement:

1. ALTER TABLE Student ADD CONSTRAINT PrimaryKey PRIMARY KEY (Id);

After successful execution, we can verify whether the primary key is added or not in the Id column
using the table design option in SQL Server Management Studio. In the below image, we can see that
the primary key is added successfully in the column:

Drop Constraint on the Column


SQL Server provides the ALTER TABLE DROP CONSTRAINT statement for removing constraints from
the specified column. The following syntax illustrates this alteration:

1. ALTER TABLE table_name DROP CONSTRAINT [constraint_name]

In this syntax, we will first specify the table name in which we want to make the modification. Next, we
will specify the constraint name after the DROP CONSTRAINT keyword.

Example
Suppose we want to drop the above-created constraint on the Id column from the Student table. We
can do this by using the below statement:

1. ALTER TABLE Student DROP CONSTRAINT PrimaryKey;

After successful execution, we can verify whether the primary key is deleted or not from the Id column
using the table design option in SQL Server Management Studio. In the below image, we can see
that the primary key is deleted successfully:

Add a NOT NULL Constraint to a NULLABLE Column


We can also change the nullable column into a NOT NULL column. To do this, we first need to update
the NULL to non-null and then add the NOT NULL constraint to the column.

Example

The Age column of the Student table allows us to store null values. If we want to change it from null
to NOT NULL, we must update NULL to non-null first using the below statement:

1. UPDATE Student SET Age = '' WHERE Age IS NULL;

Now, we can add the NOT NULL constraint using the below statement:

1. ALTER TABLE Student ALTER COLUMN Age VARCHAR (10) NOT NULL;

Let us insert a row without containing a value into the Age column:

1. INSERT INTO Student (Name, Gender, Marks) VALUES


2. ('Maria Smith', 'Female', 435);

We will get the following error:


However, if we insert a value into the Age column, it will be executed successfully:

1. INSERT INTO Student (Name, Gender, Age, Marks) VALUES


2. ('Maria Smith', 'Female', 29, 435);

Here is the output:

View in SQL Server


A view is a database object that has no values. It is a virtual table, which is created according to
the result set of an SQL query. However, it looks similar to an actual table containing rows and
columns. Therefore, we can say that its contents are based on the base table. It is operated similarly to
the base table but does not contain any data of its own. Its name is always unique, like tables. The
views differ from tables as they are definitions that are created on top of other tables (or views). If any
changes occur in the underlying table, the same changes reflected in the views also.
This diagram illustrates the concept of a view that included columns from more than one table. Here
we have two tables named 'Table A' and 'Table B,' and by using a SQL statement, a view is created
containing data from both tables. Views are a database object; that's why it does not store physically.
This feature makes views excellent for abstracting or hiding complex queries.

Uses of views
The primary use of view in SQL Server is to implement the security mechanism. It prevents users from
seeing specific columns and rows from tables. It only shows the data returned by the query that was
declared when the view was created. The rest of the information is completely hidden from the end-
user.

Types of views
The SQL Server categories the views into two types:

1. User-Defined Views

Users define these views to meet their specific requirements. It can also divide into two types one
is the simple view, and another is the complex view. The simple view is based on the single base
table without using any complex queries. The complex view is based on more than one table along
with group by clause, order by clause, and join conditions.

2. System-Defined Views
System-defined views are predefined and existing views stored in SQL Server, such as Tempdb,
Master, and temp. Each system views has its own properties and functions. They can automatically
attach to the user-defined databases. We can divide the System-defined views in SQL Server into
three types: Information Schema, Catalog View, and Dynamic Management View.

SQL Server allows us to create a view in mainly two ways:

o Using T-SQL Query


o Using SQL Server Management Studio

Let us explain both ways in detail.

Using T-SQL Query


We can create a new view by using the CREATE VIEW and SELECT statement. SELECT statements are
used to take data from the source table to make a VIEW.

Syntax

The following syntax is used to create a view in SQL Server:

1. CREATE VIEW view_name AS


2. SELECT column1, column2, ...
3. FROM table_name
4. WHERE condition;

In this syntax, the view_name indicates the name of a view. It should be unique.
The SELECT statement chooses columns from the source table. The WHERE is an optional clause
specifying the conditions that must be met for the records to be included in the VIEW.

Example

Let us understand it with the help of an example. Suppose our database has a table
named Student and Fee that contains the following data:
Now, we will create a view based on these tables. Thus, the below example will create a view name
"course" that creates a virtual table made by taking data from both tables.

1. CREATE VIEW course_enrolled


2. AS
3. SELECT first_name, last_name, course, amount_paid
4. FROM Student AS S
5. INNER JOIN Fee AS F
6. ON S.admission_no = F.admission_no;

We can verify the view data using the SELECT statement as below:

1. SELECT * FROM course_enrolled;

This query will display the below output:

Rename views in SQL Server


We can also change the name of a view in SQL Server. We can do this by using the built-in stored
procedure named sp_rename or the SQL Server management studio. Here we will see both ways:

Using sp_rename
The following syntax is used to rename a view:

1. SP_RENAME View_Old_Name, View_New_Name

Suppose we want to change the name of the above-created view course_enrolled to course. The
following query explains this concept:

1. sp_rename course_enrolled, course

Using SQL Server Management Studio


To change the name of a view in SSMS, we need to navigate to the Object Explorer -> Databases ->
Views. Here you will see all available views. Select one that you want to modify, right-click on it and
select the Rename option. For example, we are going to rename a view name course as follows:

Once we click the Rename option, we are able to change its name:

Update views in SQL Server


We can also update a view in SQL Server. We can do this by using the ALTER VIEW command or the
management studio. Here we will see both ways:
ALTER VIEW Statement

Suppose we want to add one more column named 'city' in the above-created view course_enrolled.
To do this, we need to use the statements as follows:

1. ALTER VIEW course_enrolled


2. AS
3. SELECT first_name, last_name, course, city, amount_paid
4. FROM Student AS S
5. INNER JOIN Fee AS F
6. ON S.admission_no = F.admission_no;

We can verify this modification by using the SELECT statement. It will display the below output where
we can see that the city column is added successfully.

Using SQL Server Management Studio


To alter an existing view using SSMS, we need to navigate to the Views. Then, select your desired
view name that you want to modify, right-click on it and select the Design option. For example, we
are going to modify a view name course_enrolled as follows:

This option will display a new design query window with existing tables and their relationship. Here
we can make any changes to our views.
How to get views definition in SQL Server?
SQL Server provides the sp_helptext stored procedure that allows us to get the information of any
views. We can use the below syntax to see the definition of a view:

1. SP_HELPTEXT view_name

Suppose you want to see the definition of a course_enrolled view. You can do this as follows:

1. SP_HELPTEXT course_enrolled

It will display the following output:


List views in SQL Server
We can use the sys.views or sys.objects catalog view to list or display all views available in a SQL
Server Database. Here is an example:

1. SELECT OBJECT_SCHEMA_NAME(v.object_id) schema_name, v.name


2. FROM sys.views as v;

Drop Views in SQL Server


We can also remove the existing view from the SQL Server. We can do this by using the SQL query or
the management studio. Here we will see both ways:

Using SQL Query

SQL Server provides a DROP VIEW command to remove the view from a database. If the view does
not exist, we will get an error. We can use the below syntax to remove a view:

1. DROP VIEW [IF EXISTS] schema_name.view_name;

Suppose you want to delete a view course_enrolled, we can do this as follows:

1. DROP VIEW course_enrolled

It will delete the view successfully. If we execute this command again, we will get the below error
message:

Using SQL Server Management Studio


To remove an existing view using SSMS, we need to navigate to the Views. Select your desired view
name that you want to delete, right-click on it and select the Delete option. For example, we are
going to drop a view name course as follows:

Once we click on the Delete option, we will get a new window to confirm the deletion process. Click
on Yes to complete the deletion. We will make sure that it will delete all permission of a view also.

SQL Server MIN Function


The MIN() function in SQL Server is a type of aggregate function. It is used to get the minimum or
smallest value of a specified column or expression. It is the most commonly used built-in function in
the SQL Server. It comes under the numeric function that accepts only one parameter and returns a
single result after evaluation to summarize the input data set. We can use this function with several
clauses such as WHERE, GROUP BY, ORDER BY, and HAVING clause to get the filtered output.

Syntax
The following syntax explain the MIN() function in SQL Server:

1. SELECT MIN ( DISTINCT aggregate_expression)


2. FROM table_name(s)
3. [WHERE conditions];

The function parameters are explained below:


aggregate_expression: It is the required expression that represents the column name from which the
lowest value is returned.

table_name(s): It indicates the name of a table from where we want to retrieve columns. There can be
specified more than one table.

WHERE conditions: It is an optional clause to define a condition to filter the column or expressions.

DISTINCT: It returns the lowest of the unique values in the expression. However, it does not affect the
MIN() function and produces the same result without using this keyword.

NOTE: The MIN() function ignores NULL values.

MIN() Function Example


Let us understand how the MIN function works in SQL Server with the help of various examples.
Consider our database has a table named "ProductQty" that contains the following data:
Example1: This example uses the MIN() function to get the minimum quantity of the sold products
from the table:

1. SELECT MIN(Quantity) AS "Minimum Quantity" FROM ProductQty;

Executing the statement will display the result of minimum values in all rows:

Example2: This example uses the WHERE clause with the MIN() function. This clause is used to filter
the records from the table. The below statement will display the product name with the lowest
quantity sold:

1. SELECT Product, Quantity, Price


2. FROM ProductQty
3. WHERE Quantity = (
4. SELECT MIN(Quantity) AS "Minimum Quantity"
5. FROM ProductQty);

Here, SQL Server first evaluates the subquery that uses the MIN() function and then the outer query
display the product name whose quantity is equal to the result of the subquery. Executing the
statement will return the desired output:
Example3: This example uses the GROUP BY clause with the MIN() function. This clause collects data
from multiple rows and groups them based on single or multiple columns. The below statement will
return the minimum quantity in all rows from the ProductQty table for each product group.

1. SELECT Product, MIN(Quantity) AS "Minimum Quantity"


2. FROM ProductQty
3. GROUP BY Product;

Executing the statement will display the minimum quantity of each product:

Example4: This example uses the HAVING clause with the MIN() function. This clause must be used
with the GROUP BY clause to filter the grouped records from the table. The below statement will
display the product name with a minimum quantity greater than 200.

1. SELECT Product, MIN(Quantity) AS "Minimum Quantity"


2. FROM ProductQty
3. GROUP BY Product
4. HAVING MIN(Quantity)>100;

Executing the statement will return the below output:

Example5: This example uses the DISTINCT clause with the MIN() function. This clause is used to
remove the duplicate rows from the column. The below statement returns the minimum sold product
quantity by removing the duplicates data from the "Quantity" column of a "ProductQty" table.

1. SELECT Product, MIN( DISTINCT Quantity) AS "Minimum Quantity"


2. FROM ProductQty
3. GROUP BY Product;

Here is the result:


Example6: This example uses the MIN() function with two columns to get the lowest resultant output:

1. SELECT Product, MIN(Quantity * Price) AS "Lowest Value"


2. FROM ProductQty
3. GROUP BY Product;

Executing the statement will return the lowest values of (Quantity * Price) from the ProductQty table:

Example7: This example uses the OVER() clause with the MIN() function. This clause determines
which rows from the query are applied to the function, in what order the function evaluates them, and
when the function's calculations should restart.

1. SELECT DISTINCT Product,


2. MIN(Quantity) OVER (PARTITION BY Product) AS "Lowest Quantity"
3. FROM ProductQty;

Executing the query will return the below result:

SQL Server MAX() Function


The MAX() function in SQL Server is a type of aggregate function. It is used to get the maximum or
largest value in a group of values of a specified column or expression. It is the most commonly used
built-in function in the SQL Server. This function accepts a single parameter that can be a column or
valid expression and returns a single result to summarize the input data set. It can also work with the
WHERE, GROUP BY, ORDER BY, and HAVING clauses to get the filtered result.

Syntax
The following syntax explain the MAX() function in SQL Server:

1. SELECT MAX ( DISTINCT aggregate_expression)


2. FROM table_name(s)
3. [WHERE conditions];

The function parameters are explained below:

aggregate_expression: It is the required expression that represents the column name from which the
largest value is returned.

table_name(s): It indicates the name of a table from where we want to retrieve columns. There can be
specified more than one table.

WHERE conditions: It is an optional clause to define a condition to filter the column or expressions.

DISTINCT: It returns the largest of the unique values in the expression. However, it does not affect
the MAX() function and produces the same result without using this keyword.

NOTE: The MAX() function ignores NULL values. It returns NULL when no row is found.

MAX() Function Example


Let us understand the use of a MAX function in SQL Server with the help of various examples.
Consider our database has a table named "ProductQty" that contains the following data:
Example1: This example uses the MAX() function to get the maximum quantity of the sold products
in the ProductQty table:

1. SELECT MAX(Quantity) AS "Maximum Quantity" FROM ProductQty;

This statement displays the following output where we see the maximum quantity of sold products:

Example2: This example uses the WHERE clause with the MAX() function. This clause is used to filter
the records from the table. It is useful when we want to get the product name with the highest sold
quantity. See the below statement:

1. SELECT Product, Quantity, Price


2. FROM ProductQty
3. WHERE Quantity = (
4. SELECT MAX(Quantity) AS "Maximum Quantity"
5. FROM ProductQty);

Here, SQL Server first evaluates the subquery that uses the MAX() function and then the outer query
display the product name whose quantity is equal to the result of the subquery. When we execute the
statement, we will see the desired output:

Example3: This example uses the GROUP BY clause with the MAX() function. The GROUP BY clause
collects data from multiple rows and groups them based on a specified column. For example, we can
use the below statement to get the maximum quantity in all rows from the ProductQty table for each
product group.

1. SELECT Product, MAX(Quantity) AS "Maximum Quantity"


2. FROM ProductQty
3. GROUP BY Product
4. ORDER BY Product;

Executing the statement will display the maximum quantity of each product:
Example4: This example uses the HAVING clause with the MAX() function. We always use the
HAVING clause with the GROUP BY clause to filter the grouped records. For example, if we want to
get the maximum quantity of the sold product name greater than 300, the below statement can be
used:

1. SELECT Product, MAX(Quantity) AS "Maximum Quantity"


2. FROM ProductQty
3. GROUP BY Product
4. HAVING MAX(Quantity)>300;

Executing the statement will return the below output:

Example5: This example uses the MAX() function with two columns to get the highest resultant
output:

1. SELECT Product, MAX(Quantity * Price) AS "Highest Value"


2. FROM ProductQty
3. GROUP BY Product;

When we execute the statement, it will return the highest values of (Quantity * Price) for each product
from the ProductQty table:

Example6: This example uses the DISTINCT and OVER() clause with the MAX() function. We use the
DISTINCT clause to get the unique data, and the OVER clause determines which rows from the query
are applied to the function, in what order the function evaluates them, and when the function's
calculations should restart.

1. SELECT DISTINCT Product,


2. MAX(Quantity) OVER (PARTITION BY Product) AS "Highest Quantity"
3. FROM ProductQty;

This statement returns the below output:

Example7: This example uses the MAX() function with the character data. Suppose we have
considered the system database and want to get the database name that sorts the last name
alphabetically. We can write the statement as below:

1. SELECT MAX(name) AS DBNAME FROM sys.databases WHERE database_id<5;

Here is the result:

SQL Server SUM() Function


The SUM() function in SQL Server is a type of aggregate function. We use this function to calculate
the total summed value in a set of values of a specified column or expression.

It is a built-in function, which accepts a single parameter that can be a column or valid expression and
returns a single result to summarize the input data set. This function ignores the NULL values.
However, it returns NULL when the result set does not have any rows. It can also work with the
WHERE, GROUP BY, ORDER BY, and HAVING clauses to get the filtered result.

Syntax
The syntax of a SUM() function in SQL Server are given below:

1. SELECT SUM( DISTINCT aggregate_expression)


2. FROM table_name(s)
3. [WHERE conditions];

This function contains the following parameters:

00:00/05:29

aggregate_expression: It is the required expression that represents the column name we are going
to calculate the sum.

table_name(s): It indicates the name of a table from where we want to retrieve columns. There can be
specified more than one table.

WHERE conditions: It is an optional clause to define a condition that should satisfy the records to be
selected.

DISTINCT: It tells the function to sum up only distinct values.

SUM() Function Example


Let us understand how the SUM() function works in SQL Server with the help of various examples. We
are going to take the 'employee_info' table to demonstrate the SUM function practically. This table
contains the following data:

Basic Example of SUM Function


This example explains the very basic use of a SUM function that returns the sum of all values in the
specified column. Suppose we want to calculate the total number of salaries from the given table. We
can write the query as below:

1. SELECT SUM(salary) AS "Total Salary" FROM employee_info;

Executing the query will return the below output:


SUM Function with DISTINCT Clause
The DISTINCT keyword calculates only the unique data of the table. Suppose we want to calculate
the sum of unique records present in the salary column of an employee_info table. We can write
the query to do the same as below:

1. SELECT SUM( DISTINCT salary) AS "Total Salary"


2. FROM employee_info;

Executing the query will return the following output that shows the sum of only unique values of the
salary column:

SUM Function with WHERE Clause


The WHERE clause is used to filter the records of a table. This example will use the WHERE clause with
the SUM() function to calculate the total salary of employees whose working hour is greater than
9.

1. SELECT SUM(salary) AS "Total Salary"


2. FROM employee_info
3. WHERE working_hours>9;

When we execute the query, it returns the following result:


SUM Function with GROUP BY Clause
The GROUP BY clause is used to groups rows that have the same values into summary rows. It is very
useful in the aggregate function to produce summary reports. We will get an error if we try to
combine aggregate and non-aggregated columns in a SELECT statement as below:

1. SELECT occupation, SUM(salary) AS "Total Salary"


2. FROM employee_info;

Here is the error message:

However, if we use the GROUP BY clause, it does not throw an error. The below query will use the
SUM() function to calculate the sum of employee's salary based on each occupation:

1. SELECT occupation, SUM(salary) AS "Total Salary"


2. FROM employee_info
3. GROUP BY occupation;

This query finds the employee associated with each occupation and sums up their total salary:
SUM Function with ORDER BY Clause
The ORDER BY clause is used to organize the table either in ascending or descending order. The
below example will use the SUM() function with the ORDER BY clause, calculate the sum of
employee's salary based on each occupation and then sorts the result set in the ascending order of
total summed salary:

1. SELECT occupation, SUM(salary) AS "Total Salary"


2. FROM employee_info
3. GROUP BY occupation
4. ORDER BY SUM(salary);

Executing the statement will display the below output:

SUM Function with HAVING Clause


The HAVING clause is used with the GROUP BY clause to filter the grouped rows. This example uses
the HAVING clause with the SUM() function, calculate the sum of an employee's salary based on each
occupation and then check whether the aggregated salary is greater than 50000 or not. If this is true,
the corresponding records displayed in the ascending order of total summed salary:

1. SELECT occupation, SUM(salary) AS "Total Salary"


2. FROM employee_info
3. GROUP BY occupation
4. HAVING SUM(salary)>50000
5. ORDER BY SUM(salary);

Executing the statement will return the below output:

SUM Function with OVER()


The OVER() clause determines which rows from the query are applied to the function, in what order
the function evaluates them, and when the function's calculations should restart. The below query
provide a cumulative total sales for each occupation in the employee_info table:

1. SELECT DISTINCT occupation,


2. SUM(salary) OVER (PARTITION BY occupation) AS "Total Salary"
3. FROM employee_info;

Executing the query will return the below result:


SQL Server AVG() Function
The AVG() function in SQL Server is a part of an aggregate function. We use this function to
calculate the average value of an expression. This function ignores the NULL values. However,
when the result set does not have any rows, it returns NULL. The AVG() is a built-in function usually
used with the SELECT statement. This function accepts only one parameter that can be a column or
valid expression and returns a single result to summarize the input data set. It can also work with the
WHERE, GROUP BY, ORDER BY, and HAVING clauses to get the filtered result.

Syntax
The following syntax illustrate the AVG() function in SQL Server:

1. SELECT AVG(ALL | DISTINCT expression)


2. FROM table_name(s)
3. [WHERE conditions];

This function contains the following parameters:

Expression: It is the required expression representing the column name whose non-null values are
used to calculate the average.

table_name(s): It is the name of a table from where we want to retrieve records. There can be
specified more than one table.

WHERE conditions: It is an optional clause to define a condition that must be satisfied for selecting
the records.

ALL|DISTINCT: ALL is used by default that instructs the function to operate on all values for
calculation. In comparison, the DISTINCT tells the function to take only unique values.
AVG() Function Example
Let us understand how the AVG() function works in SQL Server with the help of various examples. We
are going to take the 'employee_info' table to demonstrate the AVERAGE function practically that
contains the following data:

Basic Example of AVERAGE Function


This example explains the basic use of an AVERAGE function in SQL Server. It returns the average
value of an expression, including null, non-null, and duplicates. Suppose we want to calculate the
average working hours of all employees listed in the table. We can write the query as below:

1. SELECT AVG(working_hours) AS "Average Working Hours"


2. FROM employee_info;

Executing the query will return the below output that shows the average working hours of employees:

AVERAGE Function with WHERE Clause


SQL Server uses the WHERE clause to filter the records of a table. This example will use the WHERE
clause with the AVG() function to get the average working hours of employees whose occupation
is a writer.

1. SELECT AVG(working_hours) AS "Average Working Hours"


2. FROM employee_info
3. WHERE occupation = 'Writer';

When we execute the query, we see that the average working hours of the writer is 11 hours:

AVERAGE Function with GROUP BY Clause


SQL Server uses the GROUP BY clause to group rows having the same values into summary rows. We
use this clause because it produces the summary reports to make further strategies. The below query
will use the AVG() function to return the total working hours of employees in each
occupation listed in the table:

1. SELECT occupation, AVG(working_hours) AS "Average Working Hours"


2. FROM employee_info
3. GROUP BY occupation;

Executing the query will return the average working hours of employees associated with each
occupation:

If we try to combine aggregate and non-aggregated columns in a SELECT statement, we will get an
error. Here is the error message:
AVERAGE Function with ORDER BY Clause
SQL Server uses the ORDER BY clause to sort the table either in ascending or descending order. The
below example will use the AVG() function with the ORDER BY clause, calculate the average working
hours of employees associated with each occupation and then sorts the result set in the descending
order of the aggregated average value:

1. SELECT occupation, AVG(working_hours) AS "Average Working Hours"


2. FROM employee_info
3. GROUP BY occupation
4. ORDER BY AVG(working_hours) DESC;

Executing the statement will display the result in the descending order based on the
aggregated average value:

AVERAGE Function with HAVING Clause


SQL Server uses the HAVING clause to filter the grouped rows, and this clause always needs the
GROUP BY clause to produce the output. The below example will use the HAVING clause with the
AVG() function. It calculates the average working hours of employees in each occupation and then
checks whether the aggregated average is greater than ten or not. If this is true, the corresponding
result returns in the ascending order of an aggregated average value:
1. SELECT occupation, AVG(working_hours) AS "Average Working Hours"
2. FROM employee_info
3. GROUP BY occupation
4. HAVING AVG(working_hours)>10
5. ORDER BY AVG(working_hours);

Executing the statement will return the average working hour of employees greater than ten in the
occupation:

AVERAGE Function with DISTINCT Clause


SQL Server uses the DISTINCT keyword to remove the duplicate data from the table. Suppose we
want to calculate the total working hours of unique employees in each occupation listed in the
employee_info table. We can write the query to get these data as below:

1. SELECT occupation, AVG( DISTINCT working_hours) AS "Average Working Hours"


2. FROM employee_info
3. GROUP BY occupation;

Executing the query will return the below result that shows working hours of unique employees in
each occupation in the table:
SQL Server COUNT() Function
The COUNT() function in SQL Server is a part of the aggregate function used for calculating the
total number of rows present in the table. When the result set does not have any rows, it
returns NULL. It is usually used with the SELECT statement, and its return type is INT.

The COUNT() is a built-in function, which accepts a single parameter that can be a column or valid
expression and returns a single result to summarize the input data set. This function does not ignore
the NULL values as it considers them too while calculating the query's result. It can also work with the
WHERE, GROUP BY, ORDER BY, and HAVING clauses to get the filtered result.

Syntax
The syntax of a COUNT() function in SQL Server are given below:

1. SELECT COUNT(expression)
2. FROM table_name(s)
3. [WHERE conditions];

This function contains the following parameters:

58.6M
1.1K
Difference between JDK, JRE, and JVM

Expression: It is the required expression that represents the column name whose non-null values will
be counted.

table_name(s): It indicates the name of a table from where we want to retrieve records. There can be
specified more than one table.

WHERE conditions: It is an optional clause to define a condition that should satisfy the records to be
selected.
SQL Server allows us to use the count function in three forms that are listed below:

1. COUNT(*): It is used with the SELECT statement to get the total number of rows present in a
result set. The result set can contain non-null, null, and duplicates rows.
2. COUNT(ALL expression): This function is used to get the total number of rows present in the
table without containing null rows.
3. COUNT(DISTINCT expression): This function is used to calculate only the unique number of
rows present in the table without containing null values.

COUNT() Function Example


Let us understand how the COUNT() function works in SQL Server with the help of various examples.
We are going to take the 'employee_info' table to demonstrate the COUNT function practically. This
table contains the following data:

Basic Example of COUNT Function


This example explains the very basic use of a COUNT function. It displays the total number of rows
present in the table, including null, non-null, and duplicates. Suppose we want to calculate the total
number of employees listed in the given table. We can write the query as below:

1. SELECT COUNT(*) AS "Total Employee" FROM employee_info;

Executing the query will return the below output:


COUNT Function with DISTINCT Clause
The DISTINCT keyword considered only the unique data of the table. Suppose we want to calculate
the total number of unique employees listed in the employee_info table. We can write the query to do
the same as below:

1. SELECT COUNT(DISTINCT name) AS "Total Employee"


2. FROM employee_info;

Executing the query will return the following output that shows only the number of unique employees
in the table:

It is another example that uses the COUNT(expression) function to calculate the total number of non-
null values in the employee_info table:

1. SELECT COUNT(name) AS "Total Employee"


2. FROM employee_info;

This statement will count all employees as there are no NULL records found:

COUNT Function with WHERE Clause


The WHERE clause is used to filter the records of a table. This example will use the WHERE clause
with the COUNT() function to return the total number of employees whose salary is less than 50000
and working hours greater than 9.

1. SELECT COUNT(name) AS "Total Employee"


2. FROM employee_info
3. WHERE salary<50000 AND working_hours>9;
When we execute the query, we see that seven employee's salary is less than 50000 and working
hours are greater than 9:

COUNT Function with GROUP BY Clause


The GROUP BY clause is used to groups rows that have the same values into summary rows. It is
very useful in the aggregate function to produce summary reports. The below query will use the
COUNT() function to count the total number of employees in each occupation:

1. SELECT occupation, COUNT(name) AS "Total Employee"


2. FROM employee_info
3. GROUP BY occupation;

Executing the query will return the number of employees associated with each occupation:

If we try to combine aggregate and non-aggregated columns in a SELECT statement, we will get an
error. Here is the error message:
COUNT Function with ORDER BY Clause
The ORDER BY clause allows us to display the table either in ascending or descending order. The
below example will use the COUNT() function with the ORDER BY clause, calculate the total number of
employees in each occupation and then sorts the result set based on the number of employees in the
ascending order:

1. SELECT occupation, COUNT(name) AS "Total Employee"


2. FROM employee_info
3. GROUP BY occupation
4. ORDER BY COUNT(name);

Executing the statement will display the result in the ascending order of the number of employees:

COUNT Function with HAVING Clause


The HAVING clause is used to filter the grouped rows. We must use the GROUP BY clause with the
HAVING clause. This example uses the HAVING clause with the COUNT() function. It counts the
number of employees in each occupation and then checks whether the aggregated count is greater
than one or not. If this is true, the corresponding records return in the ascending order of a number of
employees:
1. SELECT occupation, COUNT(name) AS "Total Employee"
2. FROM employee_info
3. GROUP BY occupation
4. HAVING COUNT(name)>1
5. ORDER BY COUNT(name);

Executing the statement will return the number of employees greater than one in each occupation:

COUNT Function with OVER()


The OVER() clause determines which rows from the query are applied to the function, in what order
the function evaluates them, and when the function's calculations should restart. The below query
provide a cumulative total number of employees for each occupation in the employee_info table and
organize the output in ascending order:

1. SELECT DISTINCT occupation,


2. COUNT(name) OVER (PARTITION BY occupation) AS "Total Employee"
3. FROM employee_info
4. ORDER BY "Total Employee";

Executing the query will return the below result:


How COUNT() is different from COUNT_BIG() function?
The COUNT and COUNT_BIG function in SQL Server essentially do the same thing, i.e., count the
number of items present in the table. But sometimes we make a choice between them for the
application. In that case, we might prefer which is best for the application based on the data types.

The COUNT() function returns the result as an INT, whereas COUNT_BIG() function returns the
result as BIGINT data types. Thus, if we have a table with millions of records and we need to get the
count of these records, the COUNT() function will give an error, but the COUNT_BIG() function will
display such a result.

Another major difference between them is while creating an index on the view. COUNT() does not
allow the creation of the clustered index on the view. However, we can create clustered index on view
when we use the COUNT_BIG() function.

SQL Server Comparison Operator


In SQL Server, the comparison operators are used to test for equality and inequality. These operators
are used in the WHERE clause to determine which records to select.

Following is a list of the SQL Server comparison operators:

Inde Comparison Description


x Operator

1) = It specifies equal symbol.

2) <> It specifies not equal symbol.

3) != It specifies not equal symbol.


4) > It specifies greater than symbol.

5) >= It specifies greater than or equal symbol.

6) < It specifies less than symbol.

7) <= It specifies less than or equal symbol.

8) !> It specifies not greater than symbol.

9) !< It specifies not less than symbol.

10) IN ( ) It matches a value in a list.

11) NOT It is used to negate a condition.

12) BETWEEN It is used to specify within a range (inclusive) value.

13) IS NULL It specifies null value.

14) IS NOT NULL It specifies non-null value.

15) LIKE It specifies pattern matching with % and _

16) EXISTS It specifies that the condition is met if subquery returns at least
one row.

Equality Operator
In SQL Server database, Equality Operator "=" is used to test for equality in a query.

Example:

Competitive questions on Structures in HindiKeep Watching

We have a table named "Employees", having the following data:


Use the following query to select the specific data where "name" = "Lily":

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE name = 'Lily';

Output:
Inequality Operator
In SQL Server, inequality operators "<> or !=" are used to test for inequality in a query.

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE name <> 'Lily';

Output:
OR

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE name != 'Lily';

Output:
Greater Than Operator
Greater Than ">" Operator is used to test for an expression that it is "greater than".

Example:

Let's select employees from the table "Employees" where salary > 15000.

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE salary > 15000;

Output:
Greater Than or Equal Operator
Greater Than or Equal ">=" Operator is used to test for an expression that it is "greater than or equal
to".

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE salary >= 15000;

Output:
Less than Operator
Less Than "<" Operator is used to test for an expression that it is "less than" the other one.

Example:

Select all employees from the table "Employees" where salary is < 20000.

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE salary < 20000;

Output:
Less Than or Equal Operator
Less Than or Equal "<=" Operator is used to test for an expression that it is "less than or equal to" the
other one.

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE salary <= 20000;

Output:
SQL Server UNION Operator
In SQL Server, the UNION operator is used to combine the result-set of two or more SELECT
statements.

Syntax:

1. SELECT expression1, expression2, ... expression_n


2. FROM tables
3. [WHERE conditions]
4. UNION
5. SELECT expression1, expression2, ... expression_n
6. FROM tables
7. [WHERE conditions];

Parameter explanation
expression1, expression2, ... expression_n: expressions specify the columns or calculations that you
want to compare between the two SELECT statements.
tables: It specifies the tables that you want to retrieve records from. There must be at least one table
listed in the FROM clause.

152.2K

Facebook announces new tool for users to locate and book COVID jabs

WHERE conditions: It is optional condition. It specifies the conditions that must be met for the
records to be selected.

Image representation:

Note: The covered blue area specifies the union data.

UNION operator with single expression


Example:

1. SELECT name
2. FROM [javatpoint].[dbo].[Employees]
3. UNION
4. SELECT name
5. FROM [javatpoint].[dbo].[Employee2];

Output:
UNION operator with multiple expressions
Example:

Let's use multiple expressions of each table. For example: id, name, salary.

1. SELECT id, name, salary


2. FROM [javatpoint].[dbo].[Employees]
3. WHERE salary >= 15000
4. UNION
5. SELECT id, name, salary
6. FROM [javatpoint].[dbo].[Employee2]

Output:

UNION ALL Operator


The UNION operator selects only distinct values by default. So, the UNION ALL operator is used to
allow duplicate values also.

1. SELECT column_name(s) FROM table1


2. UNION ALL
3. SELECT column_name(s) FROM table2;

Example:

1. SELECT id, name, salary


2. FROM [javatpoint].[dbo].[Employees]
3. WHERE salary >= 15000
4. UNION
5. SELECT id, name, salary
6. FROM [javatpoint].[dbo].[Employee2]

Output:
SQL Server INTERSECT Operator
In SQL Server, the INTERSECT operator is used to fetch the records that are in common between two
SELECT statements or data sets. If a record exists in one query and not in the other, it will be omitted
from the INTERSECT results.

Syntax:

1. SELECT expression1, expression2, ... expression_n


2. FROM tables
3. [WHERE conditions]
4. INTERSECT
5. SELECT expression1, expression2, ... expression_n
6. FROM tables
7. [WHERE conditions];

Parameter explanation
expression1, expression2, ... expression_n: expressions specify the columns or calculations that you
want to compare between the two SELECT statements. There is not necessary to have the same fields
in each of the SELECT statements, but the corresponding columns must be similar data types in both
tables.

tables: It specifies the tables that you want to retrieve records from. There must be at least one table
listed in the FROM clause.

WHERE conditions: It is optional condition. It specifies the conditions that must be met for the
records to be selected.

Image representation:

Note: The overlapped blue field specifies the intersect data.


Mandatory conditions for INTERSECT operation
o The number of expressions in both SELECT statements must be same.
o The corresponding columns in each of the SELECT statements must have similar data types.
o The INTERSECT operator fetch only common records the SELECT statements.

INTERSECT operator with single expression


Example:

1. SELECT name
2. FROM [javatpoint].[dbo].[Employees]
3. INTERSECT
4. SELECT name
5. FROM [javatpoint].[dbo].[Employee2];

Output:

INTERSECT operator with single expressions


1. SELECT id, name, salary
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE salary >= 15000
4. INTERSECT
5. SELECT id, name, salary
6. FROM [javatpoint].[dbo].[Employee2]

Output:

It shows blank because nothing is common between them according to the query.

SQL Server IN ( ) Operators


The SQL Server IN condition is used to avoid multiple OR conditions in a SELECT, INSERT, UPDATE, or
DELETE statement.

Syntax

1. expression IN (value1, value2, .... value_n);

Parameter explanation
expression: It specifies a value to test.
value1, value2,.. value_n: It specifies the values to test against expression.

00:00/05:45

Note: The SQL Server IN condition is also called the SQL Server IN operator.

IN Condition with string values


An SQL Server SELECT statement that uses the IN condition to compare string values:

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE name IN ('Mahesh', 'Lily', 'Rahul');

Output:

Or

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE name = 'Mahesh'
4. OR name = 'Lily'
5. OR name = 'Rahul';

Output:

IN Condition with numeric values


An SQL Server SELECT statement that uses the IN condition to compare numeric values:

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE id IN (14, 13, 9, 11, 10);

Output:
Or

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE id = 14
4. OR id = 13
5. OR id = 9
6. OR id = 11
7. OR id = 10;

Output:
IN Condition using NOT Operators
An SQL Server SELECT statement that uses the IN condition with NOT operator:

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE name NOT IN ('Mahesh', 'Lily', 'Rahul');

Output:
Or

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE name <> 'Mahesh'
4. AND name <> 'Lily'
5. AND name <> 'Rahul';

Output:
SQL Server NOT Condition (Operator)
The SQL Server NOT condition or NOT operator is used to negate a condition in a SELECT, INSERT,
UPDATE, or DELETE statement.

Syntax:

1. NOT condition

Parameter explanation
condition: It specifies the condition that you want to negate.

NOT Operator with IN condition


We have a table "Employees", having the following data:

Competitive questions on Structures in HindiKeep Watching


Example

Retrieve all employees from the table where the following "NOT" condition is satisfied:

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE name NOT IN ('Mahesh', 'Mohan', 'Chitra');

Output:
NOT Operator with IS NULL condition
Retrieve all employees from the table "Employees" which follows the IS NOT NULL condition:

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE name IS NOT NULL;

Output:
NOT Operator with LIKE condition
Retrieve all employees from the table "Employees" which follows the NOT LIKE condition. It will
display only names which don?t start with "M".

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE name NOT LIKE 'M%';

Output:
NOT Operator with BETWEEN condition
Retrieve all employees from the table "Employees", which follows the following condition. It will not
show the employees between the id 8 to 13.

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE id NOT BETWEEN 8 AND 13;

Output:
Or

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE id < 8
4. OR id > 13;

Output:
NOT Operator with EXISTS condition
You can also combine SQL Server NOT condition with the EXISTS condition.

OR condition:

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE NOT EXISTS (SELECT *
4. FROM [javatpoint].[dbo].[Employee2]
5. WHERE Employees.name = Employee2.name
6. OR Employees.salary = Employee2.salary);

Output:
AND Condition:

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE NOT EXISTS (SELECT *
4. FROM [javatpoint].[dbo].[Employee2]
5. WHERE Employees.name = Employee2.name
6. AND Employees.salary = Employee2.salary);

Output:
This SQL Server NOT example would return all records from the Employees table where there are no
records in the Employee2 table for the matching name and salary.

SQL Server BETWEEN Condition (Operator)


The SQL Server BETWEEN operator is used to retrieve values within a specified range in a SELECT,
INSERT, UPDATE, or DELETE statement.

Syntax:

1. expression BETWEEN value1 AND value2;

Parameter Explanation
expression: It specifies a column or a calculation.

value1 and value2: These values specify inclusive range that is used by expression for comparison.
BETWEEN operator with Numeric Value
Retrieve all employees from table "Employees" where id is between 7 and 13.

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE id BETWEEN 7 AND 13;

Output:

Or

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE id >= 7
4. AND id <= 13;

Output:
BETWEEN operator with NOT Operator
Retrieve all employees from table "Employees", where it satisfies the following BETWEEN NOT
condition.

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE id NOT BETWEEN 7 AND 11;

Output:
Or

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE id < 7
4. OR id > 11;

Output:
SQL Server IS NULL Condition (Operator)
The SQL Server IS NULL operator is used to test for a NULL value.

Syntax:

1. expression IS NULL

Parameter explanation
expression: It specifies a value whether it is NULL.

Note:
o If the expression is NULL value then the condition evaluates to TRUE.

o If expression is not a NULL value, the condition evaluates to FALSE.


IS NULL Operator with SELECT Statement
Example:

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE salary IS NULL;

Output:

IS NULL Operator with INSERT Statement


Example:

1. INSERT INTO [javatpoint].[dbo].[Employees]


2. (id, name, salary)
3. SELECT id, name, Department
4. FROM [javatpoint].[dbo].[Employee2]
5. WHERE name IS NULL;

Output:
Note: This displays "0 rows affected" because there is no NULL value in name in the "Employees"
table.

IS NULL Operator with UPDATE Statement


Example:

Update the salary of the employees in "Employees" table and set to 100000 where salary is NULL.

1. UPDATE Employees
2. SET salary = '100000'
3. WHERE salary IS NULL;

Output:
You can verify it by using SELECT query:

IS NULL Operator with DELETE Statement


Delete the employees from the "Employees" table where age is NULL.

Example:

1. DELETE FROM [javatpoint].[dbo].[Employees]


2. WHERE age IS NULL;

Output:

You can verify it by using SELECT query:


You can see that there is no NULL value in age in the above table.

SQL Server IS NOT NULL Condition


(Operator)
SQL Server IS NOT NULL condition is used to test for a NOT NULL value.

Syntax:

1. expression IS NOT NULL

Parameter explanation
expression: It specifies the value to test where it is NOT NULL value.

Note: If the expression is NOT a NULL value, the condition evaluates to TRUE. If it is a NULL value,
the condition evaluates to FALSE.

IS NOT NULL operator with SELECT Statement


Example:

Play Video
x

Retrieve all employees from the table "Employees" where salary is NOT NULL value.

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE salary IS NOT NULL;

Output:

IS NOT NULL operator with INSERT Statement


Example:

1. INSERT INTO [javatpoint].[dbo].[Employees]


2. (id, name, salary)
3. SELECT id, name, salary
4. FROM [javatpoint].[dbo].[Employee2]
5. WHERE name IS NOT NULL;

Output:

IS NOT NULL operator with UPDATE Statement


Update the employees of "Employees" table and set the name "Active" where name is not null.

Example:

1. UPDATE [javatpoint].[dbo].[Employees]
2. SET name = 'Active'
3. WHERE name IS NOT NULL;

Output:
Verify the example:
IS NOT NULL operator with DELETE Statement
Update the employees of "Employees" table where name is not null.

1. DELETE
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE name IS NOT NULL;

Output:

Verify the example:


You can see that all employees are deleted from the table "Employees" where name is NOT NULL.

SQL Server LIKE Condition (Operator)


SQL Server LIKE condition or operator is used to perform pattern matching. It is used with WHERE
clause and SELECT, INSERT, UPDATE and DELETE statement.

Syntax:

1. expression LIKE pattern [ ESCAPE 'escape_character' ]

Parameter Explanation
expression: It is a character expression like a column or field.

pattern: It is a character expression that contains pattern matching.

9K

Class 9th - Equal Chords and their Distances from the Centre

Following is a list of patterns used with LIKE operator:

Wildcar Explanation
d
% It is used to match any string of any length (including zero length).

_ It is used to match on a single character.

[] It is used to match on any character in the [ ] brackets (for example, [abc] would match on a, b, or
c characters)

[^] It is used to match on any character not in the [^] brackets (for example, [^abc] would match on
any character that is not a, b, or c characters)

LIKE Operator using % wildcard (percent sign


wildcard)
Example:

You have a table named "Students", having the following data:


Let's use % wildcard with SQL Server LIKE condition. Here we retrieve all of the students from
"Student" table whose name begins with 'L'.

1. SELECT *
2. FROM [javatpoint].[dbo].[Student]
3. WHERE name LIKE 'L%';

Output:

Or

1. SELECT *
2. FROM [javatpoint].[dbo].[Student]
3. WHERE name LIKE '%L%';
LIKE Operator using [ ] wildcard (square brackets
wildcard)
Let's use [] wildcard with SQL Server LIKE condition.

1. SELECT *
2. FROM [javatpoint].[dbo].[Student]
3. WHERE name LIKE 'Aj[ie]et%';
Note:
It will return all students whose name is 5 characters long, where the first two characters is 'Aj'
and the last two characters is 'et', and the third character is either 'i' or 'e'. So in this case, it would
match on either 'Ajiet' or 'Ajeet'.

Output:
LIKE Condition with NOT Operator
Let's retrieve all of the students from "Student" table whose name is not begin with 'L'.

1. SELECT *
2. FROM [javatpoint].[dbo].[Student]
3. WHERE name NOT LIKE 'A%';

Output:
SQL Server EXISTS Conditions
In SQL Server, EXIST condition is used in combination with a subquery. It returns at least one row after
met the conditions. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Syntax:

1. WHERE EXISTS ( subquery );

Parameter explanation
subquery: The subquery is a SELECT statement. If the subquery returns at least one record in its result
set, the EXISTS clause will evaluate to TRUE and the EXISTS condition will be met. If the subquery does
not return any records, the EXISTS clause will evaluate to FALSE and the EXISTS condition will not be
met.
EXISTS condition with SELECT statement
We have two tables: "Employees" and "Employee2", having the following data:

Skip Ad

Employees:

Employee2:
Example:

Use the EXISTS condition on both tables with OR condition:

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE EXISTS (SELECT *
4. FROM [javatpoint].[dbo].[Employee2]
5. WHERE Employees.salary = Employee2.salary
6. OR Employees.name = Employee2.name);

Output:
Example2:

Use the EXISTS condition on both tables with AND condition:

1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE EXISTS (SELECT *
4. FROM [javatpoint].[dbo].[Employee2]
5. WHERE Employees.salary = Employee2.salary
6. AND Employees.name = Employee2.name);

Output:
There is nothing common in both table on given parameters.

SQL Server DISTINCT Clause


In SQL Server, DISTINCT clause is used to remove duplicates from the table. The DISTICT clause is only
used with SELECT statement.

Syntax:

1. SELECT DISTINCT expressions


2. FROM [database_name].[dbo].[table_name]
3. [WHERE conditions];

Parameter explanation
expressions: It specifies the columns or calculations that you want to retrieve.

database_name & table_name: It specifies the name of the database and name of the table on
which you want to do your operations.

Example:

DISTINCT clause with single expression


You have a table named "Employees", having the following data:

Select distinct salary from Employees where salary is greater than 12000.

1. SELECT DISTINCT salary


2. FROM [javatpoint].[dbo].[Employees]
3. WHERE salary > 15000;

Output:
Here, you can see that there is only 6 distinct salaries within 9 records. Distinct clause shows only
unique records.

DISTINCT clause with multiple expressions


DISTINCT clause can also be used with multiple expressions. It will remove duplicates from more than
one field in your SELECT statement.

1. SELECT DISTINCT name, age, salary


2. FROM [javatpoint].[dbo].[Employees]
3. WHERE id > 7;

Output:
SQL Server GROUP BY Clause
SQL Server GROUP BY clause is used to collect data across multiple records and group the results by
one or more columns. It is used with SELECT statement.

Syntax:

1. SELECT expression1, expression2, ... expression_n,


2. aggregate_function (expression)
3. FROM tables
4. [WHERE conditions]
5. GROUP BY expression1, expression2, ... expression_n;

Parameter explanation
expression1, expression2, ... expression_n: These expressions are not encapsulated within an
aggregate function and must be included in the GROUP BY clause.

aggregate_function: It can be a function such as SUM, COUNT, MIN, MAX, or AVG functions.

Competitive questions on Structures in HindiKeep Watching

tables: The tables that you wish to retrieve records from. There must be at least one table listed in the
FROM clause.

WHERE conditions: It is optional. The conditions that must be met for the records to be selected.

Example:

First create a table "Employee2":

Following is a list of some inserted data in the table.


GROUP By using SUM Function
See this example where we GROUP BY department from the "Employee2" using SUM function:

1. SELECT department, SUM(salary) AS "Total salary"


2. FROM [javatpoint].[dbo].[Employee2]
3. GROUP BY department;

Output:
GROUP By using COUNT Function
See this example where we GROUP BY designation from the "Employee2" using COUNT function:

1. SELECT designation, COUNT(*) AS "Number of employees"


2. FROM [javatpoint].[dbo].[Employee2]
3. GROUP BY designation;

Output:
GROUP By using MIN Function
See this example where we GROUP BY department on the basis of salary from the "Employee2" using
MIN function.

This will retrieve the minimum salary according to department:

1. SELECT department, MIN(salary) AS "Lowest salary"


2. FROM [javatpoint].[dbo].[Employee2]
3. GROUP BY department;

Output:
GROUP By using MAX Function
See this example where we GROUP BY department on the basis of salary from the "Employee2" sing
MAX function.

This will retrieve the maximum salary according to department:

1. SELECT department, MAX(salary) AS "Highest salary"


2. FROM [javatpoint].[dbo].[Employee2]
3. GROUP BY department;

Output:
SQL Server WHERE Clause
The WHERE clause in SQL Server is used to filter records from the table. It is an optional clause that
is used to limit the number of rows returned by the query. We can also say that this clause specifies a
condition to return only those records that fulfill the defined conditions. The WHERE clause can also
work with the UPDATE and DELETE query.

Need of WHERE Clause


When we perform an operation on the table using the SELECT statement, it will return all records from
that table. If our table has many records, the SELECT statement can return unnecessary data because
the application process only the set of rows at a time. In such a case, we need some conditions that
return only those records that we want to see in the output table. Thus, we use the WHERE clause to
restrict the query from fetching unnecessary records from a table and return only those rows that
meet the condition mentioned in the WHERE clause.

Syntax
The following are the syntax that illustrates the WHERE clause in SQL Server:
1. SELECT column_list
2. FROM table_name
3. WHERE search_condition;

This syntax has the following parameters:

00:00/11:48

Column_list: It is the name of the columns that we want to retrieve from the table in the result set.

Table_name: It is the table name from which columns will be selected.

Search_condition: It is a condition that returns only those records that fulfill this condition. It
performs filtration on the table. It also indicates the logical expression or a combination of multiple
logical expressions that evaluates the result: TRUE, FALSE, or UNKNOWN. If it evaluates to FALSE or
UNKNOWN, the WHERE clause will not return any record.

The WHERE clause also supports the following operators to filter the records:

Operator Name Operator Symbol

Equal =

Less Than <

Greater Than >

Less Than or Equal <=

Greater Than or Equal >=

Not Equal <>

Search for a specific pattern LIKE

Find records within given range BETWEEN

Used to specify multiple values IN

Example
Let us understand the working of WHERE clause in SQL Server with several examples. We will table
the employee_info table to demonstrate all examples of the WHERE clause. The employee_info table
has the following data:
Example1: This example will use the simple equality operator to filter rows. The following statement
will retrieve all employees whose working hour is equal to 12 and then sort them based on their
name:

1. SELECT name, occupation, working_hours, salary


2. FROM employee_info
3. WHERE working_hours = 12
4. ORDER BY name;

Executing the statement will return only those employees whose working hour is equal to 12:

Example2: This example retrieves those rows that meet two conditions in the WHERE clause. The
following example returns the employee information whose working hour is greater than 10 and
salary is less than 50000. Here we use the logical operator AND to combine the two conditions in
the WHERE clause.

1. SELECT name, occupation, working_hours, salary


2. FROM employee_info
3. WHERE working_hours>10 AND salary<50000
4. ORDER BY name;

Executing the statement will return all those employees whose working hour is greater than 10 and
salary is less than 50000:
Example3: This example retrieves those rows that meet any of the two conditions in the WHERE
clause. The following example returns the employee information whose occupation is writer and
salary is greater than 35000. Here we use the OR operator to combine the conditions in the WHERE
clause.

1. SELECT name, occupation, working_hours, salary


2. FROM employee_info
3. WHERE occupation='Writer' OR salary>35000
4. ORDER BY name;

Executing the statement will return all those employees that meet one of these conditions included in
the query.

Example4: This example will retrieve those rows that belong to the range of two values. The following
statement finds the employee information whose salaries are between 35000 and 60000. Here
we use the BETWEEN operator to get the desired result.

1. SELECT name, occupation, working_hours, salary


2. FROM employee_info
3. WHERE salary BETWEEN 35000 AND 60000
4. ORDER BY name;

Executing the statement will return all those employees whose salary is in the range of 35000 to
60000.
Example5: This example retrieves the records that have a value in a list of values. The following
statement will use the IN operator to find employee information whose occupation is in Writer,
Manager, or HR.

1. SELECT name, occupation, working_hours, salary


2. FROM employee_info
3. WHERE occupation IN ('HR', 'Writer', 'Manager')
4. ORDER BY name;

Executing the query will return all employee information whose occupation is Writer, Manager, or HR:

Example6: This example retrieves the records whose values contain a string. The following statement
will use the LIKE operator to find an employee's information whose occupation contains the 'er'
string.

1. SELECT name, occupation, working_hours, salary


2. FROM employee_info
3. WHERE occupation LIKE '%er%'
4. ORDER BY name;

Executing the query will return all employee information whose occupation contains the 'er' string:
Example7: This example retrieves the records whose values do not satisfy the condition. The
following statement will use the NOT EQUAL operator to find an employee's information whose
occupation does not contain the 'Writer' occupation.

1. SELECT name, occupation, working_hours, salary


2. FROM employee_info
3. WHERE occupation <> 'Writer'
4. ORDER BY name;

Executing the query will return all employee information whose occupation does not have the 'Writer'
occupation:

SQL Server ORDER BY


An ORDER BY clause is used to arrange the table's data in ascending or descending order based
on the given column or list of columns. It is usually used with the SELECT statement as it returns the
records without sorting in specific orders. It means SQL Server produces the output in an unspecified
order. However, using the ORDER BY clause guarantees that the records in the output are sorted in
ascending or descending order. This clause allows sorting of the table by defining single or multiple
columns.

Syntax
The following are the syntax that illustrates the ORDER BY clause in SQL Server:
1. SELECT column_lists
2. FROM table_name
3. WHERE conditions
4. ORDER BY column_name [ASC | DESC];

The above syntax parameter descriptions are given below:

Column_lists: It indicates the name of the columns that we want to retrieve in the result set.

Skip Ad

Table_name: It indicates the name of a table from where we want to retrieve columns. We must
provide at least one table name in the FROM clause.

Conditions: It is an optional parameter that will be used to filter the table records.

column_name [ASC | DESC]: It indicates the name of columns to which table is sorted. The ASC
keyword is optional, but if defined, it sorts the output in ascending order (lowest to highest). The
DESC keyword is optional, but if defined, it sorts the output in descending order (highest to lowest).

If we do not define ASC or DESC keyword, SQL Server will use ASC as the default sorting
order. SQL Server considers the NULL value to be the lowest. In addition, the ORDER BY clause is the
very last clause to be considered when processing a SELECT statement with an ORDER BY clause.

Example of ORDER BY clause


Let us understand how the ORDER BY clause works in the SQL Server by taking several examples
practically. Here we are going to take a table employee_info for demonstration of this clause. The
table employee_info contains the following records:

Example1: The following statement explains the ORDER BY clause without specifying any sorting
order. Here we will specify the 'salary' column to sort the table.

1. SELECT name, occupation, salary


2. FROM employee_info
3. ORDER BY salary;

Executing the statement will return the below output where we see that table is sorted based on the
salary column. Since we have not specified the sorting order, SQL Server will sort the table in the
default order:

Example2: This example will sort the result set based on the single column in descending order. The
below statement sorts the employee_info table in descending order by using the employee name
column:

1. SELECT name, occupation, salary


2. FROM employee_info
3. ORDER BY name DESC;

Executing the statement will display the below output. Since we specified the DESC keyword explicitly,
the SQL Server sorted the result set based on the name values in descending order.

Example3: This example will sort the result set based on the multiple columns. The following
statement will return the name, occupation, and salary of the employees. It first sorts the employee
list by the salary column and then by the name column.
1. SELECT name, occupation, salary
2. FROM employee_info
3. ORDER BY salary, name;

Executing the statement will produce the following result set:

Example4: This example will sort a result set based on the multiple columns and different orders. The
following statement will return the name, occupation, and salary of the employees. It first sorts the
employee list by the salary column in descending order and then sorts the sorted result set by the
name in ascending order.

1. SELECT name, occupation, salary


2. FROM employee_info
3. ORDER BY
4. salary DESC,
5. name ASC;

Executing the statement will produce the following result set:


Example5: This example will sort a result based on the column that is not defined in the SELECT list.
Because, in some cases, the column name used for sorting the result does not appear on the select
list. The following statement sorts the employee based on the working hour even though
the working_hours column is not listed on the select list.

1. SELECT name, occupation, salary


2. FROM employee_info
3. ORDER BY working_hours;

It should be noted that the working hour column is defined in the employee_info table. Otherwise, we
would have an invalid query. Now, execute the query to display the result:

Example6: This example will sort a result set based on the defined expression. The following example
uses the LEN() function that returns the number of characters of a string. Here, we use this function
in the ORDER BY clause to retrieve an employee's information sorted by the length of their name.

1. SELECT name, occupation, salary


2. FROM employee_info
3. ORDER BY LEN(name) DESC;

This query will produce the below output:


Example7: This example will sort the table based on the ordinal positions of columns. We do this
as SQL Server allows us to sort the result by column's ordinal positions in the SELECT list.

The given query sorts the employee_info table name by specifying


the name and occupation column's ordinal position instead of specifying the column names
explicitly:

1. SELECT name, occupation, salary


2. FROM employee_info
3. ORDER BY 1, 2;

Executing the statement will display the below result set:

In the statement, the name column is represented by 1, and the occupation column is represented by
2. This statement was executed successfully, but DBA considered the bad programming practice to
use the ordinal positions of the columns in the ORDER BY clause. Some of the popular reasons are
given below:

o A table's columns do not have ordinal positions and must be referred to by their names.
o When we edit the select list, it's possible to forget to update the corresponding changes in the
ORDER BY clause.

Therefore, it is recommended to always specify the column names directly in the ORDER BY clause to
remove future difficulties.

OFFSET and FETCH options in the ORDER BY Clause


OFFSET option is used in the ORDER BY clause to eliminate the number of records from the starting
record (TOP). It means that OFFSET specifies the beginning point for returning rows from a result set.

The FETCH option in the ORDER BY clause is used to specify the number of rows return after the
OFFSET clause is processed in a query.

Example

Suppose we want to get the employee records starting from 3 up to the next four rows. It can be
retrieved easily by using the OFFSET and FETCH clauses. Here is the query:

1. SELECT name, occupation, salary


2. FROM employee_info
3. ORDER BY name
4. OFFSET 3 ROWS
5. FETCH NEXT 4 ROWS ONLY;

Executing the statement will return the following output where OFFSET 3 skips the three rows and
FETCH 4 ROWS ONLY displays the required result.

SQL Server HAVING


The HAVING clause in SQL Server is used to specify the search condition for a group or an
aggregate. It can only work with the SELECT statement and is usually used with the GROUP BY
clause. It enables us to filter which group results appear in the results. We used this clause instead of
the WHERE clause because it places a condition on groups created by the GROUP BY clause, while the
WHERE clause places a condition on the selected columns.
Each HAVING condition in SQL can compare one group column or aggregate expression to another
group aggregate expression or a constant. We may use HAVING to place conditions on both column
and aggregate values in the group list.

Benefits of Having Clause


The HAVING clause validates groups in the same way as the WHERE clause validates individual rows.
The main benefit of using a HAVING clause is that aggregates can be included in the search condition,
whereas aggregates cannot be used in a WHERE clause's search condition.

Syntax
The following are the basic syntax of the HAVING clause in SQL Server:

Play Video
x
1. SELECT column_list,
2. aggregate_function (expression)
3. FROM table_name
4. GROUP BY group_list
5. HAVING search_conditions;

The parameter descriptions of the above syntax are explained below:

o First, we will select the column names that we want in the result. Here, we can also specify the
aggregate function such as SUM, COUNT, MIN, MAX, or AVG.
o Second, we will write the table name from which column will be selected.
o Third, we use the GROUP BY clause to summarize the rows into groups.
o Fourth, we use the HAVING clause with single or multiple conditions to the groups evaluated
by the GROUP BY clause. The final result included only those groups that make the evaluation
of the condition TRUE. If the condition is found FALSE or UNKNOWN, the groups are filtered
out.

HAVING Clause Example


Let us understand the HAVING clause with examples that helps us to use it with the different SQL
aggregate functions. Suppose we have a table named employees_info that contains the following
data:
We will use this table to demonstrate the HAVING clause with different examples.

Example1: The below query will use the SUM function with the HAVING clause. It returns the
employee name and SUM of their working hours whose working hours are more than 6 hours:

1. SELECT name, SUM(working_hours) AS "Total working hours"


2. FROM employee_info
3. GROUP BY name
4. HAVING SUM(working_hours) > 6;

Executing the query will return the below output:

Example2: The below query will use the COUNT function with the HAVING clause. This statement
counts the working hour of those employees whose salary is greater than 30000:

1. SELECT name, COUNT(working_hours) AS total_employee


2. FROM employee_info WHERE salary>30000
3. GROUP BY name
4. HAVING COUNT(working_hours)>= 1;

Executing the statement will return the below output:


Example3: The below query will use the MIN function with the HAVING clause. It returns the
minimum working hour of each employee whose minimum working hour is greater than 10.

1. SELECT name, MIN(working_hours) AS total_working_hours


2. FROM employee_info
3. GROUP BY name
4. HAVING MIN(working_hours)>= 10;

Executing the statement will return the below output where we see the employee name along with
their minimum working hours:

Example4: The below query will use the MAX function with the HAVING clause. It returns the
maximum working hour of each employee whose maximum working hour is less than 12.

1. SELECT name, MAX(working_hours) AS total_working_hours


2. FROM employee_info
3. GROUP BY name
4. HAVING MAX(working_hours) <= 12;

Executing the statement will return the below output where we see the employee name along with
their maximum working hours less than 12:

Example5: The below query will use the AVERAGE function with the HAVING clause. It returns the
occupation name whose average salary is more than and equals 30000.

1. SELECT AVG(salary) AS average_salary, occupation


2. FROM employee_info
3. GROUP BY occupation
4. HAVING AVG(salary) >= 30000;

Executing the statement will return the below output:


SQL Server SELECT
The SELECT statement in SQL Server is used to display all or specific records from the table. This
statement allows us to fetch the records based on our needs or retrieve all records of the table.

Need of SELECT statement


The database can contain one or more tables, and each table stores our data in sequential order. The
data in the table is organized in the form of rows and columns, similar to a spreadsheet. Each row
represents the unique records, and the column represents the field in the table. SQL Server used
schema to arrange the tables logically.

When we extract or fetch the required data from the table, we use queries written in SQL languages.
The most basic statement used for such an operation is the SELECT statement.

Syntax
The following statement illustrates the most basic use of SELECT statement to fetch records from the
table:

x
1. SELECT column1, column2,... columnN
2. FROM table1, table2....
3. [WHERE condition]
4. [GROUP BY column]
5. [HAVING condition]
6. [ORDER BY column];

If we want to fetch all columns from the table, we use the below statement:

1. SELECT * FROM tables;

In this syntax, we have seen the following parameters:

Column or *: It indicates the field name of the table we want to fetch in the result set. We use the
asterisk (*) when all columns need to be fetched.
Table: It indicates the name of the table from which we want to retrieve data. We can list more than
one table.

WHERE: It's an optional clause to filter the records based on the given condition.

GROUP BY: It's an optional clause used to group the records based on single or multiple columns.

HAVING: It is an optional clause used with the GROUP BY clause to return only those rows whose
condition is TRUE.

ORDER BY: It's an optional clause used to arrange the table records in ascending or descending
order.

Points to remember

o SQL Server will evaluate the FROM clause first, and then the SELECT clause will be evaluated.
o The SELECT * is not recommended to use in real-time databases as it fetches the data more
than our requirements.
o The SELECT * query keeps the application performance slow.
o When a user adds new columns to a table, the SELECT * query fetches all of the columns,
including the new ones, causing the application to crash.

SELECT Statement Example


Let us understand how SELECT query works in SQL Server with the help of several examples. Suppose
we have a table named "employee_info" that contains the following data:

Example1: Suppose we want to fetch only one column (name) in a sorted manner from the table. We
can get this data using the below statement:

1. SELECT name
2. FROM employee_info
3. ORDER BY name;

Executing the statement will get the following output that has only one column:

Example2: Suppose we want to fetch multiple columns in the sorted manner of their employee name
from the table. We can get this data using the below statement:

1. SELECT name, occupation, salary


2. FROM employee_info
3. ORDER BY name;

Executing the statement will get the following output where we can see the name, occupation, and
salary of employees:

Example3: Suppose we want to retrieve all columns data of the table. In this case, either we need to
write all column's names with the select statement or use an asterisk (*) symbol in place of column
names. Specifying all column names is not convenient for the user, so we usually use an asterisk (*) to
retrieve all column data and save some typing. It is also useful to examine the columns and data of a
table from which we are unfamiliar. Here is the query:

1. SELECT * FROM employee_info


2. ORDER BY name;

Executing the query will show the following output where we can see all columns of the table:

Example4: This example will explain the SELECT statement with the WHERE clause. The WHERE clause
is used to filter data based on one or more columns. The following query will return all employees
information whose working hour is greater than 10:

1. SELECT * FROM employee_info


2. WHERE working_hours > 10
3. ORDER BY name;

Executing the statement shows the below output:

Example5: This example explains the SELECT statement with the GROUP BY clause, which is used to
group the rows into groups based on single or multiple columns. The following statement shows
occupation and number of employees in each occupation and then sort them in ascending order:

1. SELECT occupation, COUNT(*) AS Total_employee


2. FROM employee_info
3. GROUP BY occupation
4. ORDER BY occupation;

Executing the statement will display the expected result:


Example6: This example explains the SELECT statement with the HAVING clause. We use
the HAVING clause to filter groups by using single or multiple columns. It is noted that the WHERE
clause filters the records while the HAVING clause filter the groups. The following statement shows
occupation and number of employees in each occupation which has more than one employee and
then sort them in ascending order:

1. SELECT occupation, COUNT(*) AS Total_employee


2. FROM employee_info
3. GROUP BY occupation
4. HAVING COUNT(*)>1
5. ORDER BY occupation;

Executing the statement will display the expected result:

Example7: This example explains the SELECT statement with the TOP clause. The TOP clause shows
the limited number of records from the table. It is noted that we must specify how many rows are
returned in the TOP clause.

Suppose we want to get the first three records of the table. To fetch this detail, we use the query as
below:

1. SELECT TOP(3) * FROM employee_info;

Executing this query will return only the first three records as shown below:
Example8: This example explains the SELECT statement with the JOIN clause. We use the JOIN clause
to fetch the data from more than two tables.

We will take the two tables named "Student" and "Fee" to demonstrate this example. The following
image shows the data of both tables:

Suppose we want to get the student information who have paid their course fees. In this case, we use
the common column "admission_no" as a join condition to get data from both tables. Let us execute
the below statement to fetch the required data from both tables:

1. SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_paid


2. FROM Student
3. INNER JOIN Fee
4. ON Student.admission_no = Fee.admission_no;

Executing the command will display the expected result:

SQL Server GROUPING SETS


GROUPING SET is an extension of the GROUP BY clause. The GROUP BY statement is GROUPING
SET is an extension of the GROUP BY clause. The GROUP BY statement is used to summarize the data
in conjunction with aggregate functions such as SUM, AVG, COUNT, etc. It groups the result set based
on the single or multiple columns. The GROUPING SET was first introduced with the SQL Server 2008
version.

The following scenario explains the concept of GROPING SET in SQL Server:

SQL Server allows us to create a group by combining the department and city of an employee
table to retrieve the total number of employees who are working in a particular department in a
city. Suppose we want to get all employee who works in the IT department in Bangalore
city. Also, we can further add employee type (writer) to department and city to retrieve all writers
working in the IT department in Bangalore city. These are the two different groups so that it cannot
be performed in a single query using the GROUP BY clause. We need to write two different
statements for these groups where the first is the (department, city) and the second is
the (department, city, employee type).

In such a case, we use the GROUPING SET that makes it simple. It enhances the GROUP BY clause's
functionality by specifying many groups in a single query. It allows the creation of many groups and
analyze and compare their properties using a GROUPING SET in a single query as it is a collection of
multiple GROUPS.

Syntax
The following are the syntax that illustrates the GROUPING SET in SQL Server:

1. SELECT column_list, aggregate(column_name)


2. FROM table_name
3. GROUP BY
4. GROUPING SETS (
5. (column1, column2),
6. (column1),
7. (column2),
8. ()
9. );

This syntax parameter is explained below:

o Column_list: It indicates the column's name that we want to retrieve in a result set from the
table.
o aggregate(column_name): It indicates the column on which aggregate function (i.e. SUM,
COUNT, AVG etc.) is applied
o GROUP BY: It is used to specify a column or list of columns as a single group.
o GROUPING SET: It indicates the set of columns that have to be grouped together.
o (): It is optional that specifies an empty grouping set and aggregates columns individually.

GROUPING SETS Equivalents


GROUPING SETS is equivalent to a UNION ALL operator. SQL Server produces the same information
using the UNION ALL query, each having the GROUP BY list and GROUPING SETS defined as the
GROUP BY list. GROUPING SETS can also be used in place of ROLLUP and CUBE.

The below table explains GROUPING SETS equivalent UNION ALL, ROLLUP, and CUBE more
clearly:

GROUPING SETS equivalent to UNION ALL

SELECT column1, column2, SUM(colmn3) SELECT column1 NULL AS column2, SUM(column3)


FROM table1 GROUP BY FROM table1 GROUP BY column1
GROUPING SETS ((column1), (column2)); UNION ALL
SELECT NULL AS column1, column2, SUM(column3)
FROM table1 GROUP BY column2;

GROUPING SETS equivalent to ROLLUP

GROUP BY ROLLUP (column1, column2, GROUP BY GROUPING SETS ((column1, column2,


column3) column3),
(column1, column2),
(column1),
());

GROUPING SETS equivalent to CUBE

GROUP BY CUBE (column1, column2, GROUP BY GROUPING SETS ( (column1, column2,


column3) column3),
(column1, column2),
(column1, column3),
(column2, column3),
(column1),
(column2),
(column3),
());

GROUPING SETS Example


Let us look at how GROUPING SETS works in SQL Server with examples. We will demonstrate this by
first creating a sample table named ProductQty that contains the details of the purchased product
and then insert some records in the table.

Execute the below statement to create a ProductQty table:

1. CREATE TABLE ProductQty(


2. Id INT IDENTITY(1,1),
3. Region VARCHAR(100),
4. Product VARCHAR(50),
5. Year INT,
6. Quantity INT
7. )

Next, execute the below statement to insert records into this table:

1. INSERT INTO ProductQty(Region, Product, Year, Quantity)


2. VALUES('East', 'Computer', 2020, 13000),
3. ('South', 'Computer', 2020, 45000),
4. ('North', 'Computer', 2020, 25000),
5. ('East', 'Hard Disk', 2020, 1900),
6. ('West', 'Computer', 2021, 25000),
7. ('South', 'Hard Disk', 2021, 5500),
8. ('West', 'Hard Disk', 2021, 6500),
9. ('East', 'Pen Drive', 2021, 1200),
10. ('North', 'Mouse', 2019, 1600),
11. ('South', 'Pen Drive', 2019, 2700),
12. ('East', 'Mouse', 2019, 2000),
13. ('West', 'Pen Drive', 2019, 1900);

Now, we can verify the data by executing the SELECT statement:


Here we will start with the GROUP BY clause instead of starting with the GROUPING SET so that we
can gradually extend the logic and clearly understand the significance and usage of the GROUPING
SET.

1) Query to determine the total purchased quantity by region

This statement creates a GROUP using the 'Region' column to get the quantity of the total purchases.
Here we use the aggregate function SUM on the 'Quantity' column for the summation of the total
purchases.

1. SELECT Region, SUM(Quantity) AS TotalPurchase


2. FROM ProductQty
3. GROUP BY Region;

Executing the query will display the total purchase quantity:

2) Query to determine the total purchased quantity in each year

This statement creates a GROUP using the 'Year' column to get the quantity of the total purchases in
each year. Here we also used the SUM function for the summation of the total purchases.
1. SELECT Year, SUM(Quantity) AS TotalPurchase
2. FROM ProductQty
3. GROUP BY Year;

Executing the query will display the total purchase quantity:

3) Query to determine the total purchase quantity available in each region and year

This statement creates a GROUP using the 'Region' and 'Year' columns and returns the total number
of purchases in each region and year.

1. SELECT Region, Year, SUM(Quantity) AS TotalPurchase


2. FROM ProductQty
3. GROUP BY Region, Year;

Executing the query will display the total purchase quantity:


4) If we want to display the overall purchase quantity, we use the empty group set query:

1. SELECT SUM(Quantity) AS TotalPurchase


2. FROM ProductQty;

Executing the query will display the total purchase quantity:

As we can see, the above four queries return four result set using different grouping sets. Here we
have an issue to execute a fresh query each time to create a new group or category for analyzing the
data from a different point of view. SQL Server has another way also to get the same result by
combining all the query result sets into a single query using the UNION ALL operator[.

The following UNION ALL statement yields the same result. Because the UNION ALL operator
demands that all participating queries' result sets have the same number of columns, we must add a
dummy column NULL to the select list to ensure that all statements have the same number of
columns.
1. SELECT Region, NULL AS Product, SUM(Quantity) AS TotalQty
2. FROM ProductQty
3. GROUP BY Region
4. UNION ALL
5. SELECT NULL AS Region, Product, SUM(Quantity) AS TotalQty
6. FROM ProductQty
7. GROUP BY Product
8. UNION ALL
9. SELECT Region, Product, SUM(Quantity) AS TotalQty
10. FROM ProductQty
11. GROUP BY Region, Product
12. UNION ALL
13. SELECT NULL AS Region, NULL AS Product, SUM(Quantity) AS TotalQty
14. FROM ProductQty

Executing the statement will display the below output where we see that the UNION ALL generate a
single result with the aggregates for all grouping sets as expected. This result set is also an integrated
output of all the above four queries.

However, this approach returns the result within a single query, but it is ad-hoc, cumbersome, and
inefficient. The database server has a lot of pressure to execute this approach that can cause slowness
of query and performance issues as it must conduct four different queries. Here database server first
combines the result sets of the first two queries, then combine those result sets with the third query
and then with the fourth query. This approach needs several table reads, temporary storage, and
many IOs.

SQL Server 2008 introduced the GROUPING SET capability to overcome these shortcomings,
allowing us to define many GROUPS within a single query. We can achieve the same goal by including
all GROUPS in the GROUPING SET clause, resulting in an output that includes all groups and their
essential details. Here is the query that defines each grouping set within a single statement:

1. SELECT Region, Year, SUM(Quantity) AS TotalPurchaseQty


2. FROM ProductQty
3. GROUP BY GROUPING SETS
4. ((Region),
5. (Year),
6. (Region, Year),
7. ())
8. ORDER BY Region, Year;

Executing the statement will produce the following output:

In this output, we can see that this query gives the same result and is also very simple and efficient
compared to using the UNION ALL query. Here we can see that it has one row (first row), which is not
a group; it is just an aggregate of the total quantity.

GROUPING Function
SQL Server also enables us to check whether the specified column in the GROUP BY clause is
aggregated or not by using the GROUPING FUNCTION in the above query. This function returns two
values, 0 & 1, where 1 represents the aggregated result set, and 0 represents not aggregated.

The following query explains the use of the grouping function:

1. SELECT GROUPING(Region) AS Is_RegionGrouped, GROUPING(Year) AS Is_YearGrouped,


2. Region, Year, SUM(Quantity) AS TotalPurchaseQty
3. FROM ProductQty
4. GROUP BY GROUPING SETS ((Region), (Year), (Region, Year), ( ))
5. ORDER BY Region, Year;

Executing the statement will display the below output:

In this output, the column Is_RegionGrouped indicates 1 when the product quantity is aggregated by
region, 0 means that the product quantity is not aggregated by region. The same concept is applied
to the Is_YearGrouped column.

SQL Server Primary Key


SQL Server Primary key is a single field or combination of fields that is used to uniquely define a
record. Any field of a primary key cannot contain a null value. A table can have only one primary key.

You can define a primary key either in a CREATE TABLE statement or an ALTER TABLE statement.
Create Primary Key Using CREATE TABLE
Statement
Syntax:

1. CREATE TABLE table_name


2. (
3. column1 datatype [ NULL | NOT NULL ] [ PRIMARY KEY ],
4. column2 datatype [ NULL | NOT NULL ],
5. ...
6. );

Or

1. CREATE TABLE table_name


2. (
3. column1 datatype [ NULL | NOT NULL ],
4. column2 datatype [ NULL | NOT NULL ],
5. ...
6. CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n)
7. );

Example:

Create a table "cricketers" where "cricketer_id" is a primary key.

1. CREATE TABLE cricketers


2. ( cricketer_id INT PRIMARY KEY,
3. last_name VARCHAR(50) NOT NULL,
4. first_name VARCHAR(50) NOT NULL,
5. salary MONEY
6. );

Output:
You can verify that created table by using SELECT command:

1. SELECT *
2. FROM [javatpoint].[dbo].[cricketers]

Output:
Here cricketer_id is the primary key.

You can also create a table with primary key by using the second syntax:

Example:

1. CREATE TABLE cricketers2


2. ( cricketer_id INT,
3. last_name VARCHAR(50) NOT NULL,
4. first_name VARCHAR(50) NOT NULL,
5. salary MONEY,
6. CONSTRAINT cricketers2_pk PRIMARY KEY (cricketer_id)
7. );

Output:
You can verify that created table by using SELECT command:

1. SELECT *
2. FROM [javatpoint].[dbo].[cricketers2]

Output:
Create a primary key in SQL Server where the
primary key is more than one field:
Example:

1. CREATE TABLE cricketers3


2. ( last_name VARCHAR(50) NOT NULL,
3. first_name VARCHAR(50) NOT NULL,
4. salary MONEY,
5. CONSTRAINT cricketers3_pk PRIMARY KEY (last_name, first_name)
6. );

Output:

You can verify that created table by using SELECT command:

1. SELECT *
2. FROM [javatpoint].[dbo].[cricketers3]

Output:
Here, last_name and first_name both is primary key.

Create Primary Key Using ALTER TABLE statement


You can use an ALTER TABLE statement to create a primary key only on the column or columns that
are already defined as NOT NULL.

If a column of a table has NULL values, you cannot add a primary key without dropping and
recreating the table.

Syntax:

1. ALTER TABLE table_name


2. ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n);

Example:

Create a primary key "cricketer_id" in the table "cricketers2".

1. ALTER TABLE [javatpoint].[dbo].[cricketers2]


2. ADD CONSTRAINT cricketers2_pk PRIMARY KEY (cricketer_id);

Output:
It will create a primary key "cricketer_id" in the "cricketers2" table.

Enable Primary Key


ALTER INDEX statement is used to enable a primary key in SQL Server database.

Syntax:

1. ALTER INDEX constraint_name ON table_name


2. REBUILD;

Example:

Enable the primary key "customer_id" on the table "customers".

x
1. ALTER INDEX cricketers2_pk ON [javatpoint].[dbo].[cricketers2]
2. REBUILD;

Output:
Now primary key "customer_id" is enabled in table "customers".

Disable Primary key


ALTER INDEX statement is used to disable a primary key in SQL Server database.

Syntax:

1. ALTER INDEX constraint_name ON table_name


2. DISABLE;

Example:

Disable the primary key "customer_id" on the table "customers".

Play Video
x
1. ALTER INDEX cricketers2_pk ON [javatpoint].[dbo].[cricketers2]
2. DISABLE;

Output:
Drop Primary Key
ALTER TABLE statement is used to drop a primary key in SQL Server.

Syntax:

1. ALTER TABLE table_name


2. DROP CONSTRAINT constraint_name;

Example:

Let's drop a primary key using the ALTER TABLE statement in SQL Server. Here we take "cricketers2"
table which has "cricketer_id" as a primary key and "cricketers2_pk" as constraint name.

x
1. ALTER TABLE [javatpoint].[dbo].[cricketers2]
2. DROP CONSTRAINT cricketers2_pk ;

Output:
SQL Server Foreign Key
In SQL Server, foreign key is used to enforce referential integrity within your SQL Server database. It
specifies that a value in one table must also appear in another table.

The referenced table is called parent table while the table having foreign key is called child table. The
foreign key in the child table will generally reference a primary key in the parent table.

A foreign key can be created using either a CREATE TABLE statement or an ALTER TABLE statement.

Create a Foreign Key using CREATE TABLE


statement
Syntax:

00:00/11:06
22.6M
314
Triggers in SQL (Hindi)

1. CREATE TABLE child_table


2. (
3. column1 datatype [ NULL | NOT NULL ],
4. column2 datatype [ NULL | NOT NULL ],
5. ...
6. CONSTRAINT fk_name
7. FOREIGN KEY (child_col1, child_col2, ... child_col_n)
8. REFERENCES parent_table (parent_col1, parent_col2, ... parent_col_n)
9. [ON DELETE {NO ACTION | CASCADE | SET NULL | SET DEFAULT} ]
10. [ON UPDATE {NO ACTION | CASCADE | SET NULL | SET DEFAULT} ]
11. );

Parameter Explanation
child_table: It specifies the name of the child table that you want to create.

column1, column2: It specifies the columns that you want to create in the table. Each column must
have a datatype. The column should either be defined as NULL or NOT NULL and if this value is left
blank, the database assumes NULL as the default.

fk_name: It specifies the name of the foreign key constraint that you want to create.

child_col1, child_col2, ... child_col_n: It specifies columns in child_table that will reference a primary
key in the parent_table.

parent_table: It specifies the name of the parent table whose primary key will be used in the
child_table.

parent_col1, parent_col2, ... parent_col3: It specifies columns that make up the primary key in the
parent_table. The foreign key will enforce a link between this data and the child_col1, child_col2, ...
child_col_n columns in the child_table.

Example:

Let's create two table "products" and "inventory" where primary key of products table is "product_id"
which is foreign key in "inventory" table.

1. CREATE TABLE products


2. ( product_id INT PRIMARY KEY,
3. product_name VARCHAR(50) NOT NULL,
4. category VARCHAR(25)
5. );
6. CREATE TABLE inventory
7. ( inventory_id INT PRIMARY KEY,
8. product_id INT NOT NULL,
9. quantity INT,
10. min_level INT,
11. max_level INT,
12. CONSTRAINT fk_inv_product_id
13. FOREIGN KEY (product_id)
14. REFERENCES products (product_id)
15. );

Output:

The foreign key constraint in "inventory" table is fk_inv_product_id. It will establish a relationship
between the product_id column in the inventory table and the product_id column in the products
table.

You can now check the both tables.


Create foreign key with more than one field
In the above example, we see how to create a foreign key having one column. Let's create foreign key
having more than one field.

Let's create two table "products2" and "inventory2". In this example, "products2" table has a primary
key that contains both the product_name and location columns. Therefore, the second table and
foreign key must also reference these two columns.

So in this example, our foreign key called fk_inv_product references the products table based on two
fields: the product_name and location fields.
1. CREATE TABLE products2
2. ( product_name VARCHAR(50) NOT NULL,
3. location VARCHAR(50) NOT NULL,
4. category VARCHAR(25)
5. CONSTRAINT products_pk PRIMARY KEY (product_name, location)
6. );
7. CREATE TABLE inventory2
8. ( inventory_id INT PRIMARY KEY,
9. product_name VARCHAR(50) NOT NULL,
10. location VARCHAR(50) NOT NULL,
11. quantity INT,
12. min_level INT,
13. max_level INT,
14. CONSTRAINT fk_inv_product
15. FOREIGN KEY (product_name, location)
16. REFERENCES products2 (product_name, location)
17. );

Output:
Enable a Foreign Key
ALTER TABLE statement is used to enable a foreign key in SQL Server.

Syntax:

1. ALTER TABLE table_name


2. CHECK CONSTRAINT fk_name;

Parameter Explanation
table_name: It specifies the name of the table where the foreign key has been created.

fk_name: It specifies the name of the foreign key that you wish to disable.

Example:

We have disabled the foreign key in previous example, now enable the foreign key.

1. ALTER TABLE inventory


2. CHECK CONSTRAINT fk_inv_product_id;

Output:

Now the foreign key is enabled.


Disable Foreign Key
ALTER TABLE statement is used to disable a foreign key. Once you have created a foreign key in SQL
Server, you may get a situation where you are want to disable the foreign key, use the following
syntax.

Syntax:

1. ALTER TABLE table_name


2. NOCHECK CONSTRAINT fk_name;

Parameter explanation
table_name: It specifies the name of the table where the foreign key has been created.

fk_name: It specifies the name of the foreign key that you wish to disable.

Play Video
x

Example:

Create a foreign key by creating two tables "products3" and "inventory" table.

1. CREATE TABLE products3


2. ( product_id INT PRIMARY KEY,
3. product_name VARCHAR(50) NOT NULL,
4. category VARCHAR(25)
5. );
6. CREATE TABLE inventory3
7. ( inventory_id INT PRIMARY KEY,
8. product_id INT NOT NULL,
9. quantity INT,
10. min_level INT,
11. max_level INT,
12. CONSTRAINT fk_inv_product_id
13. FOREIGN KEY (product_id)
14. REFERENCES products3 (product_id)
15. );

Now use the following command to disable the foreign key where foreign constraint is:

fk_inv_product_id.
1. ALTER TABLE [javatpoint].[dbo].[inventory]
2. NOCHECK CONSTRAINT fk_inv_product_id;

Output:

Now the foreign key is disabled.

Drop a Foreign Key


ALTER TABLE statement is used to drop a foreign key from a table once it has been created.

Syntax:

1. ALTER TABLE table_name


2. DROP CONSTRAINT fk_name;

Parameter explanation
table_name: It specifies the name of the table where the foreign key has been created.

fk_name: It specifies the name of the foreign key that you want to remove.

Example:

In the previous example we have seen how to create a foreign key.


1. CREATE TABLE products
2. ( product_id INT PRIMARY KEY,
3. product_name VARCHAR(50) NOT NULL,
4. category VARCHAR(25)
5. );
6. CREATE TABLE inventory
7. ( inventory_id INT PRIMARY KEY,
8. product_id INT NOT NULL,
9. quantity INT,
10. min_level INT,
11. max_level INT,
12. CONSTRAINT fk_inv_product_id
13. FOREIGN KEY (product_id)
14. REFERENCES products (product_id)
15. );

Use the following command to drop the foreign key called fk_inv_product_id.

1. ALTER TABLE [javatpoint].[dbo].[inventory]


2. DROP CONSTRAINT fk_inv_product_id;

Output:

Now the foreign key is dropped.

You might also like