Improving the Performance of Functions

Slides:



Advertisements
Similar presentations
Yukon – What is New Rajesh Gala. Yukon – What is new.NET Framework Programming Data Types Exception Handling Batches Databases Database Engine Administration.
Advertisements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
Database Systems More SQL Database Design -- More SQL1.
Introduction to PL/SQL Chapter 9. Objectives Explain the need for PL/SQL Explain the benefits of PL/SQL Identify the different types of PL/SQL blocks.
SEMESTER 1, 2013/2014 DB2 APPLICATION DEVELOPMENT OVERVIEW.
Topics Views Stored Procedures User Defined Functions Triggers.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Database Design for DNN Developers Sebastian Leupold.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
Functions Lesson 10. Skills Matrix Function A function is a piece of code or routine that accepts parameters and stored as an object in SQL Server. The.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Stored Procedures, Transactions, and Error-Handling
Module 9 Designing and Implementing Stored Procedures.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
1 Definition of a subquery Nested subqueries Correlated subqueries The ISNULL function Derived tables The EXISTS operator Mixing data types: CAST & CONVERT.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 6 Functions.
5/24/01 Leveraging SQL Server 2000 in ColdFusion Applications December 9, 2003 Chris Lomvardias SRA International
PL/SQLPL/SQL Oracle11g : PL/SQL Programming Chapter 6 Functions.
Triggers A Quick Reference and Summary BIT 275. Triggers SQL code permits you to access only one table for an INSERT, UPDATE, or DELETE statement. The.
Using Procedures & Functions Oracle Database PL/SQL 10g Programming Chapter 9.
Lecture 8 Creating Stored Functions. Objectives  After completing this lesson, you should be able to do the following:  What is Function?  Types of.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
Sumanth M Ganesh B CPSC 620.  SQL Injection attacks allow a malicious individual to execute arbitrary SQL code on your server  The attack could involve.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
SQL Server User Defined Functions. CREATE FUNCTION [ schema_name. ] function_name ( [ [ AS ][ type_schema_name. ] parameter_data_type.
Slide 1 of 19Session 13 Ver. 1.0 Querying and Managing Data Using SQL Server 2005 In this session, you will learn to: Implement stored procedures Implement.
Dynamic SQL. 2 home back first prev next last What Will I Learn? Recall the stages through which all SQL statements pass Describe the reasons for using.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
1 Intro stored procedures Declaring parameters Using in a sproc Intro to transactions Concurrency control & recovery States of transactions Desirable.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Oracle9i Developer: PL/SQL Programming Chapter 5 Functions.
SQL Triggers, Functions & Stored Procedures Programming Operations.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Stored Procedures and Functions Pemrograman Basis Data MI2183.
In this session, you will learn to: Create and manage views Implement a full-text search Implement batches Objectives.
Implementing Functions Advanced Database Dr. AlaaEddin Almabhouh.
High Performance Functions SQLBits VI. Going backwards is faster than going forwards.
1. Advanced SQL Functions Procedural Constructs Triggers.
Session Name Pelin ATICI SQL Premier Field Engineer.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Trigger used in PosgreSQL
COMP 430 Intro. to Database Systems
More SQL: Complex Queries,
Creating Stored Functions
Stored Procedures.
Bridging the Data Science and SQL Divide for Practitioners
Java Primer 1: Types, Classes and Operators
UNIT - V STORED PROCEDURE.
Topic: Functions – Part 2
STORED PROCEDURES AND FUNCTION (9.6.1)
Functions CIS 40 – Introduction to Programming in Python
PL/SQL Scripting in Oracle:
PRACTICE OVERVIEW PL/SQL Part - 2.
U-SQL Object Model.
Query Optimization Techniques
Using Table Expressions
Tally Ho! -- Explore the Varied Uses of Tally Tables
Chapter 8 Advanced SQL.
MATERI PL/SQL Procedures Functions Packages Database Triggers
Diving into Query Execution Plans
Prof. Arfaoui. COM390 Chapter 6
Presentation transcript:

Improving the Performance of Functions Eric Freeman Lead BI Architect @ John Burns Real Estate Consulting Over 15 Years Experience

Agenda- Overview Brief History Limitations Function Types Functions with Bad Performance Refactoring Function UDF Auto Inline

Why we use Functions Modular Reusable Cleaner queries In most coding languages, functions are often-used blocks of code that can be reused from multiple locations, leading to less code – and cleaner code. SQL Server also lets us create functions that can be used the same way. They are reusable blocks of code that can be called from multiple locations.

Function Origins Functional programming has its origins in lambda calculus , a formal system developed in the 1930s to investigate computability SQL Server 2000- Microsoft introduced the concept of User-Defined Functions that allow you to define your own T-SQL functions that can accept zero or more parameters and return a single scalar data value or a table data type.

UDF Limitations Can not be used to perform actions that modify the database state Can not contain an OUTPUT INTO clause that has a table as its target Can not return multiple result sets Can not call a stored procedure* Can not use dynamic SQL or temp tables. Table variables are allowed Can not use SET statements (ex. SET ROWCOUNT) Can not use The FOR XML clause Error handling is restricted and does not support TRY...CATCH, @ERROR or RAISERROR User-defined functions can be nested; that is, one user-defined function can call another. The nesting level is incremented when the called function starts execution, and decremented when the called function finishes execution. User-defined functions can be nested up to 32 levels. Exceeding the maximum levels of nesting causes the whole calling function chain to fail. Any reference to managed code from a Transact-SQL user-defined function counts as one level against the 32-level nesting limit. Methods invoked from within managed code do not count against this limit.

Function Types Scalar- Returns a single value Multi-Statement Table Value Function- Returns table Inline Table Value Function- Returns table

Scalar Function Syntax CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name ( [ { @parameter_name [ AS ][ type_schema_name. ] parameter_data_type [ = default ] [ READONLY ] } [ ,...n ] ] ) RETURNS return_data_type [ WITH <function_option> [ ,...n ] ] [ AS ] BEGIN function_body RETURN scalar_expression END [ ; ]

Scalar Function Syntax CREATE FUNCTION [dbo].function_name (@parameter AS int) RETURNS int --WITH SCHEMABINDING, ... AS BEGIN --function_body RETURN 1 --value END

Multi-Statement TVF Syntax CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name ( [ { @parameter_name [ AS ] [ type_schema_name. ] parameter_data_type [ = default ] [READONLY] } [ ,...n ] ] ) RETURNS @return_variable TABLE <table_type_definition> [ WITH <function_option> [ ,...n ] ] [ AS ] BEGIN function_body RETURN END [ ; ]

Multi-Statement TVF Syntax CREATE FUNCTION [dbo].function_name (@parameter AS int) RETURNS @return_variable TABLE (a int)--<table_type_definition> --WITH SCHEMABINDING, ... AS BEGIN --function_body RETURN END

Inline TVF Syntax CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name ( [ { @parameter_name [ AS ] [ type_schema_name. ] parameter_data_type [ = default ] [ READONLY ] } [ ,...n ] ] ) RETURNS TABLE [ WITH <function_option> [ ,...n ] ] [ AS ] RETURN [ ( ] select_stmt [ ) ] [ ; ]

Inline TVF Syntax CREATE FUNCTION [dbo].function_name (@parameter AS int) RETURNS TABLE --WITH SCHEMABINDING, ... AS RETURN (select 1 as colName)

Demo 1 Create & Demo Functions

Functions Have Purpose As we looked at in the prior demo, functions have their place in SQL and should not be set aside Some companies have outright bans on UDF’s due to having prior, unresolved, issues with them.

Demo 2 Performance- Why is that query taking so long?

Good, not Great User defined functions give you great benefits in terms of encapsulation and code reusability Unfortunately, when you invoke a scalar UDF as part of a query and pass the function a column from the table as input, the function is invoked separately for each row This causes queries that could logically run fast, run significantly slower

Demo 3 What can we do to “make functions great again”?

Scalar UDF Inlining SQL 2019- Removing the ban on Scalar Functions The goal of the Scalar UDF inlining feature is to improve performance of queries that invoke scalar UDFs, where UDF execution is the main bottleneck.

Is my UDF inlineable? The sys.sql_modules catalog view includes a property called “is_inlineable”, which indicates whether a UDF is inlineable or not A value of 1 indicates that it is inlineable, and 0 indicates otherwise This property will also have a value of 1 for inline table-valued functions, since they are inlineable by definition.

Inlineable Checklist DECLARE, SET: Variable declaration and assignments. SELECT: SQL query with single/multiple variable assignments*. IF/ELSE: Branching with arbitrary levels of nesting. RETURN: Single or multiple return statements. UDF: Nested/recursive function calls**. Others: Relational operations such as EXISTS, ISNULL. The UDF does not invoke any intrinsic function that is either time-dependent (such as GETDATE()) or has side effects*** (such as NEWSEQUENTIALID()). The UDF uses the EXECUTE AS CALLER clause (the default behavior if the EXECUTE AS clause is not specified). The UDF does not reference table variables or table-valued parameters. The query invoking a scalar UDF does not reference a scalar UDF call in its GROUP BY clause.

Inlineable Checklist The UDF is not natively compiled (interop is supported). The UDF is not used in a computed column or a check constraint definition. The UDF does not reference user-defined types. There are no signatures added to the UDF. The UDF is not a partition function. *SELECT with variable accumulation/aggregation (for example, SELECT @val += col1 FROM table1) is not supported for inlining. **Recursive UDFs will be inlined to a certain depth only. ***Intrinsic functions whose results depend upon the current system time are time-dependent. An intrinsic function that may update some internal global state is an example of a function with side effects. Such functions return different results each time they are called, based on the internal state.

Summary How Scalar functions can destroy performance How Inline Table Valued Functions work w/ the Query Engine How SQL 2019 improves Scalar functions by making them inline automagically

Questions