๐—ง๐—ผ๐—ฝ ๐Ÿฎ๐Ÿฌ ๐—ฆ๐—ค๐—Ÿ ๐—พ๐˜‚๐—ฒ๐—ฟ๐˜† ๐—ผ๐—ฝ๐˜๐—ถ๐—บ๐—ถ๐˜‡๐—ฎ๐˜๐—ถ๐—ผ๐—ป ๐˜๐—ฒ๐—ฐ๐—ต๐—ป๐—ถ๐—พ๐˜‚๐—ฒ๐˜€

Here is the list of the top 20 SQL query optimization techniques I found important:

1. Create an index on very large tables (>1.000.000) rows

2. Use EXIST() instead of COUNT() to find an element in the table

3. SELECT fields instead of using SELECT *

4. Avoid Subqueries in WHERE Clause

5. Avoid SELECT DISTINCT where possible

6. Use WHERE Clause instead of HAVING

7. Create joins with INNER JOIN (not WHERE)

8. Use LIMIT to sample query results

9. Use UNION ALL instead of UNION wherever possible

10. Use UNION where instead of WHERE … or … query.

11. Run your query during off-peak hours

12. Avoid using OR in join queries

14. Choose GROUP BY over window functions

15. Use derived and temporary tables

16. Drop the index before loading bulk data

16. Use materialized views instead of views

17. Avoid != or <> (not equal) operator

18. Minimize the number of subqueries

19. Try to use INNER join as little as possible when you can get the same output using LEFT/RIGHT join.

20. For retrieving the same dataset frequently try to use temporary sources.

Do you know what is ๐—ค๐˜‚๐—ฒ๐—ฟ๐˜† ๐—ข๐—ฝ๐˜๐—ถ๐—บ๐—ถ๐˜‡๐—ฒ๐—ฟ? Its primary function is to determine ๐˜๐—ต๐—ฒ ๐—บ๐—ผ๐˜€๐˜ ๐—ฒ๐—ณ๐—ณ๐—ถ๐—ฐ๐—ถ๐—ฒ๐—ป๐˜ ๐˜„๐—ฎ๐˜† to execute a given SQL query by finding the best execution plan. The query optimizer works by taking the SQL query as input and analyzing it to determine how best to execute it. The first step is to parse the SQL query and create a syntax tree. The optimizer then analyzes the syntax tree to determine the various ways the query can be executed.

Next, the optimizer generates ๐—ฎ๐—น๐˜๐—ฒ๐—ฟ๐—ป๐—ฎ๐˜๐—ถ๐˜ƒ๐—ฒ ๐—ฒ๐˜…๐—ฒ๐—ฐ๐˜‚๐˜๐—ถ๐—ผ๐—ป ๐—ฝ๐—น๐—ฎ๐—ป๐˜€, which are different ways of executing the same query. Each execution plan specifies the order in which the tables should be accessed, the join methods to use, and any filtering or sorting operations to be performed. The optimizer then assigns a ๐—ฐ๐—ผ๐˜€๐˜ to each execution plan based on factors such as the number of disk reads and the amount of CPU time required to execute the query.

Finally, the optimizer ๐—ฐ๐—ต๐—ผ๐—ผ๐˜€๐—ฒ๐˜€ ๐˜๐—ต๐—ฒ ๐—ฒ๐˜…๐—ฒ๐—ฐ๐˜‚๐˜๐—ถ๐—ผ๐—ป ๐—ฝ๐—น๐—ฎ๐—ป with the lowest cost as the optimal execution plan for the query. This plan is then used to execute the query.

Working with CDC in SQL server

How do you read all the changes captured by CDC in a table?

USE AdventureWorks2022; 
GO 
DECLARE @from_lsn binary(10), @to_lsn binary(10); 
SET @from_lsn = sys.fn_cdc_get_min_lsn('HR_Department'); 
SET @to_lsn = sys.fn_cdc_get_max_lsn(); 
SELECT * FROM cdc.fn_cdc_get_all_changes_HR_Department (@from_lsn, @to_lsn, N'all'); 
GO

How do you read the net changes captured by CDC in a table?

USE AdventureWorks2022;  
GO  
DECLARE @begin_time datetime, @end_time datetime, @from_lsn binary(10), @to_lsn binary(10);  
-- Obtain the beginning of the time interval.  
SET @begin_time = DATEADD(day, -1, GETDATE()) ;  
-- DML statements to produce changes in the HumanResources.Department table.  
INSERT INTO HumanResources.Department (Name, GroupName)  
VALUES (N'MyDept', N'MyNewGroup');  
  
UPDATE HumanResources.Department  
SET GroupName = N'Resource Control'  
WHERE GroupName = N'Inventory Management';  
  
DELETE FROM HumanResources.Department  
WHERE Name = N'MyDept';  
  
-- Obtain the end of the time interval.  
SET @end_time = GETDATE();  
-- Map the time interval to a change data capture query range.  
SET @from_lsn = sys.fn_cdc_map_time_to_lsn('smallest greater than or equal', @begin_time);  
SET @from_lsn = ISNULL(sys.fn_cdc_map_time_to_lsn('smallest greater than or equal', @begin_time), [sys].[fn_cdc_get_min_lsn]('HR_Department') );
SET @to_lsn = sys.fn_cdc_map_time_to_lsn('largest less than or equal', @end_time);  
  
-- Return the net changes occurring within the query window.  
SELECT * FROM cdc.fn_cdc_get_net_changes_HR_Department(@from_lsn, @to_lsn, 'all');

source: cdc.fn_cdc_get_net_changes_<capture_instance> (Transact-SQL) – SQL Server | Microsoft Learn

Load excel files into a table on SQL server database

$File = "\\NFS01\SQLBackup\DATA_SQL.xlsx"
$Instance = "SQLSERVER01"
$Database = "dbname01"

$fileName =  [System.IO.Path]::GetFileNameWithoutExtension($File)

foreach($sheet in Get-ExcelSheetInfo $File)
{

$data = Import-Excel -Path $File -WorksheetName $sheet.name | ConvertTo-DbaDataTable
$tablename = "table_name"

Write-DbaDataTable -SqlInstance $Instance -Database $Database -InputObject $data -Truncate -Table $tablename

}

Update an existing database mail account using T-SQL

EXEC msdb..sysmail_update_account_sp @account_name = 'SMTP_database_mail',            -- sysname
                                     @email_address = N'altersemail@example.com',            -- nvarchar(128)
                                     @display_name = N'Database Mail',             -- nvarchar(128)
                                     @replyto_address = N'altersemail@example.com',          -- nvarchar(128)
                                     @description = N'Primary database alerts profile',              -- nvarchar(256)
                                     @mailserver_name = 'smtp.office365.com',         -- sysname
                                     @port = 587,                       -- int
                                     @username = 'altersemail@example.com',                -- sysname
                                     @password = 'SecurePassword',                -- sysname
                                     @use_default_credentials = 0, -- bit
                                     @enable_ssl = 1

Export SQL Server config using dbatools

Exports SQL Serverย ALLย database restore scripts, logins, database mail profiles/accounts, credentials, SQL Agent objects, linked servers, Central Management Server objects, server configuration settings (sp_configure), user objects in systems databases, system triggers and backup devices from one SQL Server to another.

Export-DbaInstance consolidates most of the export scripts in dbatools into one command.

This is useful when you’re looking to Export entire instances. It less flexible than using the underlying functions. Think of it as an easy button. Unless an -Exclude is specified, it exports:

All database ‘restore from backup’ scripts. Note: if a database does not have a backup the ‘restore from backup’ script won’t be generated. All logins. All database mail objects. All credentials. All objects within the Job Server (SQL Agent). All linked servers. All groups and servers within Central Management Server. All SQL Server configuration objects (everything in sp_configure). All user objects in system databases. All system triggers. All system backup devices. All Audits. All Endpoints. All Extended Events. All Policy Management objects. All Resource Governor objects. All Server Audit Specifications. All Custom Errors (User Defined Messages). All Server Roles. All Availability Groups. All OLEDB Providers.

The exported files are written to a folder with a naming convention of “machinename$instance-yyyyMMddHHmmss”.

Export-DbaInstance -SqlInstance SQLSERVER01 -Path \\SQLSERVER01\Backups\ -NoPrefix