SQL Server Tutorial NEW
SQL Server Tutorial NEW
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.
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 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.
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
bit It is an integer type that allows us to store 0, 1, and NULL values. 1 byte
Numeric(p, s) It is similar to the decimal data type because both are synonyms. 5 to 17 bytes.
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].
varbinary It is used to store variable-length binary string. The actual length of data
entered + 2 bytes
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.
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:
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.
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).
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.
o Transact-SQL Command
o SQL Server Management Studio
In the above syntax, the database_name indicates the name of 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:
SQL Server allows the stored procedure statement to list all databases stored in the database engine
as below:
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.
o Transact-SQL Command
o SQL Server Management Studio
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:
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.
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:
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:
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:
o Transact-SQL Command
o SQL Server Management Studio
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:
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.
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).
o Transact-SQL Command
o SQL Server Management Studio
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:
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.
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:
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:
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.
Syntax:
The following syntax of INSERT INTO command allows us to add single row in a table:
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:
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.
1. f we want to store single records for all fields, use the syntax as follows:
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:
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:
This statement is executed successfully. Verifying the data will display the below output:
This statement is executed successfully. Verifying the data will display the below output:
To read more information, click here.
If we want to capture inserted values from multiple columns, we are required to specify the columns
in the output as follows:
"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:
Let's execute the following statements to insert a value for the identity column in the Student table:
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:
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:
Parameter Explanation
The above syntax parameter description is given below:
Parameter Descriptions
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:
1. UPDATE Student
2. SET Marks = 492
3. WHERE Name = 'Alan Simmons';
After successful execution, we will verify the table using the below statement:
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.
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
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:
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.
Example:
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.
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:
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:
Example
Suppose we want to add a new column 'Phone_number' into the Student table. We can do this by
using the below command:
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:
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:
Example
Suppose we want to drop a 'Phone_number' column from the Student table. We can do this by
using the below command:
We can verify whether this column is deleted or not from the table using the below statement:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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.
Syntax
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.
We can verify the view data using the SELECT statement as below:
Using sp_rename
The following syntax is used to rename a view:
Suppose we want to change the name of the above-created view course_enrolled to course. The
following query explains this concept:
Once we click the Rename option, we are able to change its name:
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:
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.
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
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:
It will delete the view successfully. If we execute this command again, we will get the below error
message:
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.
Syntax
The following syntax explain the MIN() function in SQL Server:
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.
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:
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.
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.
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.
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.
Syntax
The following syntax explain the MAX() function in SQL Server:
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.
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:
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.
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:
Example5: This example uses the MAX() function with two columns to get the highest resultant
output:
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.
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:
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:
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.
Executing the query will return the following output that shows the sum of only unique values of the
salary column:
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:
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:
Syntax
The following syntax illustrate the AVG() function in SQL Server:
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:
Executing the query will return the below output that shows the average working hours of employees:
When we execute the query, we see that the average working hours of the writer is 11 hours:
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:
Executing the statement will display the result in the descending order based on the
aggregated average value:
Executing the statement will return the average working hour of employees greater than ten in the
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];
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.
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:
This statement will count all employees as there are no NULL records found:
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:
Executing the statement will display the result in the ascending order of the number of employees:
Executing the statement will return the number of employees greater than one in each occupation:
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.
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:
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:
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:
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.
Output:
Example:
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:
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:
1. SELECT name
2. FROM [javatpoint].[dbo].[Employees]
3. INTERSECT
4. SELECT name
5. FROM [javatpoint].[dbo].[Employee2];
Output:
Output:
It shows blank because nothing is common between them according to the query.
Syntax
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.
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:
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.
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.
Syntax:
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.
1. SELECT *
2. FROM [javatpoint].[dbo].[Employees]
3. WHERE salary IS NULL;
Output:
Output:
Note: This displays "0 rows affected" because there is no NULL value in name in the "Employees"
table.
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:
Example:
Output:
Syntax:
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.
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:
Output:
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:
Syntax:
Parameter Explanation
expression: It is a character expression like a column or field.
9K
Class 9th - Equal Chords and their Distances from the Centre
Wildcar Explanation
d
% It is used to match any string of any length (including zero length).
[] 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)
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:
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:
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:
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.
Syntax:
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:
Select distinct salary from Employees where salary is greater than 12000.
Output:
Here, you can see that there is only 6 distinct salaries within 9 records. Distinct clause shows only
unique records.
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:
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.
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:
Output:
GROUP By using COUNT Function
See this example where we GROUP BY designation from the "Employee2" using COUNT function:
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.
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.
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.
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;
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.
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:
Equal =
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:
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.
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.
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.
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.
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.
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.
Executing the query will return all employee information whose occupation does not have the 'Writer'
occupation:
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];
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.
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.
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:
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;
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.
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.
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.
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:
Executing the statement will return the following output where OFFSET 3 skips the three rows and
FETCH 4 ROWS ONLY displays the required result.
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;
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.
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:
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:
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.
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.
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:
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.
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:
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:
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:
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:
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:
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:
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:
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.
The below table explains GROUPING SETS equivalent UNION ALL, ROLLUP, and CUBE more
clearly:
Next, execute the below statement to insert records into this table:
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.
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;
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.
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:
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.
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.
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:
Or
Example:
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:
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:
Output:
1. SELECT *
2. FROM [javatpoint].[dbo].[cricketers3]
Output:
Here, last_name and first_name both is primary key.
If a column of a table has NULL values, you cannot add a primary key without dropping and
recreating the table.
Syntax:
Example:
Output:
It will create a primary key "cricketer_id" in the "cricketers2" table.
Syntax:
Example:
x
1. ALTER INDEX cricketers2_pk ON [javatpoint].[dbo].[cricketers2]
2. REBUILD;
Output:
Now primary key "customer_id" is enabled in table "customers".
Syntax:
Example:
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:
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.
00:00/11:06
22.6M
314
Triggers in SQL (Hindi)
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.
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.
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:
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.
Output:
Syntax:
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.
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:
Syntax:
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:
Use the following command to drop the foreign key called fk_inv_product_id.
Output: