SlideShare a Scribd company logo
MS SQL SERVER TIPS
By Arman Aug-18
• Relationship Database Management System
• Database Design
• Indexes
• Useful Queries
RELATIONSHIP DATABASE MANAGEMENT SYSTEM
 Collection of information organized in tables
 Tables are also “Relations”
 Tables are constructed and associated to each other through shared fields.
 Fields are also “Columns” or “Attributes”
 A set of attributes comprises a record
 Records are also “Rows” or “Tuples”
 Tables are related through common fields designated as primary key and foreign keys.
 Allow us to find, update, and delete data quickly, and help to ensure accuracy
RELATIONSHIP DATABASE MANAGEMENT SYSTEM
 Primary Key :
 Primary key fields must be unique and cannot contain a null value
 Each table should have a primary key field[s].
 Composite Key: Using more than one field as a primary key.
 Foreign Key :
 Fields in a table that refer to the primary key in another table.
 The data in this field must exactly match data contained in the primary key
DATABASE DESIGN RELATIONSHIP TYPES
 One-to-one relationships
 One-to-many relationships
 Many-to-many relationships
 Mandatory or not?
DATABASE DESIGN NORMALIZATION
 First normal form (1NF)
 Second normal form (2NF)
 Third normal form (3NF)
DATABASE DESIGN NORMALIZATION 1NF
 First normal form (1NF)
I. It should only have single(atomic) valued attributes/columns.
II. Values stored in a column should be of the same domain
III. All the columns in a table should have unique names.
IV. And the order in which data is stored, does not matter.
DATABASE DESIGN NORMALIZATION 2NF
 Second normal form (2NF)
I. It should be in the First Normal form.
II. And, it should not have Partial Dependency.
DATABASE DESIGN NORMALIZATION 3NF
 Third normal form (3NF)
I. It is in the Second Normal form.
II. And, it doesn't have Transitive Dependency.
DATABASE DESIGN NORMALIZATION BCNF
 Boyce-Codd Normal Form (BCNF)
I. It should be in the Third Normal Form.
II. And, for any dependency A → B, A should be a super key.
DATABASE DESIGN NORMALIZATION 4NF
 Fourth Normal Form (4NF)
INDEXES TYPES
 Regulations
 1 Clustered Index per Table
 249 Non Clustered (2005)
 999 Non Clustered (2008+)
 16 Columns or 900 Bytes
 Clustered Index
 Nonclustered Index
 Unique index
 Filtered index
 Full-Text
 XML
CLUSTERED TABLE VS HEAP TABLE
Clustered Indexed Table Heap Table
CLUSTERED INDEX
 Clustered Index – sort order of the data within the table on the hard
drive and in memory.
 One per table
 Desired Qualities
 Narrow Data Type
 Unique
 Static
 Increasing
NONCLUSTERED INDEX
 Cover Common Queries
 Link to Clustered Indexes through Key
 Bookmark (Key/RID) Lookup
FRAGMENTATION
 Identifying Fragmentation
 2005
 DBCC SHOWCONTIG
 Above 2005
 sys.dm_db_index_physical_stats
Required Actions
avg_fragmentation_in_percent value Corrective statement
> 5% and < = 30% ALTER INDEX REORGANIZE
> 30% ALTER INDEX REBUILD WITH (ONLINE = ON)
USEFUL QUERIES
 Check index fragmentation using Transact-SQL
 2012
 2005
 DBCC SHOWCONTIG WITH TABLERESULTS, ALL_INDEXES;
 Currently running process
SELECT sqltext.TEXT,
req.session_id, req.status,req.command,
req.cpu_time, req.total_elapsed_time
,blocking_session_id ,wait_time ,wait_type
,logical_reads
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS
sqltext
SELECT a.index_id, name, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (DB_ID(N'UniversoDB2018'),
OBJECT_ID(N'dbo.tblindividual'), NULL, NULL, NULL) AS a
JOIN sys.indexes AS b
ON a.object_id = b.object_id AND a.index_id = b.index_id;
USEFUL QUERIES
 Check index fragmentation using Transact-SQL
SELECT TOP 10 SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1,
((CASE qs.statement_end_offset
WHEN -1 THEN DATALENGTH(qt.TEXT)
ELSE qs.statement_end_offset
END - qs.statement_start_offset)/2)+1),
qs.execution_count,
qs.total_logical_reads, qs.last_logical_reads,
qs.total_logical_writes, qs.last_logical_writes,
qs.total_worker_time, qs.last_worker_time,
qs.total_elapsed_time/1000000 total_elapsed_time_in_S,
qs.last_elapsed_time/1000000 last_elapsed_time_in_S,
qs.last_execution_time, qp.query_plan
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
ORDER BY qs.total_logical_reads DESC -- logical reads
-- ORDER BY qs.total_logical_writes DESC -- logical writes
-- ORDER BY qs.total_worker_time DESC -- CPU time
READ TYPES
 Index Scan
 Table Scan (Heap)
 Index Seek
 Key Lookup
 RID Lookup (heap)
RULES FOR EXECUTION PLAN COMPILATION
 Build up most resource efficient plan
 AS little page reads as possible
 Fastest Operation possible
 Choosing Indexes:
 Prefer read range over scan
 Prefer small indexes over large

More Related Content

What's hot

Inner join and outer join
Inner join and outer joinInner join and outer join
Inner join and outer joinNargis Ehsan
 
Assignment 3
Assignment 3Assignment 3
Assignment 3
SneaK3
 
Entity relationship diagram - Concept on normalization
Entity relationship diagram - Concept on normalizationEntity relationship diagram - Concept on normalization
Entity relationship diagram - Concept on normalization
Satya Pal
 
SQL Joins
SQL JoinsSQL Joins
SQL Joins
Paul Harkins
 
Unions and joins in mysql
Unions and joins in mysqlUnions and joins in mysql
OrACLE RELATIONAL
OrACLE RELATIONALOrACLE RELATIONAL
OrACLE RELATIONAL
ASHABOOPATHY
 
Chapter8 my sql revision tour
Chapter8 my sql revision tourChapter8 my sql revision tour
Chapter8 my sql revision tour
KV(AFS) Utarlai, Barmer (Rajasthan)
 
Sql joins
Sql joinsSql joins
Sql joins
Gaurav Dhanwant
 
Teradata imp
Teradata impTeradata imp
Teradata imp
Hameed Lebbai
 
Advance sqlite3
Advance sqlite3Advance sqlite3
Advance sqlite3Raghu nath
 
Sql join
Sql  joinSql  join
Sql join
Vikas Gupta
 
Join sql
Join sqlJoin sql
Join sql
Vikas Gupta
 
Displaying data from multiple tables
Displaying data from multiple tablesDisplaying data from multiple tables
Displaying data from multiple tables
Syed Zaid Irshad
 
Solutions manual for guide to sql 9th edition by pratt
Solutions manual for guide to sql 9th edition by prattSolutions manual for guide to sql 9th edition by pratt
Solutions manual for guide to sql 9th edition by pratt
Aldis8862
 
Normalization PRESENTATION
Normalization PRESENTATIONNormalization PRESENTATION
Normalization PRESENTATION
bit allahabad
 
Normalization
NormalizationNormalization
Normalization
Salman Memon
 
Chapter9 more on database and sql
Chapter9 more on database and sqlChapter9 more on database and sql
Chapter9 more on database and sql
KV(AFS) Utarlai, Barmer (Rajasthan)
 

What's hot (19)

Inner join and outer join
Inner join and outer joinInner join and outer join
Inner join and outer join
 
Assignment 3
Assignment 3Assignment 3
Assignment 3
 
Entity relationship diagram - Concept on normalization
Entity relationship diagram - Concept on normalizationEntity relationship diagram - Concept on normalization
Entity relationship diagram - Concept on normalization
 
SQL Joins
SQL JoinsSQL Joins
SQL Joins
 
Unions and joins in mysql
Unions and joins in mysqlUnions and joins in mysql
Unions and joins in mysql
 
OrACLE RELATIONAL
OrACLE RELATIONALOrACLE RELATIONAL
OrACLE RELATIONAL
 
Chapter8 my sql revision tour
Chapter8 my sql revision tourChapter8 my sql revision tour
Chapter8 my sql revision tour
 
Joins SQL Server
Joins SQL ServerJoins SQL Server
Joins SQL Server
 
Sql joins
Sql joinsSql joins
Sql joins
 
Teradata imp
Teradata impTeradata imp
Teradata imp
 
Advance sqlite3
Advance sqlite3Advance sqlite3
Advance sqlite3
 
Sql join
Sql  joinSql  join
Sql join
 
Join sql
Join sqlJoin sql
Join sql
 
Index Tuning
Index TuningIndex Tuning
Index Tuning
 
Displaying data from multiple tables
Displaying data from multiple tablesDisplaying data from multiple tables
Displaying data from multiple tables
 
Solutions manual for guide to sql 9th edition by pratt
Solutions manual for guide to sql 9th edition by prattSolutions manual for guide to sql 9th edition by pratt
Solutions manual for guide to sql 9th edition by pratt
 
Normalization PRESENTATION
Normalization PRESENTATIONNormalization PRESENTATION
Normalization PRESENTATION
 
Normalization
NormalizationNormalization
Normalization
 
Chapter9 more on database and sql
Chapter9 more on database and sqlChapter9 more on database and sql
Chapter9 more on database and sql
 

Similar to Ms sql server tips 1 0

Database Performance
Database PerformanceDatabase Performance
Database Performance
Boris Hristov
 
Basic SQL and History
 Basic SQL and History Basic SQL and History
Basic SQL and History
SomeshwarMoholkar
 
Relational database management system
Relational database management systemRelational database management system
Relational database management system
Praveen Soni
 
Dbms interview questions
Dbms interview questionsDbms interview questions
Dbms interview questions
ambika93
 
MSSQL_Book.pdf
MSSQL_Book.pdfMSSQL_Book.pdf
MSSQL_Book.pdf
DubsmashTamizhan
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
DraguClaudiu
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
PavithSingh
 
Adbms
AdbmsAdbms
Adbms
jass12345
 
Database Basics
Database BasicsDatabase Basics
Database Basics
Abdel Moneim Emad
 
Advance Sqlite3
Advance Sqlite3Advance Sqlite3
Advance Sqlite3Raghu nath
 
Database Overview
Database OverviewDatabase Overview
Database Overview
Livares Technologies Pvt Ltd
 
Anchor data type,cursor data type,array data type
Anchor data type,cursor data type,array data typeAnchor data type,cursor data type,array data type
Anchor data type,cursor data type,array data typedhruv patel
 
Presentation1
Presentation1Presentation1
Presentation1Jay Patel
 
ORACLE PL SQL
ORACLE PL SQLORACLE PL SQL
ORACLE PL SQL
Srinath Maharana
 
Relational Theory for Budding Einsteins -- LonestarPHP 2016
Relational Theory for Budding Einsteins -- LonestarPHP 2016Relational Theory for Budding Einsteins -- LonestarPHP 2016
Relational Theory for Budding Einsteins -- LonestarPHP 2016
Dave Stokes
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management System
Mian Abdul Raheem
 
153680 sqlinterview
153680  sqlinterview153680  sqlinterview
153680 sqlinterview
zdsgsgdf
 
Sql Interview Questions
Sql Interview QuestionsSql Interview Questions
Sql Interview Questionsarjundwh
 

Similar to Ms sql server tips 1 0 (20)

T-SQL Overview
T-SQL OverviewT-SQL Overview
T-SQL Overview
 
Database Performance
Database PerformanceDatabase Performance
Database Performance
 
Basic SQL and History
 Basic SQL and History Basic SQL and History
Basic SQL and History
 
Relational database management system
Relational database management systemRelational database management system
Relational database management system
 
Dbms interview questions
Dbms interview questionsDbms interview questions
Dbms interview questions
 
MSSQL_Book.pdf
MSSQL_Book.pdfMSSQL_Book.pdf
MSSQL_Book.pdf
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Adbms
AdbmsAdbms
Adbms
 
Database Basics
Database BasicsDatabase Basics
Database Basics
 
Advance Sqlite3
Advance Sqlite3Advance Sqlite3
Advance Sqlite3
 
Database Overview
Database OverviewDatabase Overview
Database Overview
 
Anchor data type,cursor data type,array data type
Anchor data type,cursor data type,array data typeAnchor data type,cursor data type,array data type
Anchor data type,cursor data type,array data type
 
Presentation1
Presentation1Presentation1
Presentation1
 
ORACLE PL SQL
ORACLE PL SQLORACLE PL SQL
ORACLE PL SQL
 
Relational Theory for Budding Einsteins -- LonestarPHP 2016
Relational Theory for Budding Einsteins -- LonestarPHP 2016Relational Theory for Budding Einsteins -- LonestarPHP 2016
Relational Theory for Budding Einsteins -- LonestarPHP 2016
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management System
 
Sql
SqlSql
Sql
 
153680 sqlinterview
153680  sqlinterview153680  sqlinterview
153680 sqlinterview
 
Sql Interview Questions
Sql Interview QuestionsSql Interview Questions
Sql Interview Questions
 

Recently uploaded

Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 

Recently uploaded (20)

Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 

Ms sql server tips 1 0

  • 1. MS SQL SERVER TIPS By Arman Aug-18
  • 2. • Relationship Database Management System • Database Design • Indexes • Useful Queries
  • 3. RELATIONSHIP DATABASE MANAGEMENT SYSTEM  Collection of information organized in tables  Tables are also “Relations”  Tables are constructed and associated to each other through shared fields.  Fields are also “Columns” or “Attributes”  A set of attributes comprises a record  Records are also “Rows” or “Tuples”  Tables are related through common fields designated as primary key and foreign keys.  Allow us to find, update, and delete data quickly, and help to ensure accuracy
  • 4. RELATIONSHIP DATABASE MANAGEMENT SYSTEM  Primary Key :  Primary key fields must be unique and cannot contain a null value  Each table should have a primary key field[s].  Composite Key: Using more than one field as a primary key.  Foreign Key :  Fields in a table that refer to the primary key in another table.  The data in this field must exactly match data contained in the primary key
  • 5. DATABASE DESIGN RELATIONSHIP TYPES  One-to-one relationships  One-to-many relationships  Many-to-many relationships  Mandatory or not?
  • 6. DATABASE DESIGN NORMALIZATION  First normal form (1NF)  Second normal form (2NF)  Third normal form (3NF)
  • 7. DATABASE DESIGN NORMALIZATION 1NF  First normal form (1NF) I. It should only have single(atomic) valued attributes/columns. II. Values stored in a column should be of the same domain III. All the columns in a table should have unique names. IV. And the order in which data is stored, does not matter.
  • 8. DATABASE DESIGN NORMALIZATION 2NF  Second normal form (2NF) I. It should be in the First Normal form. II. And, it should not have Partial Dependency.
  • 9. DATABASE DESIGN NORMALIZATION 3NF  Third normal form (3NF) I. It is in the Second Normal form. II. And, it doesn't have Transitive Dependency.
  • 10. DATABASE DESIGN NORMALIZATION BCNF  Boyce-Codd Normal Form (BCNF) I. It should be in the Third Normal Form. II. And, for any dependency A → B, A should be a super key.
  • 11. DATABASE DESIGN NORMALIZATION 4NF  Fourth Normal Form (4NF)
  • 12. INDEXES TYPES  Regulations  1 Clustered Index per Table  249 Non Clustered (2005)  999 Non Clustered (2008+)  16 Columns or 900 Bytes  Clustered Index  Nonclustered Index  Unique index  Filtered index  Full-Text  XML
  • 13. CLUSTERED TABLE VS HEAP TABLE Clustered Indexed Table Heap Table
  • 14. CLUSTERED INDEX  Clustered Index – sort order of the data within the table on the hard drive and in memory.  One per table  Desired Qualities  Narrow Data Type  Unique  Static  Increasing
  • 15. NONCLUSTERED INDEX  Cover Common Queries  Link to Clustered Indexes through Key  Bookmark (Key/RID) Lookup
  • 16. FRAGMENTATION  Identifying Fragmentation  2005  DBCC SHOWCONTIG  Above 2005  sys.dm_db_index_physical_stats Required Actions avg_fragmentation_in_percent value Corrective statement > 5% and < = 30% ALTER INDEX REORGANIZE > 30% ALTER INDEX REBUILD WITH (ONLINE = ON)
  • 17. USEFUL QUERIES  Check index fragmentation using Transact-SQL  2012  2005  DBCC SHOWCONTIG WITH TABLERESULTS, ALL_INDEXES;  Currently running process SELECT sqltext.TEXT, req.session_id, req.status,req.command, req.cpu_time, req.total_elapsed_time ,blocking_session_id ,wait_time ,wait_type ,logical_reads FROM sys.dm_exec_requests req CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext SELECT a.index_id, name, avg_fragmentation_in_percent FROM sys.dm_db_index_physical_stats (DB_ID(N'UniversoDB2018'), OBJECT_ID(N'dbo.tblindividual'), NULL, NULL, NULL) AS a JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id;
  • 18. USEFUL QUERIES  Check index fragmentation using Transact-SQL SELECT TOP 10 SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1, ((CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(qt.TEXT) ELSE qs.statement_end_offset END - qs.statement_start_offset)/2)+1), qs.execution_count, qs.total_logical_reads, qs.last_logical_reads, qs.total_logical_writes, qs.last_logical_writes, qs.total_worker_time, qs.last_worker_time, qs.total_elapsed_time/1000000 total_elapsed_time_in_S, qs.last_elapsed_time/1000000 last_elapsed_time_in_S, qs.last_execution_time, qp.query_plan FROM sys.dm_exec_query_stats qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp ORDER BY qs.total_logical_reads DESC -- logical reads -- ORDER BY qs.total_logical_writes DESC -- logical writes -- ORDER BY qs.total_worker_time DESC -- CPU time
  • 19. READ TYPES  Index Scan  Table Scan (Heap)  Index Seek  Key Lookup  RID Lookup (heap)
  • 20. RULES FOR EXECUTION PLAN COMPILATION  Build up most resource efficient plan  AS little page reads as possible  Fastest Operation possible  Choosing Indexes:  Prefer read range over scan  Prefer small indexes over large

Editor's Notes

  1. Student and Branch Example Insertion Anomaly Updation Anomaly Deletion Anomaly
  2. Student and Branch Example Insertion Anomaly Updation Anomaly Deletion Anomaly
  3. Student and Branch Example Insertion Anomaly Updation Anomaly Deletion Anomaly
  4. Student and Branch Example Insertion Anomaly Updation Anomaly Deletion Anomaly
  5. In the table above, student_id, subject form primary key, which means subject column is a prime attribute. But, there is one more dependency, professor → subject. And while subject is a prime attribute, professor is a non-prime attribute, which is not allowed by BCNF.
  6. For a dependency A → B, if for a single value of A, multiple value of B exists, then the table may have multi-valued dependency. Also, a table should have at-least 3 columns for it to have a multi-valued dependency. And, for a relation R(A,B,C), if there is a multi-valued dependency between, A and B, then B and C should be independent of each other.
  7. HEAP Data is not stored in any particular order Specific data can not be retrieved quickly, unless there are also non-clustered indexes Data pages are not linked, so sequential access needs to refer back to the index allocation map (IAM) pages Since there is no clustered index, additional time is not needed to maintain the index Since there is no clustered index, there is not the need for additional space to store the clustered index tree These tables have a index_id value of 0 in the sys.indexes catalog view Clustered Indexed Table Data is stored in order based on the clustered index key Data can be retrieved quickly based on the clustered index key, if the query uses the indexed columns Data pages are linked for faster sequential access Additional time is needed to maintain clustered index based on INSERTS, UPDATES and DELETES Additional space is needed to store clustered index tree These tables have a index_id value of 1 in the sys.indexes catalog view
  8. Clustered Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be stored in only one order. The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.
  9. Nonclustered Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value. The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key. You can add nonkey columns to the leaf level of the nonclustered index to by-pass existing index key limits, and execute fully covered, indexed, queries.