Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

rikiritesh

Ritesh Khatri (Tech Lead)


What is Data ?

• Data is the lifeblood of business, and it comes in a huge variety of formats.


What is Data ?
rikiritesh
Ritesh Khatri (Tech Lead)
What is RDBMS ?

• RDBMS stands for Relational DataBase Management System.

• All modern database management systems like MS SQL Server, IBM DB2, ORACLE, My-SQL and Microsoft
Access are based on RDBMS.
What is SQL Server ?

• SQL is stand for Structure Query Language.


• SQL Server is a relational database management system (RDBMS) developed by Microsoft.
• Used to store, update and retrieve ( CRUD - Create, Read, Update & Delete) the information from/to the
database.
Connecting to SQL Server

• SQL Server Management Studio (SSMS), is the client tool that can be used to write and execute SQL
queries. To connect to the SQL Server Management Studio.

• Server Type = Database Engine.

• Server Name = (local) or 127.0.0.1 or Instance Name.

• Authentication = Windows OR SQL Authentication.

• If SQL Server Authentication


• Login
• Password
Authentication Mode
• Windows Authentication Mode
• Windows authentication is the default and is often referred to as integrated security because this SQL Server security model is
tightly integrated with Windows.

• Mixed Mode
• Mixed mode supports authentication both by Windows and by SQL Server.
Authentication Mode
• Authentication Mode
• Windows Authentication Mode
o SRKAYCG/Ritesh.Khatri

• Mixed Mode
o SRKAYCG/Ritesh.Khatri
o sa (super admin default SQL user)
o Other normal users
Connecting to SQL Server

• Connection Failed !!!!!


Keep in Min while going with SQL … !!!
• Structure query language is not case sensitive.
• Statements of SQL are dependent on text lines. We can use a single SQL statement on one or multiple
text line.
• Using the SQL statements, you can perform most of the actions in a database.
• Make sure on query page about your Active Server & Database.
• Cannot find the object "Products" because it does not exist or you do not have permissions.
• There is already an object named 'Utility_CertiModificationProcess_Fill' in the database.
What is Database ?

• SQL Database is organized collection of structure information or data stored in file.

• Database Files

.MDF File (Data File) = Contain Actual Data

.LDF File (Transaction Log File) = Used to recover the database

• Database Files can be multiple as per the requirement


Create / Alter / Delete

• Create Database :
CREATE DATABASE Developer_Ritesh_DB.

• Alter/Rename Database :
ALTER DATABASE Developer_Ritesh_DB MODIFY NAME = Dev_Ritesh

• Drop/Delete Database :
DROP DATABASE Dev_Ritesh

• Get Database List :


Select * From sys.databases
What is Schema ?

• A Schema in SQL is a collection of database objects associated with a database.

• Schema always belong to a single database whereas a database can have single or multiple schemas.

• SQL Server have some built-in schema, for example : dbo, guest, sys, and INFORMATION_SCHEMA.

• Syntax :

CREATE SCHEMA schemaname [AUTHORIZATION ownername]

• Get Schema List :


Select * From sys.schemas
System Datatypes
User Defined Types
• SQL Server supports two kinds of user-defined types.
o Data Types
o Table Types
Table in SQL Server
• User Table (Regular Table)
• Local Temporary Table
• Global Temporary Table
• Table Variable
• Heap Table
What is Table (User Table) ?
• Tables are database objects that contain all the data in a database. In tables, data is logically organized in a row-
and-column format similar to a spreadsheet.

• A standard user-defined table can have up to 1,024 columns.

• The number of rows in the table is limited only by the storage capacity of the server.

• You can assign properties to the table and to each column in the table to control the data that is allowed and other
properties.

• For example, you can create constraints on a column to disallow null values or provide a default value if a value is
not specified, or you can assign a key constraint on the table that enforces uniqueness or defines a relationship
between tables.

• Syntax :
CREATE TABLE table_name (column1 datatype, column2 datatype, ….., column N datatype]

• Get Schema List :


Select * From sys.tables
Table
• CREATE -
create table tablename
(column1 data type,
column2 data type,
...
columnN data type);
• ALTER -
ALTER TABLE table_name ADD column_name datatype, column_name datatype, …… column_name datatype
ALTER TABLE table_name ALTER COLUMN column_name datatype
ALTER TABLE table_name DROP COLUMN column_name
• RENAME - sp_rename ‘ old_tablename’, ‘new_table_name’
• DROP - Drop table tablename
• DELETE - Delete From tablename [Where condition]
• TRUNCATE - Truncate Table tablename
Drop vs Delete vs Truncate
Drop Delete Truncate

Command Type DDL DML DDL

Rollback Transactions NO Can be Rolledback NO

Permanent Delete Does with structure Does not Does

Trigger NO YES NO

Perfomance Quick with Complication Slower Than Truncate Faster Than Delete

Where Clause NO YES NO


Local & Global Temporary Table
• Creating a local & Global Temporary table is very similar to creating a permanent table, except that you prefix the
table name with 1 pound (#) symbol for local & 2 pound (##) symbol for global.

• Local temporary tables are temporary tables that are available only to the session that created them. These tables
are automatically destroyed at the termination of the procedure or session.

• Global temporary tables are temporary tables that are available for all session & all user. They are dropped
automatically when the last session using the temporary table has completed

• Both tables are stored in the tempdb system database.

CREATE TABLE #employee (column1 varchar(20), column2 int)

CREATE TABLE ##employee (column1 varchar(20), column2 int)


Table Variable
• The table variable is a special type of the local variable that helps to store data temporarily, similar to the temp
table in SQL Server. except that you prefix the table name with (@) symbol.

Declare @employee TABLE (column1 varchar(20), column2 int)


Copy Table

• COPY TABLE
Select * INTO new_tablename
From tablename

• SQL will consider New Create table by using Copy Table as HEAP table
Table Variable vs Temporary Table
• Table variable (@table) is created in the memory. Whereas, a Temporary table (#temp) is created in the
tempdb database.

• Table variables cannot be involved in transactions, logging or locking. This makes @table faster then
#temp. So table variable is faster then temporary table.

• Temporary tables are allowed CREATE INDEXes whereas, Table variables aren’t allowed CREATE INDEX
instead they can have index by using Primary Key or Unique Constraint.

• Table variable can be passed as a parameter to functions and stored procedures while the same cannot
be done with Temporary tables.

• Temporary tables are visible in the created routine and also in the child routines. Whereas, Table
variables are only visible in the created routine.

• Temporary table allows Schema modifications unlike Table variables.


Constraints
• Constraints in SQL Server are predefined rules and restrictions that are enforced in a single column or
multiple columns.

• In other words, if the inserted data meets the constraint rule, it will be inserted successfully. If the
inserted data violates the defined constraint, the insert operation will be aborted.

• There are six main constraints that are commonly used in SQL Server.
o NOT NULL
o DEFAULT
o UNIQUE
o PRIMARY KEY
o FOREIGN KEY
NOT NULL - Constraint

• By default, the columns are able to hold NULL values. A NOT NULL constraint in SQL is used to prevent
inserting NULL values into the specified column.

CREATE TABLE table_name (column_name datatype NOT NULL)

ALTER TABLE table_name ADD COLUMN column_name datatype NOT NULL

ALTER TABLE table_name ALTER COLUMN column_name datatype NOT NULL


Default - Constraint
• The DEFAULT constraint is used to set a default value for a column.

• The default value will be added to all new records, if no other value is specified.
UNIQUE - Constraint
• The UNIQUE constraint in SQL is used to ensure that no duplicate values will be inserted into a specific
column or combination of columns.

• In other words, It will guarantee that no two rows in that table can have the same value for the
columns participating.
• With the ability to insert only one UNIQUE NULL value to these columns, if the column allows NULL.

ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE column_name


PRIMARY KEY - Constraint
• A column or columns is called primary key (PK) that uniquely identifies each row in the table.

• The SQL PRIMARY KEY constraint combines between the UNIQUE and SQL NOT NULL constraints.

• When multiple columns are used as a primary key, it is known as Composite Primary Key.
• If the PRIMARY KEY is defined in multiple columns, you can insert duplicate values on each column
individually, but the combination values of all PRIMARY KEY columns must be unique.

CREATE TABLE Production.TransactionHistoryArchive1


(
TransactionID int IDENTITY (1,1) NOT NULL
,CONSTRAINT PK_TransactionHistoryArchive1_TransactionID PRIMARY KEY CLUSTERED (TransactionID)
)

ALTER TABLE Production.TransactionHistoryArchive ADD CONSTRAINT


PK_TransactionHistoryArchive_TransactionID PRIMARY KEY CLUSTERED (TransactionID ASC);
FOREIGN KEY - Constraint
• A Foreign key is constraint that enforces referential integrity in SQL server database

• To create a SQL foreign key constraint, the parent table should have primary key column or column
with UNIQUE constraint.
PRIMARY KEY vs FOREIGN KEY
• Primary key cannot be null on the other hand foreign key can be null.

• Primary key is always unique while foreign key can be duplicated.

• Primary key uniquely identify a record in a table while foreign key is a field in a table that is primary key
in another table.

• There is only one primary key in the table on the other hand we can have more than one foreign key in
the table.
Index

• Indexes are used to speed-up query process in SQL Server, resulting in high performance.
• Indexes are created on tables and views.

• They are similar to textbook indexes. In textbooks, if you need to go to a particular chapter, you go to
the index, find the page number of the chapter and go directly to that page.

• Without indexes, the process of finding your desired chapter would have been very slow.

• The existence of the right indexes, can drastically improve the performance of the query. If there is no
index to help the query, then the query engine, checks every row in the table from the beginning to the
end. This is called as Table Scan. Table scan is bad for performance.
• There are below types of Indexes in SQL Server:
Clustered, Non-Clustered, Unique, Filtered, XML, Full Text, Spatial, Columstore, Index with included columns,
Index on computed columns
Clustered Index

• A clustered index defines the order in which data is physically stored in a table.
• There can be only one clustered index per table.

• In SQL Server, the primary key constraint automatically creates a clustered index on that particular
column.

• A B-Tree (computed) clustered index is the index that will arrange the rows physically in the memory in
sorted order.
• A clustered index is analogous to a telephone directory, where the data is arranged by the last name.
How Index Works

Create Table Employees


(
Id int primary key identity,
[Name] nvarchar(50),
Email nvarchar(50),
Department nvarchar(50)
)

• EmployeeId is the primary key, so by default a clusterd index on the EmployeeId column is created.

• This means employee data is sorted by EmployeeId column and physically stored in a series of data
pages in a tree like structure….. Like…
How Index Works

• The node at the top of the tree is called Root Node.


• The nodes between the root node and the leaf nodes are called intermediate levels.
• The root and the intermediate level nodes contain index rows.
• The nodes at the bottom of the tree are called data pages or leaf nodes and contain the actual data rows, in our
case employee rows.
• Each index row contains a key value (in our case Employee Id) and a pointer to either an intermediate level page in
the B-tree, or a data row in the leaf node.
How Index Works
• For our example, let's say in Employees table we have 1200 rows and let's assume in each data page we have 200
rows.
• Select * From Employee Where Id = 1120
Non-Clustered Index
• A non-clustered index is an index that will not arrange the rows physically in the memory in sorted order.

• A non-clustered index is analogous to an index in textbook, where the data stored in one place and index in
another place.
• A one table can have multiple non-clustered index up to 999.
Cluster - Non-Clustered

S.No Clustered Non-clustered


1 A clustered index is used to sort the table or organize the data in A non-clustered index stores the data and records separately.
alphabetical order.

2 It operates faster than a non-clustered index. It operates slower than the clustered index.

3 It requires less memory to perform operations. It requires more memory to perform operations.

4 It allows storing data pages in the leaf nodes of the index. It does not store data pages in the leaf nodes of the index.

5 A single table can have only one cluster index. A single table can have multiple non-clustered indexes.
Identity
• Identity column of a table is a column whose value increases automatically.

• The value in an identity column is created by the server.

• A user generally cannot insert a value into an identity column.


IDENTITY [ ( seed, increment) ]

o Seed : Starting value of a column. Default value is 1.

o Increment : Incremental value that is added to the identity value of the previous row that was
loaded. The default value 1.
Query Statement
• Select column_list From tablename

• Join

• Where condition

• Group By
• Having
• Order By
Query Statement
Select sd.stoneid, sd.certificate_code, lot_code, serial_number, inward_datetime,
stone_process_code, stone_status_code, department_code, location_code, first_market_date,
business_logic_code, action_code, mfg_ownership_branch_code AS mfg_branch_code
From Packet.stone_details AS sd
--------------------------------------------------------------------------------------------------
left join Packet.stone_lab_master AS slm on sd.stoneid = slm.stoneid
and sd.certificate_code = slm.certificate_code
left join Packet.stone_rates AS sr on sr.stoneid = sd.stoneid
--------------------------------------------------------------------------------------------------
Where (@stoneids = '' OR sd.stoneid IN (select value from string_split(@stoneids,',')))
and (@certificate_code = 0 OR sd.certificate_code = @certificate_code)
--------------------------------------------------------------------------------------------------
Group by sd.stoneid, sd.certificate_code
--------------------------------------------------------------------------------------------------
Having count(sd.stoneid) > 1
--------------------------------------------------------------------------------------------------
Order by sd.stoneid, sd.certificate_code

You might also like