This document discusses various techniques for optimizing SQL queries in SQL Server, including:
1) Using parameterized queries instead of ad-hoc queries to avoid compilation overhead and improve plan caching.
2) Ensuring optimal ordering of predicates in the WHERE clause and creating appropriate indexes to enable index seeks.
3) Understanding how the query optimizer works by estimating cardinality based on statistics and choosing low-cost execution plans.
4) Avoiding parameter sniffing issues and non-deterministic expressions that prevent accurate cardinality estimation.
5) Using features like the Database Tuning Advisor and query profiling tools to identify optimization opportunities.
This document discusses various data types and SQL commands used in Oracle databases. It covers:
- Common data types like CHAR, VARCHAR2, NUMBER, DATE, LONG, RAW, BLOB, CLOB and how they store data.
- SQL commands for data definition (CREATE, ALTER, DROP), data manipulation (SELECT, INSERT, UPDATE, DELETE), and integrity constraints (PRIMARY KEY, FOREIGN KEY).
- Functions for calculations, string operations and data retrieval from tables.
The document provides an overview of database concepts and features in Oracle, including fundamentals like data grouping and relationships, as well as operations on tables like insert, update, delete. It also covers queries with filters, joins, and aggregations, as well as other objects like views, sequences, indexes, triggers, and stored procedures. The document is intended as training material for the Oracle database.
This document provides information about an upcoming SQL Saturday Night event on March 30, 2013 that will focus on using T-SQL. The presentation will be recorded so that those unable to attend can view it later. Attendees are asked to change their virtual cards to a specific color if they are unable to hear the presenter. The presentation will be free and begin in 1 minute.
Synapseindia dot net development chapter 8 asp dot net
This chapter discusses how to connect to and manipulate SQL Server databases from ASP.NET applications. It covers using classes in the System.Data.SqlClient namespace to connect to databases and execute SQL commands. Methods like ExecuteReader, ExecuteNonQuery and SqlDataReader are used to retrieve and modify data. The chapter also describes how to create, update and delete databases and tables by executing SQL statements with ASP.NET code.
Oracle foreign key missing index - a single index can boost performance
In Oracle databases, a foreign key does not require that the column being restricted should have an index. Update and Delete operations on referenced tables may have a heavy impact in performance, overloading the server. A single index can reduce the cost of these DML operations.
This document provides an overview and introduction to Oracle SQL basics. It covers topics such as installing Oracle software like the database, Java SDK, and SQL Developer tool. It then discusses database concepts like what a database and table are. It also covers database fundamentals including SQL queries, functions, joins, constraints, views and other database objects. The document provides examples and explanations of SQL statements and database components.
This document discusses SQL skills and how queries can negatively impact server performance if not written efficiently. It covers topics like query plans, execution contexts, using parameters, indexing, handling large datasets, and external influences on SQL performance. Specific "bad" SQL examples are also provided and analyzed. The presenter aims to help developers optimize their SQL and prevent poorly written queries from bringing servers to their knees.
This document discusses transactions in SQL Server. It introduces transactions and their relevance in ensuring data integrity when multiple tables need to be updated together. Transactions group a set of database operations so that if any operation fails, all operations are rolled back. The document demonstrates creating a transaction using START TRANSACTION, COMMIT TRANSACTION, and ROLLBACK TRANSACTION statements. It also shows handling transactions within try/catch blocks so that failures cause a rollback. Transactions ensure atomicity and integrity by committing all operations together as a single unit, or rolling them all back if any fail.
This document discusses programming SQL Server data mining with Analysis Management Objects (AMO) and stored procedures. It describes how to create mining structures and models using AMO, including defining columns, updating objects, and processing models. It also explains how to create, execute, and debug stored procedures for adding business logic, including registering assemblies, setting permissions, and attaching to processes for debugging. The goal is to provide an overview of programming options for data mining with SQL Server.
The document discusses new improvements to the parser and optimizer in MySQL 5.7. Key points include:
1) The parser and optimizer were refactored for improved maintainability and stability. Parsing was separated from optimization and execution.
2) The cost model was improved with better record estimation for joins, configurable cost constants, and additional explain output.
3) A new query rewrite plugin allows rewriting queries without changing application code.
This document discusses stored procedures in SQL Server. It begins by explaining that stored procedures allow encapsulation of repetitive tasks and are stored in the database data dictionary. It then shows how stored procedures reduce network traffic and client-server communication compared to individual SQL statements. The document provides examples of how to create a stored procedure using CREATE PROCEDURE and how to call it using EXEC. It notes advantages like precompiled execution, reduced traffic, code reuse, and security control. It also demonstrates using parameters, loops, conditions and variables inside stored procedures.
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
This document discusses how to speed up queries in MySQL through the proper use of indexes, histograms, and other techniques. It begins by explaining that the MySQL optimizer tries to determine the most efficient way to execute queries by considering different query plans. The optimizer relies on statistics about column distributions to estimate query costs. The document then discusses using EXPLAIN to view and analyze query plans, and how indexes can improve query performance by allowing faster data retrieval through secondary indexes and other index types. Proper index selection and column data types are important to allow the optimizer to use indexes efficiently.
This presentation focuses on optimization of queries in MySQL from developer’s perspective. Developers should care about the performance of the application, which includes optimizing SQL queries. It shows the execution plan in MySQL and explain its different formats - tabular, TREE and JSON/visual explain plans. Optimizer features like optimizer hints and histograms as well as newer features like HASH joins, TREE explain plan and EXPLAIN ANALYZE from latest releases are covered. Some real examples of slow queries are included and their optimization explained.
This document provides an overview of Android application development training on accessing and manipulating data using SQLite databases on Android. It covers topics like what SQLite is, creating and connecting to databases, setting database properties, creating tables, inserting, updating, and deleting records from the databases using ContentValues and SQLiteDatabase methods. Code examples are provided for each topic.
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
This presentation focuses on two of the new features in MySQL 8.0.18: hash joins and EXPLAIN ANALYZE. It covers how these features work, both on the surface and on the inside, and how you can use them to improve your queries and make them go faster.
Both features are the result of major refactoring of how the MySQL executor works. In addition to explaining and demonstrating the features themselves, the presentation looks at how the investment in a new iterator based executor prepares MySQL for a future with faster queries, greater plan flexibility and even more SQL features.
This document discusses how the author's time is extraordinarily valuable and feels it is being wasted. The author concludes that whoever is wasting their time is now "dead to me" and they should refer to the previous bullet points listed.
Estudio benchmark publicidad digital mayor rendimiento por media mind
MediaMind, proveedor líder mundial de soluciones integradas de publicidad online, ha presentado su estudio comparativo mundial (benchmark) de publicidad online.
This document is the United Nations E-Government Survey 2012. It discusses how e-government can advance sustainable development and be more responsive, citizen-centric, and socially inclusive. The survey found that while e-government has helped promote transparency and accountability, more needs to be done to reduce digital divides and increase access for vulnerable groups. Cooperation between governments, funding, and innovations like mobile services will help e-government better serve people.
The document discusses SQL query performance analysis. It covers topics like the query optimizer, execution plans, statistics analysis, and different types of queries and scanning. The query optimizer is cost-based and determines the most efficient execution plan using cardinality estimates and cost models. Addhoc queries are non-parameterized queries that SQL Server treats differently than prepared queries. Execution plans show the steps and methods used to retrieve and process data. Statistics help the optimizer generate accurate cardinality estimates to pick high-performing plans.
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...Dave Stokes
Slow query? Add an index or two! But things are suddenly even slower! Indexes are great tools to speed data lookup but have overhead issues. Histograms don’t have that overhead but may not be suited. And how you lock rows also effects performance. So what do you do to speed up queries smartly?
Confoo 2021 - MySQL Indexes & HistogramsDave Stokes
Confoo 2021 presentation on MySQL Indexes, Histograms, and other ways to speed up your queries. This slide deck has slides that may not have been included in the presentation that were omitted due to time constraints
This document discusses various strategies for optimizing MySQL queries and indexes, including:
- Using the slow query log and EXPLAIN statement to analyze slow queries.
- Avoiding correlated subqueries and issues in older MySQL versions.
- Choosing indexes based on selectivity and covering common queries.
- Identifying and addressing full table scans and duplicate indexes.
- Understanding the different join types and selecting optimal indexes.
This document discusses various data types and SQL commands used in Oracle databases. It covers:
- Common data types like CHAR, VARCHAR2, NUMBER, DATE, LONG, RAW, BLOB, CLOB and how they store data.
- SQL commands for data definition (CREATE, ALTER, DROP), data manipulation (SELECT, INSERT, UPDATE, DELETE), and integrity constraints (PRIMARY KEY, FOREIGN KEY).
- Functions for calculations, string operations and data retrieval from tables.
The document provides an overview of database concepts and features in Oracle, including fundamentals like data grouping and relationships, as well as operations on tables like insert, update, delete. It also covers queries with filters, joins, and aggregations, as well as other objects like views, sequences, indexes, triggers, and stored procedures. The document is intended as training material for the Oracle database.
This document provides information about an upcoming SQL Saturday Night event on March 30, 2013 that will focus on using T-SQL. The presentation will be recorded so that those unable to attend can view it later. Attendees are asked to change their virtual cards to a specific color if they are unable to hear the presenter. The presentation will be free and begin in 1 minute.
This chapter discusses how to connect to and manipulate SQL Server databases from ASP.NET applications. It covers using classes in the System.Data.SqlClient namespace to connect to databases and execute SQL commands. Methods like ExecuteReader, ExecuteNonQuery and SqlDataReader are used to retrieve and modify data. The chapter also describes how to create, update and delete databases and tables by executing SQL statements with ASP.NET code.
Oracle foreign key missing index - a single index can boost performanceCarlos Oliveira
In Oracle databases, a foreign key does not require that the column being restricted should have an index. Update and Delete operations on referenced tables may have a heavy impact in performance, overloading the server. A single index can reduce the cost of these DML operations.
This document provides an overview and introduction to Oracle SQL basics. It covers topics such as installing Oracle software like the database, Java SDK, and SQL Developer tool. It then discusses database concepts like what a database and table are. It also covers database fundamentals including SQL queries, functions, joins, constraints, views and other database objects. The document provides examples and explanations of SQL statements and database components.
This document discusses SQL skills and how queries can negatively impact server performance if not written efficiently. It covers topics like query plans, execution contexts, using parameters, indexing, handling large datasets, and external influences on SQL performance. Specific "bad" SQL examples are also provided and analyzed. The presenter aims to help developers optimize their SQL and prevent poorly written queries from bringing servers to their knees.
This document discusses transactions in SQL Server. It introduces transactions and their relevance in ensuring data integrity when multiple tables need to be updated together. Transactions group a set of database operations so that if any operation fails, all operations are rolled back. The document demonstrates creating a transaction using START TRANSACTION, COMMIT TRANSACTION, and ROLLBACK TRANSACTION statements. It also shows handling transactions within try/catch blocks so that failures cause a rollback. Transactions ensure atomicity and integrity by committing all operations together as a single unit, or rolling them all back if any fail.
This document discusses programming SQL Server data mining with Analysis Management Objects (AMO) and stored procedures. It describes how to create mining structures and models using AMO, including defining columns, updating objects, and processing models. It also explains how to create, execute, and debug stored procedures for adding business logic, including registering assemblies, setting permissions, and attaching to processes for debugging. The goal is to provide an overview of programming options for data mining with SQL Server.
The document discusses new improvements to the parser and optimizer in MySQL 5.7. Key points include:
1) The parser and optimizer were refactored for improved maintainability and stability. Parsing was separated from optimization and execution.
2) The cost model was improved with better record estimation for joins, configurable cost constants, and additional explain output.
3) A new query rewrite plugin allows rewriting queries without changing application code.
This document discusses stored procedures in SQL Server. It begins by explaining that stored procedures allow encapsulation of repetitive tasks and are stored in the database data dictionary. It then shows how stored procedures reduce network traffic and client-server communication compared to individual SQL statements. The document provides examples of how to create a stored procedure using CREATE PROCEDURE and how to call it using EXEC. It notes advantages like precompiled execution, reduced traffic, code reuse, and security control. It also demonstrates using parameters, loops, conditions and variables inside stored procedures.
Dutch PHP Conference 2021 - MySQL Indexes and HistogramsDave Stokes
This document discusses how to speed up queries in MySQL through the proper use of indexes, histograms, and other techniques. It begins by explaining that the MySQL optimizer tries to determine the most efficient way to execute queries by considering different query plans. The optimizer relies on statistics about column distributions to estimate query costs. The document then discusses using EXPLAIN to view and analyze query plans, and how indexes can improve query performance by allowing faster data retrieval through secondary indexes and other index types. Proper index selection and column data types are important to allow the optimizer to use indexes efficiently.
This presentation focuses on optimization of queries in MySQL from developer’s perspective. Developers should care about the performance of the application, which includes optimizing SQL queries. It shows the execution plan in MySQL and explain its different formats - tabular, TREE and JSON/visual explain plans. Optimizer features like optimizer hints and histograms as well as newer features like HASH joins, TREE explain plan and EXPLAIN ANALYZE from latest releases are covered. Some real examples of slow queries are included and their optimization explained.
This document provides an overview of Android application development training on accessing and manipulating data using SQLite databases on Android. It covers topics like what SQLite is, creating and connecting to databases, setting database properties, creating tables, inserting, updating, and deleting records from the databases using ContentValues and SQLiteDatabase methods. Code examples are provided for each topic.
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZENorvald Ryeng
This presentation focuses on two of the new features in MySQL 8.0.18: hash joins and EXPLAIN ANALYZE. It covers how these features work, both on the surface and on the inside, and how you can use them to improve your queries and make them go faster.
Both features are the result of major refactoring of how the MySQL executor works. In addition to explaining and demonstrating the features themselves, the presentation looks at how the investment in a new iterator based executor prepares MySQL for a future with faster queries, greater plan flexibility and even more SQL features.
This document discusses how the author's time is extraordinarily valuable and feels it is being wasted. The author concludes that whoever is wasting their time is now "dead to me" and they should refer to the previous bullet points listed.
Estudio benchmark publicidad digital mayor rendimiento por media mindComercio Electronico
MediaMind, proveedor líder mundial de soluciones integradas de publicidad online, ha presentado su estudio comparativo mundial (benchmark) de publicidad online.
This document is the United Nations E-Government Survey 2012. It discusses how e-government can advance sustainable development and be more responsive, citizen-centric, and socially inclusive. The survey found that while e-government has helped promote transparency and accountability, more needs to be done to reduce digital divides and increase access for vulnerable groups. Cooperation between governments, funding, and innovations like mobile services will help e-government better serve people.
The document discusses SQL query performance analysis. It covers topics like the query optimizer, execution plans, statistics analysis, and different types of queries and scanning. The query optimizer is cost-based and determines the most efficient execution plan using cardinality estimates and cost models. Addhoc queries are non-parameterized queries that SQL Server treats differently than prepared queries. Execution plans show the steps and methods used to retrieve and process data. Statistics help the optimizer generate accurate cardinality estimates to pick high-performing plans.
This document summarizes an analytics bootcamp hosted by Google from June 25-28, 2012 in Bogota. It provides an agenda for the 4 day course, covering topics like filters, e-commerce, metrics, regular expressions, advanced segments, and analytics intelligence. The final day includes a question and answer session and exam.
SQL Server stores data in pages that are grouped into extents for management. By default, rows are returned in the order they were inserted. A nonclustered index will use less space than a clustered index since it only stores the key columns rather than the entire row. The ORDER BY clause is used to sort query results. Various types of joins can be used to combine data from multiple tables.
This document provides an introduction and overview of Microsoft SQL Server and its main components: the Database Engine, SQL Server Integration Services (SSIS), SQL Server Analysis Services (SSAS), and SQL Server Reporting Services (SSRS). It also briefly discusses the differences between SQL Server and MySQL Server and their respective client tools. The remainder of the document focuses on SQL syntax, explaining clauses such as FROM, WHERE, GROUP BY, HAVING, and ORDER BY and functions like COUNT, AVG, MIN, MAX and SUM. It emphasizes that the order of predicates in the WHERE clause can impact performance.
Reporte Cámara Colombiana de Comercio Electrónico Retail, Banking y TravelComercio Electronico
El documento presenta datos sobre el uso de internet en Colombia en agosto de 2013 en las categorías de retail, banca online y travel. En retail, los sitios más visitados fueron MercadoLibre, Amazon y Apple. El crecimiento en los últimos 6 meses fue de 7.082 mil visitantes únicos. En banca online, los más visitados fueron Grupo Banco Colombia, Davivienda y Banco de Bogotá, con 2.547 mil visitantes únicos. Y en travel, Despegar-Decolar, Avianca y LanChile encabezaron la lista, con un total de 2.974
This session talks all about SQL Server Query Parameterization. Covers various topics like Query Tuning, Adhoc Query, Execution Plan, Query Optimizer, Parameter Sniffing, Indexes etc. etc.
The document discusses SQL query performance analysis. It covers topics like the query optimizer, execution plans, statistics analysis, and different types of queries and indexes. The query optimizer uses cost-based optimization to determine the most efficient execution plan. Statistics help it estimate cardinality and choose good plans, so keeping statistics up to date is important. The goal is to have queries use indexes through seeks instead of scans whenever possible to improve performance.
This document provides guidelines for tuning SQL statements to improve response time. It discusses reviewing table and column statistics, execution plans, and restructuring SQL statements and indexes. Specific techniques covered include gathering statistics, reviewing access paths like index scans and joins, and using SQL profiles to lock optimized plans.
The document discusses various techniques for optimizing database performance in Oracle, including:
- Using the cost-based optimizer (CBO) to choose the most efficient execution plan based on statistics and hints.
- Creating appropriate indexes on columns used in predicates and queries to reduce I/O and sorting.
- Applying constraints and coding practices like limiting returned rows to improve query performance.
- Tuning SQL statements through techniques like predicate selectivity, removing unnecessary objects, and leveraging indexes.
This document discusses SQL skills and how queries can negatively impact server performance if not written efficiently. It covers topics like query plans, execution contexts, using parameters, indexing, handling large datasets, and external influences on SQL performance. Specific "bad" SQL examples are also provided and explained. The presenter's goal is to help developers optimize their SQL and prevent poorly written queries from bringing servers to their knees.
Brad McGehee's presentation on "How to Interpret Query Execution Plans in SQL Server 2005/2008".
Presented to the San Francisco SQL Server User Group on March 11, 2009.
This document provides an overview of SQL tuning and optimization techniques. It discusses various indexing options in Oracle like bitmap indexes and reverse key indexes. It also covers execution plan analysis using tools like EXPLAIN PLAN and tuning techniques like hints. The goal of SQL tuning is to identify resource-intensive queries and optimize them using better indexing, rewriting queries, and other optimization strategies.
The document discusses various techniques for optimizing query performance in MySQL, including using indexes appropriately, avoiding full table scans, and tools like EXPLAIN, Performance Schema, and pt-query-digest for analyzing queries and identifying optimization opportunities. It provides recommendations for index usage, covering indexes, sorting and joins, and analyzing slow queries.
The document discusses indexes in SQL Server 2005, including what they are, why they are needed to improve query performance, and the different types (clustered and nonclustered). It also covers how to create indexes using SQL statements, and how to drop indexes. Examples are provided on creating clustered and nonclustered indexes and dropping indexes.
The document discusses indexes in SQL Server 2005, including what they are, why they are needed to improve query performance, and the different types (clustered and nonclustered). It also covers how to create indexes using SQL statements, examples of creating indexes on tables, and activities for learners to practice creating, dropping, and rebuilding indexes.
The document discusses Oracle system catalogs which contain metadata about database objects like tables and indexes. System catalogs allow accessing information through views with prefixes like USER, ALL, and DBA. Examples show how to query system catalog views to get information on tables, columns, indexes and views. Query optimization and evaluation are also covered, explaining how queries are parsed, an execution plan is generated, and the least cost plan is chosen.
U-SQL combines SQL and C# to allow for querying and analyzing large amounts of structured and unstructured data stored in Azure Data Lake Store. U-SQL queries can access data across various Azure data services and provide analytics capabilities like window functions and ranking functions. The language also allows for extensibility through user-defined functions, aggregates, and operators written in C#. U-SQL queries are compiled and executed on Azure Data Lake Analytics, which provides a scalable analytics service based on Apache YARN.
This presentation is an INTRODUCTION to intermediate MySQL query optimization for the Audience of PHP World 2017. It covers some of the more intricate features in a cursory overview.
This document provides an overview of Module 5: Optimize query performance in Azure SQL. The module contains 3 lessons that cover analyzing query plans, evaluating potential improvements, and reviewing table and index design. Lesson 1 explores generating and comparing execution plans, understanding how plans are generated, and the benefits of the Query Store. Lesson 2 examines database normalization, data types, index types, and denormalization. Lesson 3 describes wait statistics, tuning indexes, and using query hints. The lessons aim to help administrators optimize query performance in Azure SQL.
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...Dave Stokes
Speeding up queries on a MySQL server with indexes and histograms is not a mysterious art but simple engineering. This presentation is an indepth introduction that was presented on March 30th to the Quest Insynch and Open Source 101 conferences
Part 3 of the SQL Tuning workshop examines the different aspects of an execution plan, from cardinality estimates to parallel execution and explains what information you should be gleaming from the plan and how it affects the execution. It offers insight into what caused the Optimizer to make the decision it did as well as a set of corrective measures that can be used to improve each aspect of the plan.
This document contains questions and answers related to database testing. It discusses testing data validity, integrity, performance, procedures, triggers and functions. It also describes primary keys, foreign keys, NULL values, differences between Oracle, SQL and SQL Server. Database indexing, isolation levels, and creating indexes on all columns are also covered.
1. Script backup
2. Recovery models
3. Backup type(Full,differential, transactional)
4. Transactional logs
5. Point in time restore
6. Transactional log shipping
7. Recovery of deleted data without any backup
This document discusses database indexing. It provides information on the benefits of indexes, how to create indexes, common misconceptions about indexing, and rules for determining when and how to create indexes. Key points include that indexes improve performance of queries by enabling faster data retrieval and synchronization; indexes should be created on columns frequently filtered in WHERE and JOIN clauses; and the order of columns in an index matters for its effectiveness.
This document discusses SQL query performance analysis through indexing. It begins by defining an index as a way to organize data to make searching, sorting, and grouping faster. Indexes are needed for clauses like WHERE, ON, HAVING (searching), ORDER BY (sorting), and GROUP BY (grouping). The document then discusses different types of scans like table scans, index scans, and index seeks and explains their time complexities. It defines clustered and non-clustered indexes and how they are structured. Key terms in execution plans like predicate, object, and seek predicate are also explained. Finally, the concept of covering indexes to optimize queries is introduced.
The document discusses how data is stored and organized in Microsoft SQL Server. It explains that rows in a table will always appear in the order they were inserted by default. It also describes how data is stored across 8KB pages that are grouped into extents for storage management, and how rows cannot span multiple pages. The document also provides an overview of different types of JOINs between tables like INNER, LEFT OUTER, RIGHT OUTER, and FULL OUTER JOINs.
Microsoft SQL Server is a relational database management system that stores data in tabular format of columns and rows. It has four major components: the Database Engine for storing and retrieving data efficiently; Integration Services (SSIS) for extracting, transforming, and loading data from various sources into destinations; Analysis Services (SSAS) for creating multi-dimensional data structures and performing analysis and data mining; and Reporting Services (SSRS) for generating reports from different tables in various formats like PDF and maps. The SELECT statement is used to retrieve data and has clauses like FROM, WHERE, GROUP BY, HAVING, and ORDER BY. Proper use of filters and indexes in the WHERE clause is important for query performance.
The document discusses database normalization through third normal form. It describes eliminating repeating groups and redundant data by creating separate tables for each set of related data identified by a primary key. These tables should have no non-key attributes that are functionally dependent on other non-prime attributes. The document also covers one-to-one, one-to-many, and many-to-many relationships and discusses whether an application is better suited for online transaction processing or online analytical processing.
The query optimizer in SQL Server is cost-based and determines the optimal query plan by estimating the cost of different query plans based on cardinality estimates derived from statistics, the cost model for different query operations, and the total estimated execution time. Statistics are important for the query optimizer to generate high-quality query plans, and the optimizer monitors when statistics may be out of date and automatically updates statistics.
This document discusses SQL query performance analysis and optimization. It covers key topics like indexes, different types of scans (table scan, index scan, index seek), clustered vs non-clustered indexes, covering indexes to optimize queries, and using statistics to help the query optimizer generate efficient execution plans. The goal is to help analyze and tune queries to achieve fast index seeks and optimize performance.
This document discusses SQL query performance analysis. Addhoc queries are non-parameterized queries that SQL Server treats as different statements even if they only differ by parameters. Prepared queries avoid this issue by using parameters. The query optimizer determines the most efficient execution plan based on criteria like cardinality and cost models. Execution plans and contexts are cached to improve performance. Examples are provided showing how join can outperform subquery, order in the WHERE clause matters, and how same outputs can have different execution plans.
The document discusses several key concepts in SQL Server including:
1. Data in tables is stored in pages by default in the order records are inserted (natural order).
2. Pages are the basic unit of storage which are grouped into extents of 8 contiguous pages.
3. The ORDER BY clause allows ordering the results of a SELECT statement in ascending or descending order.
This document discusses four topics related to database queries: ad hoc queries, execution plans, statistics analysis, and deadlock analysis. Ad hoc queries are queries that are not pre-defined while execution plans show how the database will execute a particular query. Statistics analysis examines data distribution and deadlock analysis identifies locking issues between concurrent queries.
2. INDEX
Adhoc Query
Predicates Order
Execution Plan
Query Optimizer
Parameter Sniffing
Indexes
Statistics
Database Engine Tuning Advisor
3. Adhoc Query
Any non-Parameterized queries are called addhoc
queries. For example :
SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 100
In sql server if we execute a sql query it goes
through two steps just like any other
programming languages:
Compilation
Execution
4. Properties Of Addhoc
Queries
Case sensitive
Space sensitive
Parameter sensitive
Sql server treats two same sql queries of different
parameters as a two different sql statements. For
example:
SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 1
SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 2
5. Effect Of Faulty C# Code
Sql server has took extra n * (Compilation time) ms to
display records
Extra time to insert records in cached plans.
Sql server has to frequently fire a job to delete the
cached plan since it will reach the max limit very soon.
It will not only decrease the performance of this sql
query but all sql queries of other application since this
faulty code will force to delete cached query plans of
other sql statements.
6. Predicates Order
Does order of predicates in WHERE clause
matters?
WHERE vcLanguage = 'English' AND ntAge = 12
WHERE ntAge = 12 AND vcLanguage = 'English'
9. Query Optimizer
The query optimizer in SQL Server is cost-based. It includes:
Cost for using different resources (CPU and IO)
Total execution time
It determines the cost by using:
Cardinality: The total number of rows processed at each
level of a query plan with the help of histograms , predicates
and constraint
Cost model of the algorithm: To perform various operations
like sorting, searching, comparisons etc.
10. Parameter Sniffing
Sql server generates execution paln according
to the first parameter
This execution plan may bad for other
parameters.
Solution:
Create multiples stored procedures.
Use optimizer for query hints.
11. What Is An Index ?
Index is a way to organize data to make
searching, sorting and grouping fasters
we need indexing when :
WHERE, ON, HAVING clause (Searching)
ORDER BY clause (Sorting)
GROUP BY clause (Grouping) etc.
12. Table Scan
SELECT * FROM Student WHERE RollNo = 111
Time complexity of table scan is : O(n)
RollNo Name Country Age
101 Greg UK 23
102 Sachin India 21
103 Akaram Pakistan 22
107 Miyabi China 18
108 Marry Russia 27
109 Scott USA 31
110 Benazir Banglades 17
111 Miyabi Japan 24
112 Rahul India 27
113 Nicolus France 19
13. Types Of Index
Table without any index is called Heap
There are two type of index:
Clustered index
Non-Clustered index
14. Clustered Index
When we create a clustered index on any
table physical organization of table is changed.
Now data of table is stored as a balanced
tree(B tree).
CREATE UNIQUE [CLUSTERED] INDEX <Name>
ON <ObjectName>(
<ColumnName> [ASC | DESC ] [ ,...n ]
)
16. Types Of Scanning
Table scan: It is very slow can and it is used only if table
has not any clustered index.
Index scan: It is also slow scan. It is used when table has
clustered index and either in WHERE clause non-key
columns are present or query has not been covered (will
discuss later) or both.
Index Seek: It is very fast. Our goal is to achieve this.
17. Clustered Index
If we create table with primary key, sql server
automatically creates clustered index on that
table
A table can have only one clustered index .
Physical order of rows of table is same as
logical order of key columns of clustered
index.
18. Terms Of Execution Plan
Predicate: It is condition in WHERE clause which is
either non-key column or column which has not been
covered.
Object: It is name of source from where it getting the
data. It can be name of table, Clustered index or non-
clustered index
Output list: It is name of the columns which is getting
from object.
Seek Predicate: It is condition in WHERE clause which is
either key column or fully covered.
19. Non-Clustered Index
It is logical organization of data of table. A non-clustered
index can be of two types.
Heap
Based on clustered index.
If table has clustered index then leaf node of non-
clustered index keeps the key columns of clustered
index.
If the table has not any clustered index then leaf node of
non-clustered index keeps RID which unique of each row
of table.
22. Covering Of Queries
We can specify maximum 16 column names.
Sum of size of the columns cannot be more than 900 bytes.
All columns must belong to same table.
Data type of columns cannot be
ntext, text, varchar (max), nvarchar (max), varbinary (max),
xml, or image
It cannot be non-deterministic computed column.
23. Statistics Analysis
The query optimizer uses statistics to create query plans
that improve query performance
A correct statistics will lead to high-quality query plan.
The query optimizer determines when statistics might be
out-of-date by counting the number of data modifications
since the last statistics update and comparing the
number of modifications to a threshold.
24. Auto Create Statistics
Default setting of auto create statistics is ON.
It creates when:
Clustered and non clustered Index is created
Select query is executed.
Auto create and updates applies strictly to
single-column statistics.
25. Why Query 2 Is Performing
Better
If we perform following operations on field of
any table in query predicate:
Using any system function or user defined
function
Scalar operation like addition, multiplication
etc.
Type casting
In this situation sql server query optimizer is
not able to estimate correct cardinality using
statistics.
26. To Improve Cardinality
If possible, simplify expressions with constants in them.
If possible, don't perform any operation on the any field
of a table in WHERE Clause, ON Clause, HAVING
Clause
Don't use local variables in WHERE Clause, ON
Clause, HAVING Clause.
If there is any cross relationship among fields or there is
a complex expression in a field in a query predicates, it
is better to create a computed column and then create a
non-clustered index on it.
27. To Improve Cardinality
If possible, don't update the value of parameters of a
function or stored procedure before using
in sql statement
Use OPTIMIZE FOR clause when you want to optimize
a sql query on the basis of specific parameter value.
If you want to update the value parameter of a stored
procedure or a function create a similar procedure or
function and execute it form base procedure or function
by passing the updated value as a parameter.
Create user defined multi column statistics if query
predicates have more than one fields of a table.