SQL Server
SQL Server
SQL Server
SQL Server is a relational database management system (RDBMS) by
Microsoft. It supports SQL along with additional features known as T-SQL or
Transact-SQL.
Microsoft provides set of tools to manage local or remote SQL Server databases
such as SSMS (SQL Server Management Studio), SQL Server Agent, SQL
Server Analysis Services, SQL Server Reporting Services, SQL Server
Integration Services, etc.
SSMS can also be used to access, configure, manage & administer Analysis
services, Reporting services, & Integration services.
Advantages
Its simple and user-friendly syntax allows even non-technical users to interact with
databases and retrieve data without having to write lengthy lines of code. SQL also
provides a standardized way of communicating with databases, ensuring that data
is consistent and uniform across different systems.
SSMS Components
SQL Server Management Studio has the following components:
• Object Explorer
• Security
• Server Objects
• Query and Text Editor
• Template Explorer
• Solution Explorer
• Visual Database Tools
------------------------------------------------
There are two authentication modes in SQL Server using which you can login and
connect with the SQL Server.
• Windows Authentication
• SQL Server Authentication
Windows Authentication
• Windows authentication mode enables local Windows authentication with
SQL Server, where you can login with your local Windows credentials.
Server Authentication
Connecting through SQL Server Authentication. When using SQL Server
Authentication, logins are created in SQL Server that aren't based on
Windows user accounts. Both the user name and the password are created
by using SQL Server and stored in SQL Server.
There are two ways to create a new User or to grant user permissions:
You can GRANT and REVOKE permissions on various database objects in SQL
Server. User permissions are at the database level.
• Select: Grants user the ability to perform Select operations on the table.
• Insert: Grants user the ability to perform the insert operations on the table.
• Update: Grants user the ability to perform the update operations on the
table.
• Delete: Grants user the ability to perform the delete operations on the table.
• Alter: Grants user permission to alter the table definitions.
• References: References permission is needed to create a Foreign key
constraint on a table. It is also needed to create a Function or View WITH
SCHEMABINDING clause that references that object
• Control: Grants SELECT, INSERT, UPDATE, DELETE, and REFERENCES
permission to the User on the table.
Data Types
• In SQL Server, data type specifies the type of data that can be stored in a
column of a table such as integer data, string data, date & time, binary
strings, etc.
• SQL Server provides built-in data types for all kinds of data that can be
used within SQL Server
Naming Conventions
• SQL Server defines a set of rules (dos and don'ts) for naming SQL Server
Objects called naming convention, but also gives the user to follow their
own preferred style. It is advisable to follow a single naming convention for
all database objects consistently.
Why Use Naming Conventions
• Following a naming convention for tables, columns, and all other related
database objects like views, stored procedures, indexes, triggers, etc., are
important for the success and maintenance of a project. A database can
have many tables and users working on it. By following a naming
convention, you can spend less time finding what you need and helps in
efficient database management.
Create Database
• In SQL Server, a database is made up of a collection of objects like tables,
functions, stored procedures, views etc. Each instance of SQL Server can
have one or more databases.
• SQL Server databases are stored in the file system as files. A login is used
to gain access to a SQL Server instance and a database user is used to
access a database. SQL Server Management Studio is widely used to work
with a SQL Server database.
• master: master database stores all system level information for an instance
of SQL Server. It includes instance-wide metadata such as logon accounts,
endpoints, linked servers, and system configuration settings.
• model: model database is used as a template for all databases created on the
instance of SQL Server
• msdb: msdb database is used by SQL Server Agent for scheduling alerts and
jobs and by other features such as SQL Server Management Studio, Service
Broker and Database Mail.
• tempdb: tempdb database is used to hold temporary objects, intermediate
result sets, and internal objects that the database engine creates.
Identity Column
In SQL Server, a column in a table can be set as an identity column. It is used
for generating key values for primary key columns.
Syntax:
column_name data_type IDENTITY[(seed, increment)]
Parameters:
1. Seed is the first value of the identity column.
2. Increment is the incremental value added to the identity value of the previous
row.
Syntax:
EXEC sp_rename 'old_name', 'new_name' [, 'object_type'];
Syntax:
ALTER TABLE [schema_name.]table_name
DROP column column_name1, column_name2,... column_nameN;
Database Schema
In SQL Server, a schema is a logical collection of database objects such as tables,
views, stored procedures, indexes, triggers, functions. It can be thought of as a
container, created by a database user. The database user who creates a schema
is the schema owner.
• A schema can belong to only one database whereas a database can have one
or multiple schemas.
• There are no restrictions on the number of objects in a schema.
• SQL Server provides us with a few built-in schemas such as dbo, guest, sys,
etc.
• A database schema can be owned by a database role or an application role
along with the database user. They are called schema owners.
• dbo is the default schema for a newly created database.
• Schema ownership can be transferred from one user to another user in the
same database.
• A database user can be dropped without dropping the database objects owned
by the user. But the schema cannot be deleted if it owns database objects.
Tables Relations
It is important to understand and design relationships among tables in a relational
database like SQL Server. In a relational database, each table is connected to
another table using the Primary-Foreign Key constraints.
1. One-to-One
2. One-to-Many
3. Many-to-Many
The following query will display data from all the tables.
Primary Key
Here you will learn what is a primary key and how to create it in a new or existing
table in the SQL Server database.
• A foreign key column can be linked to a primary key or a unique key column
of the same or another table.
• Foreign key constraints can reference tables within the same database in the
same server.
• Foreign key constraints can be defined to reference another column in the
same table. This is referred to as a self-reference.
Check Constraints
In SQL Server, a check constraint is used to specify the limitation on the values
of a column when inserting or updating.
Unique Key Constraints
The Unique Constraint ensures the uniqueness of all values and no duplicate
values are entered in a column of a table.
Views
In SQL Server, a view is a virtual table whose values are defined by a query. In
another word, a view is a name given to a query that can be used as a table. The
rows and columns of a view come from tables referenced by a query.
Important Points
• Unless indexed, a view does not exist as a stored set of data values in a
database.
• Views can be created by using tables or other views in the current or other
databases.
• The SQL statements comprising the view are stored in the database and not
the resulting data.
• The data from a view is generated dynamically when a view is referenced.
Functions
• Functions in SQL Server are similar to functions in other programming
languages. Functions in SQL Server contains SQL statements that perform
some specific tasks. Functions can have input parameters and must return
a single value or multiple records.
Types of Functions
SQL Server Functions are of two types:
User Defined Functions (UDFs): Functions created by the database user are
called User-defined functions. UDFs are of two types:
1. Scalar functions: The function that returns a single data value is called a scalar
function.
2. Table-valued functions: The function that returns multiple records as a table
data type is called a Table-valued function. It can be a result set of a single
select statement.
Stored Procedures
A stored procedure is a group of SQL statements that are created and stored in a
database management system, allowing multiple users and programs to share and
reuse the procedure. A stored procedure can accept input parameters, perform the
defined operations, and return multiple output values.
System procedures: System procedures are included with SQL Server and are
physically stored in the internal, hidden Resource database and logically appear
in the sys schema of all the databases. The system stored procedures start with
the sp_ prefix.
Advantages of Stored procedures
• Stored procedures are reusable. Multiple users in multiple applications can
use the same Stored Procedure (SP)
• As SPs reside in the database, it reduces network traffic. Applications have to
make a procedure call to the database and it communicates back to the user.
• Database objects are encapsulated within a stored procedure, and this acts
as a security mechanism by restricting access to the database objects.
• Reduced development cost, easily modified, and increased readability.
• Improves performance. When a stored procedure is executed for the first
time, the database processor creates an execution plan which is re-used every
time this SP is executed
• A stored procedure can have zero or more INPUT and OUTPUT parameters.
• A stored procedure can have a maximum of 2100 parameters specified.
• Each parameter is assigned a name, a data type, and direction like Input,
Output, or Return. If a direction is not specified, then by default, it is Input.
• You can specify a default value for the parameters.
• Stored procedures can return a value to the calling program if the parameter
is specified as OUTPUT.
• The parameter values must be a constant or a variable. It cannot be a function
name.
• Parameter variables can be either user-defined or system variables like @spid
Parameter Names
• The stored procedure parameters names must start with a single @.
• The name must be unique in the scope of the stored procedure.
• If parameter values are passed as @Param1 = value1, @ Param2 = value2
as shown in the above example, then the parameters can be passed in any
order.
OUTPUT Parameters
• The OUTPUT parameter is used when you want to return some value from
the stored procedure. The calling program must also use the OUTPUT
keyword while executing the procedure.
Optional Parameters
• SQL Server allows you to specify the default values for parameters. It allows
you to skip the parameters that have default values when calling a stored
procedure.
An index is mostly created on one or more columns which are commonly used in
the SELECT clause or WHERE clause.
1. Clustered Indexes
2. Non-Clustered Indexes
Clustered Indexes
3. The clustered index defines the order in which the table data will be sorted
and stored. As mentioned before, a table without indexes will be stored in
an unordered structure. When you define a clustered index on a column, it
will sort data based on that column values and store it. Thus, it helps in
faster retrieval of the data.
4. There can be only one clustered index on a table because the data rows can
be stored in only one order.
5. When you create a Primary Key constraint on a table, a unique clustered
index is automatically created on the table.
Non-Clustered Indexes
SQL Server provides two types of indexes, clustered and non-clustered
indexes. Here you will learn non-clustered indexes.
The non-clustered index does not sort the data rows physically. It creates a
separate key-value structure from the table data where the key contains
the column values (on which a non-clustered index is declared) and each
value contains a pointer to the data row that contains the actual value.
Modify Index
To add, remove, or change the position of an index column, you must drop and
recreate the index. However, you can set several options on the index using
ALTER INDEX statement.
Create Synonym
A few points to consider while creating a synonym:
• A synonym must have a unique name just like other database objects in a
schema.
• A synonym cannot be a base object for another synonym.
• A synonym cannot reference a user -defined aggregate function.
SQL Server supports the WHILE loop. The execution of the statements can be
controlled from within the WHLE block using BREAK and CONTINUE keywords.
----------------------------------- * -------------------------------------------
Syntax:
INSERT INTO table_name(column_name1, column_name2...)
VALUES(column1_value, column2_value...);
Syntax:
UPDATE table_name
column_name2 = new_value,
...
[WHERE Condition];
Note that the WHERE clause is optional, but you should use it to update the
specific record.
Syntax:
DELETE FROM table_name [WHERE Condition];
FROM table_name
Advantage of Alias:
WHERE Clause
In SQL Server, the SELECT statement can have an optional WHERE clause to filter
the data. The WHERE clause can include one or more boolean conditions to filter
out data of the tables.
The WHERE clause always comes after the FROM clause and before GROUP BY,
HAVING, and ORDER BY clauses.
GROUP BY Clause
In SQL Server, the GROUP BY clause is used to get the summary data based on
one or more groups. The groups can be formed on one or more columns. For
example, the GROUP BY query will be used to count the number of employees in
each department, or to get the department wise total salaries.
You must use the aggregate functions such as COUNT(), MAX(), MIN(), SUM(), AVG(),
etc., in the SELECT query. The result of the GROUP BY clause returns a single
row for each value of the GROUP BY column.
Syntax:
SELECT column1, column2,...columnN FROM table_name
[WHERE]
[ORDER BY]
HAVING Clause
In SQL Server, the HAVING clause includes one or more conditions that should
be TRUE for groups of records. It is like the WHERE clause of the GROUP BY
clause. The only difference is that the WHERE clause cannot be used with
aggregate functions, whereas the HAVING clause can use aggregate functions.
The HAVING clause always comes after the GROUP BY clause and before the
ORDER BY clause.
Syntax:
SELECT column1, column2,...columnN
FROM table_name
[WHERE]
[HAVING conditions]
[ORDER BY]
ORDER BY Clause
In SQL Server, the ORDER BY clause is used in the SELECT query to sort the
result in ascending or descending order of one or more columns.
Syntax:
SELECT column1, column2,...columnN
FROM table_name
[WHERE]
[GROUP BY]
[HAVING]
ORDER BY Characteristics:
• The ORDER BY clause is used to get the sorted records on one or more
columns in ascending or descending order.
• The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING
clause if present in the query.
• Use ASC or DESC to specify the sorting order after the column name. Use
ASC to sort the records in ascending order or use DESC for descending order.
By default, the ORDER BY clause sort the records in ascending order if the
order is not specified.
Syntax:
SELECT table1.column_name(s), table2.column_name(s)
FROM table1
ON table1.column_name = table2.column_name;
Here, the right side table is a table that comes to the right side or after the
"RIGHT JOIN" phrase in the query, and the left table is a table that comes at the
left side or before the "RIGHT JOIN" phrase.
The RIGHT JOIN returns NULL for all non-matching records from the left table. In
some databases, it is called RIGHT OUTER JOIN.
In some databases, FULL JOIN is called FULL OUTER JOIN. It can return a very
large result set because it returns all the rows from all the tables.
There is no Self Join keyword. You write a normal join where both the tables
involved in the join are the same.
Syntax: Self-join
Copy
SELECT a.column1, b.column2
FROM table1 a, table1 b
WHERE condition;
Dynamic SQL in SQL Server
Dynamic SQL is a programming technique where you build SQL query as a string
and execute it dynamically at runtime. It lets you build the general-purpose query
on the fly using variables, based on the requirements of the application. This
makes a dynamic SQL more flexible as it is not hardcoded.
Copy
DECLARE @sql nvarchar(max) --declare variable
DECLARE @empId nvarchar(max) --declare variable for parameter
Built-in Functions
The following is the list of built-in String functions, DateTime functions, Numeric
functions and conversion functions.