SlideShare a Scribd company logo
1 of 37
Download to read offline
sku   product_description   color
                              1     Ball                  Red
                              2     Bike                  Blue
                              3     Tent                  NULL




SELECT C.color                                            color
FROM Colors AS C                                          Black
WHERE C.color NOT IN (SELECT P.color                      Blue
                      FROM Products AS P);                Green
                                                          Red


color
----------

(0 row(s) affected)
/* EXISTS */
SELECT C.color
FROM Colors AS C
WHERE NOT EXISTS(SELECT *
                 FROM Products AS P
                 WHERE C.color = P.color);

/* IS NOT NULL in the subquery */
SELECT C.color
FROM Colors AS C
WHERE C.color NOT IN (SELECT P.color
                      FROM Products AS P
                      WHERE P.color IS NOT NULL);

/* EXCEPT */
SELECT color
FROM Colors
EXCEPT
SELECT color
FROM Products;

/* LEFT OUTER JOIN */
SELECT C.color
FROM Colors AS C
LEFT OUTER JOIN Products AS P
  ON C.color = P.color
WHERE P.color IS NULL;
SELECT customer_name
FROM Customers
WHERE LEFT(customer_name, 1) = 'L';



SELECT SUM(sale_amount) AS total_sales
FROM Sales
WHERE DATEPART(YEAR, sale_date) = 2009
  AND DATEPART(MONTH, sale_date) = 1;



/* Exception: SQL Server 2008 only */
SELECT SUM(sale_amount) AS total_sales
FROM Sales
WHERE CAST(sale_date AS DATE) = '20090101';
SELECT customer_name
FROM Customers
WHERE customer_name LIKE 'L%';



SELECT SUM(sale_amount) AS
total_sales
FROM Sales
WHERE sale_date >= '20090101'
  AND sale_date < '20090201';
calendar_date   holiday_name
                               2009-01-01      New Year’s Day
                               2009-01-02      NULL
                               2009-01-03      NULL
                               2009-01-04      NULL
                               2009-01-05      NULL




                                      sale_date       sale_amount
                                      2009-01-01      120.50
                                   2009-01-02         115.00
SELECT sale_date, sale_amount
FROM Sales AS S                    2009-01-03         140.80
WHERE sale_date IN                 2009-01-04         100.50
     (SELECT sale_date
      FROM Calendar AS C
      WHERE holiday_name IS NOT NULL);
SELECT sale_date, sale_amount
FROM Sales AS S
WHERE sale_date IN
     (SELECT C.calendar_date
      FROM Calendar AS C
      WHERE C.holiday_name IS NOT NULL);
CREATE TABLE Customers (
 customer_nbr INT NOT NULL PRIMARY KEY,
 first_name VARCHAR(35) NOT NULL,
 last_name VARCHAR(35) NOT NULL);


SELECT first_name, last_name
FROM Customers
WHERE last_name = N'Brown';


/*
StmtText
-----------------------------------
  |--Clustered Index Scan(OBJECT:(
         [dbo].[Customers].[PK_Customer]),
     WHERE:(CONVERT_IMPLICIT(nvarchar(35),
         [dbo].[Customers].[last_name],0)=[@1]))
*/
SELECT first_name, last_name
FROM Customers
WHERE last_name = 'Brown';
account_nbr   account_type     account_reference
                   1             Personal         abc
                   2             Business Basic   101
                   3             Personal         def
                   4             Business Plus    5


SELECT account_nbr, account_reference AS account_ref_nbr
FROM Accounts
WHERE account_type LIKE 'Business%'
  AND CAST(account_reference AS INT) > 20;


SELECT account_nbr, account_ref_nbr
FROM (SELECT account_nbr,
             CAST(account_reference AS INT)
                                    AS account_ref_nbr
      FROM Accounts
      WHERE account_type LIKE 'Business%') AS A
WHERE account_ref_nbr > 20;
SELECT account_nbr,
       account_reference AS account_ref_nbr
FROM Accounts
WHERE account_type LIKE 'Business%'
  AND CASE WHEN account_reference NOT LIKE '%[^0-9]%'
           THEN CAST(account_reference AS INT)
      END > 20;
SELECT C.customer_name,
       SUM(COALESCE(O.order_amt, 0)) AS total_2009
FROM Customers AS C
LEFT OUTER JOIN Orders AS O
  ON C.customer_nbr = O.customer_nbr
WHERE O.order_date >= '20090101'
GROUP BY C.customer_name;



SELECT C.customer_name, O.order_amt, D.qty
FROM Customers AS C
LEFT OUTER JOIN Orders AS O
  ON C.customer_nbr = O.customer_nbr
INNER JOIN OrderDetails AS D
  ON D.order_nbr = O.order_nbr
 AND D.sku = 101;
-- Correct predicate in join conditions
SELECT C.customer_name,
       SUM(COALESCE(O.order_amt, 0)) AS total_2009
FROM Customers AS C
LEFT OUTER JOIN Orders AS O
  ON C.customer_nbr = O.customer_nbr
 AND O.order_date >= '20090101'
GROUP BY C.customer_name;



-- Correct with OUTER join
SELECT C.customer_name, O.order_amt, D.qty
FROM Customers AS C
LEFT OUTER JOIN Orders AS O
  ON C.customer_nbr = O.customer_nbr
LEFT OUTER JOIN OrderDetails AS D
  ON D.order_nbr = O.order_nbr
 AND D.sku = 101;
SELECT sku, product_description,
      (SELECT plant_nbr
       FROM ProductPlants AS B
       WHERE B.sku = A.sku) AS plant_nbr
FROM Products AS A;



SELECT A.sku, A.product_description, B.plant_nbr
FROM Products AS A
JOIN ProductPlants AS B
  ON A.sku = B.sku
WHERE B.sku =
     (SELECT C.sku
      FROM NewProducts AS C
      WHERE C.product_description LIKE '%guitar%');
SELECT A.sku,
       A.product_description,
       B.plant_nbr
FROM Products AS A
JOIN ProductPlants AS B
  ON A.sku = B.sku;
INSERT INTO PlasticProducts
SELECT *
FROM Products
WHERE material_type = 'plastic';



CREATE VIEW MetalProducts
AS
SELECT *
FROM Products
WHERE material_type = 'metal';
INSERT INTO PlasticProducts
      (sku, product_description, material_type)
SELECT sku, product_description, material_type
FROM Products
WHERE material_type = 'plastic';
CREATE FUNCTION dbo.GetTotalSales(@sku INT)
RETURNS DECIMAL(15, 2)
AS
BEGIN
  RETURN(SELECT SUM(sale_amount)
         FROM Sales
         WHERE sku = @sku);
END



SELECT sku,
       product_description,
       dbo.GetTotalSales(sku) AS total_sales
FROM Products;
-- direct calculation in the query
SELECT P.sku, P.product_description,
       SUM(S.sale_amount) As total_sales
FROM Products AS P
JOIN Sales AS S
  ON P.sku = S.sku
GROUP BY P.sku, P.product_description;


-- table-valued function
CREATE FUNCTION dbo.GetTotalSales(@sku INT)
RETURNS TABLE
AS
RETURN(SELECT SUM(sale_amount) AS total_sales
       FROM Sales
       WHERE sku = @sku);


-- query using table-valued function with CROSS APPLY
SELECT sku, product_description, total_sales
FROM Products AS P
CROSS APPLY dbo.GetTotalSales(P.sku) AS S;
DECLARE PriceUpdates
CURSOR LOCAL
       FORWARD_ONLY
       STATIC
       READ_ONLY
FOR SELECT sku, price
    FROM NewPrices;

OPEN PriceUpdates;

FETCH NEXT FROM PriceUpdates
      INTO @sku, @price;

WHILE @@FETCH_STATUS = 0
BEGIN
  UPDATE ProductPrices
  SET price = @price,
      effective_start_date = CURRENT_TIMESTAMP
  WHERE sku = @sku;
  FETCH NEXT FROM PriceUpdates
        INTO @sku, @price;

END
UPDATE ProductPrices
SET price = (SELECT N.price
             FROM NewPrices AS N
             WHERE N.sku = ProductPrices.sku),
    effective_start_date = CURRENT_TIMESTAMP
WHERE EXISTS(SELECT *
             FROM NewPrices AS N
             WHERE N.sku = ProductPrices.sku);
Optimize  for SQL queries and data operations
Optimize  for SQL queries and data operations

More Related Content

What's hot

What's hot (19)

List Processing in ABAP
List Processing in ABAPList Processing in ABAP
List Processing in ABAP
 
Sql wksht-5
Sql wksht-5Sql wksht-5
Sql wksht-5
 
AskTom Office Hours about Database Migrations
AskTom Office Hours about Database MigrationsAskTom Office Hours about Database Migrations
AskTom Office Hours about Database Migrations
 
ABAP Advanced List
ABAP Advanced ListABAP Advanced List
ABAP Advanced List
 
Single row functions
Single row functionsSingle row functions
Single row functions
 
Sql wksht-1
Sql wksht-1Sql wksht-1
Sql wksht-1
 
Les03
Les03Les03
Les03
 
New Query Optimizer features in MariaDB 10.3
New Query Optimizer features in MariaDB 10.3New Query Optimizer features in MariaDB 10.3
New Query Optimizer features in MariaDB 10.3
 
Les03
Les03Les03
Les03
 
1 z1 051
1 z1 0511 z1 051
1 z1 051
 
e computer notes - Single row functions
e computer notes - Single row functionse computer notes - Single row functions
e computer notes - Single row functions
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
 
Single row functions
Single row functionsSingle row functions
Single row functions
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraints
 
Les03
Les03Les03
Les03
 
Oracle sql analytic functions
Oracle sql analytic functionsOracle sql analytic functions
Oracle sql analytic functions
 
Dialog Programming Overview
Dialog Programming OverviewDialog Programming Overview
Dialog Programming Overview
 
Sql query [select, sub] 4
Sql query [select, sub] 4Sql query [select, sub] 4
Sql query [select, sub] 4
 
Clauses
ClausesClauses
Clauses
 

Viewers also liked

15 questions sql advance
15 questions sql   advance15 questions sql   advance
15 questions sql advanceNaviSoft
 
DOAG: Visual SQL Tuning
DOAG: Visual SQL TuningDOAG: Visual SQL Tuning
DOAG: Visual SQL TuningKyle Hailey
 
Sql interview questions and answers
Sql interview questions and  answersSql interview questions and  answers
Sql interview questions and answerssheibansari
 
Top 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and AnswersTop 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and Answersiimjobs and hirist
 

Viewers also liked (9)

15 questions sql advance
15 questions sql   advance15 questions sql   advance
15 questions sql advance
 
DOAG: Visual SQL Tuning
DOAG: Visual SQL TuningDOAG: Visual SQL Tuning
DOAG: Visual SQL Tuning
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Sql interview questions and answers
Sql interview questions and  answersSql interview questions and  answers
Sql interview questions and answers
 
MYSQL.ppt
MYSQL.pptMYSQL.ppt
MYSQL.ppt
 
Introduction to MySQL
Introduction to MySQLIntroduction to MySQL
Introduction to MySQL
 
Introduction to Mysql
Introduction to MysqlIntroduction to Mysql
Introduction to Mysql
 
MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
 
Top 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and AnswersTop 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and Answers
 

Similar to Optimize for SQL queries and data operations

Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...
Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...
Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...rcmoutinho
 
SQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhh
SQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhhSQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhh
SQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhhNaveeN547338
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricksYanli Liu
 
Adding measures to Calcite SQL
Adding measures to Calcite SQLAdding measures to Calcite SQL
Adding measures to Calcite SQLJulian Hyde
 
Databricks Sql cheatseet for professional exam
Databricks Sql cheatseet for professional examDatabricks Sql cheatseet for professional exam
Databricks Sql cheatseet for professional examRupiniSarguru
 
Database Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingDatabase Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingMoutasm Tamimi
 
sql ppt for students who preparing for sql
sql ppt for students who preparing for sqlsql ppt for students who preparing for sql
sql ppt for students who preparing for sqlbharatjanadharwarud
 
Oracle SQL Model Clause
Oracle SQL Model ClauseOracle SQL Model Clause
Oracle SQL Model ClauseScott Wesley
 
Dynamic websites lec2
Dynamic websites lec2Dynamic websites lec2
Dynamic websites lec2Belal Arfa
 
May Woo Bi Portfolio
May Woo Bi PortfolioMay Woo Bi Portfolio
May Woo Bi Portfoliomaywoo
 
CIS276DB Module 6 Assignment 1. Write a select sta.docx
CIS276DB Module 6 Assignment   1. Write a select sta.docxCIS276DB Module 6 Assignment   1. Write a select sta.docx
CIS276DB Module 6 Assignment 1. Write a select sta.docxclarebernice
 
Zen and the Art of Writing SQL Query
Zen and the Art of Writing SQL QueryZen and the Art of Writing SQL Query
Zen and the Art of Writing SQL QueryPlamen Ratchev
 
SQL: The Language of Databases
SQL: The Language of DatabasesSQL: The Language of Databases
SQL: The Language of DatabasesRJ Podeschi
 
Greg Lewis SQL Portfolio
Greg Lewis SQL PortfolioGreg Lewis SQL Portfolio
Greg Lewis SQL Portfoliogregmlewis
 
Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库renguzi
 
Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...
Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...
Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...rcmoutinho
 

Similar to Optimize for SQL queries and data operations (20)

SQL sheet
SQL sheetSQL sheet
SQL sheet
 
Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...
Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...
Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...
 
SQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhh
SQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhhSQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhh
SQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhh
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricks
 
Adding measures to Calcite SQL
Adding measures to Calcite SQLAdding measures to Calcite SQL
Adding measures to Calcite SQL
 
Databricks Sql cheatseet for professional exam
Databricks Sql cheatseet for professional examDatabricks Sql cheatseet for professional exam
Databricks Sql cheatseet for professional exam
 
Database Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingDatabase Management System - SQL Advanced Training
Database Management System - SQL Advanced Training
 
sql ppt for students who preparing for sql
sql ppt for students who preparing for sqlsql ppt for students who preparing for sql
sql ppt for students who preparing for sql
 
Oracle SQL Model Clause
Oracle SQL Model ClauseOracle SQL Model Clause
Oracle SQL Model Clause
 
Dynamic websites lec2
Dynamic websites lec2Dynamic websites lec2
Dynamic websites lec2
 
May Woo Bi Portfolio
May Woo Bi PortfolioMay Woo Bi Portfolio
May Woo Bi Portfolio
 
CIS276DB Module 6 Assignment 1. Write a select sta.docx
CIS276DB Module 6 Assignment   1. Write a select sta.docxCIS276DB Module 6 Assignment   1. Write a select sta.docx
CIS276DB Module 6 Assignment 1. Write a select sta.docx
 
Zen and the Art of Writing SQL Query
Zen and the Art of Writing SQL QueryZen and the Art of Writing SQL Query
Zen and the Art of Writing SQL Query
 
SQL: The Language of Databases
SQL: The Language of DatabasesSQL: The Language of Databases
SQL: The Language of Databases
 
Greg Lewis SQL Portfolio
Greg Lewis SQL PortfolioGreg Lewis SQL Portfolio
Greg Lewis SQL Portfolio
 
Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库
 
Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...
Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...
Performance e Produtividade: 2 Habilidades para Transformar seu Relacionament...
 
SQL Tips Calculate Running Totals.pptx
SQL Tips Calculate Running Totals.pptxSQL Tips Calculate Running Totals.pptx
SQL Tips Calculate Running Totals.pptx
 
Using Inner-Joins (SQL)
Using Inner-Joins (SQL)Using Inner-Joins (SQL)
Using Inner-Joins (SQL)
 
Inner joins
Inner joinsInner joins
Inner joins
 

Recently uploaded

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 

Recently uploaded (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 

Optimize for SQL queries and data operations

  • 1.
  • 2.
  • 3.
  • 4.
  • 5. sku product_description color 1 Ball Red 2 Bike Blue 3 Tent NULL SELECT C.color color FROM Colors AS C Black WHERE C.color NOT IN (SELECT P.color Blue FROM Products AS P); Green Red color ---------- (0 row(s) affected)
  • 6. /* EXISTS */ SELECT C.color FROM Colors AS C WHERE NOT EXISTS(SELECT * FROM Products AS P WHERE C.color = P.color); /* IS NOT NULL in the subquery */ SELECT C.color FROM Colors AS C WHERE C.color NOT IN (SELECT P.color FROM Products AS P WHERE P.color IS NOT NULL); /* EXCEPT */ SELECT color FROM Colors EXCEPT SELECT color FROM Products; /* LEFT OUTER JOIN */ SELECT C.color FROM Colors AS C LEFT OUTER JOIN Products AS P ON C.color = P.color WHERE P.color IS NULL;
  • 7.
  • 8. SELECT customer_name FROM Customers WHERE LEFT(customer_name, 1) = 'L'; SELECT SUM(sale_amount) AS total_sales FROM Sales WHERE DATEPART(YEAR, sale_date) = 2009 AND DATEPART(MONTH, sale_date) = 1; /* Exception: SQL Server 2008 only */ SELECT SUM(sale_amount) AS total_sales FROM Sales WHERE CAST(sale_date AS DATE) = '20090101';
  • 9. SELECT customer_name FROM Customers WHERE customer_name LIKE 'L%'; SELECT SUM(sale_amount) AS total_sales FROM Sales WHERE sale_date >= '20090101' AND sale_date < '20090201';
  • 10.
  • 11. calendar_date holiday_name 2009-01-01 New Year’s Day 2009-01-02 NULL 2009-01-03 NULL 2009-01-04 NULL 2009-01-05 NULL sale_date sale_amount 2009-01-01 120.50 2009-01-02 115.00 SELECT sale_date, sale_amount FROM Sales AS S 2009-01-03 140.80 WHERE sale_date IN 2009-01-04 100.50 (SELECT sale_date FROM Calendar AS C WHERE holiday_name IS NOT NULL);
  • 12. SELECT sale_date, sale_amount FROM Sales AS S WHERE sale_date IN (SELECT C.calendar_date FROM Calendar AS C WHERE C.holiday_name IS NOT NULL);
  • 13.
  • 14.
  • 15. CREATE TABLE Customers ( customer_nbr INT NOT NULL PRIMARY KEY, first_name VARCHAR(35) NOT NULL, last_name VARCHAR(35) NOT NULL); SELECT first_name, last_name FROM Customers WHERE last_name = N'Brown'; /* StmtText ----------------------------------- |--Clustered Index Scan(OBJECT:( [dbo].[Customers].[PK_Customer]), WHERE:(CONVERT_IMPLICIT(nvarchar(35), [dbo].[Customers].[last_name],0)=[@1])) */
  • 16. SELECT first_name, last_name FROM Customers WHERE last_name = 'Brown';
  • 17.
  • 18. account_nbr account_type account_reference 1 Personal abc 2 Business Basic 101 3 Personal def 4 Business Plus 5 SELECT account_nbr, account_reference AS account_ref_nbr FROM Accounts WHERE account_type LIKE 'Business%' AND CAST(account_reference AS INT) > 20; SELECT account_nbr, account_ref_nbr FROM (SELECT account_nbr, CAST(account_reference AS INT) AS account_ref_nbr FROM Accounts WHERE account_type LIKE 'Business%') AS A WHERE account_ref_nbr > 20;
  • 19. SELECT account_nbr, account_reference AS account_ref_nbr FROM Accounts WHERE account_type LIKE 'Business%' AND CASE WHEN account_reference NOT LIKE '%[^0-9]%' THEN CAST(account_reference AS INT) END > 20;
  • 20.
  • 21. SELECT C.customer_name, SUM(COALESCE(O.order_amt, 0)) AS total_2009 FROM Customers AS C LEFT OUTER JOIN Orders AS O ON C.customer_nbr = O.customer_nbr WHERE O.order_date >= '20090101' GROUP BY C.customer_name; SELECT C.customer_name, O.order_amt, D.qty FROM Customers AS C LEFT OUTER JOIN Orders AS O ON C.customer_nbr = O.customer_nbr INNER JOIN OrderDetails AS D ON D.order_nbr = O.order_nbr AND D.sku = 101;
  • 22. -- Correct predicate in join conditions SELECT C.customer_name, SUM(COALESCE(O.order_amt, 0)) AS total_2009 FROM Customers AS C LEFT OUTER JOIN Orders AS O ON C.customer_nbr = O.customer_nbr AND O.order_date >= '20090101' GROUP BY C.customer_name; -- Correct with OUTER join SELECT C.customer_name, O.order_amt, D.qty FROM Customers AS C LEFT OUTER JOIN Orders AS O ON C.customer_nbr = O.customer_nbr LEFT OUTER JOIN OrderDetails AS D ON D.order_nbr = O.order_nbr AND D.sku = 101;
  • 23.
  • 24.
  • 25. SELECT sku, product_description, (SELECT plant_nbr FROM ProductPlants AS B WHERE B.sku = A.sku) AS plant_nbr FROM Products AS A; SELECT A.sku, A.product_description, B.plant_nbr FROM Products AS A JOIN ProductPlants AS B ON A.sku = B.sku WHERE B.sku = (SELECT C.sku FROM NewProducts AS C WHERE C.product_description LIKE '%guitar%');
  • 26. SELECT A.sku, A.product_description, B.plant_nbr FROM Products AS A JOIN ProductPlants AS B ON A.sku = B.sku;
  • 27.
  • 28. INSERT INTO PlasticProducts SELECT * FROM Products WHERE material_type = 'plastic'; CREATE VIEW MetalProducts AS SELECT * FROM Products WHERE material_type = 'metal';
  • 29. INSERT INTO PlasticProducts (sku, product_description, material_type) SELECT sku, product_description, material_type FROM Products WHERE material_type = 'plastic';
  • 30.
  • 31. CREATE FUNCTION dbo.GetTotalSales(@sku INT) RETURNS DECIMAL(15, 2) AS BEGIN RETURN(SELECT SUM(sale_amount) FROM Sales WHERE sku = @sku); END SELECT sku, product_description, dbo.GetTotalSales(sku) AS total_sales FROM Products;
  • 32. -- direct calculation in the query SELECT P.sku, P.product_description, SUM(S.sale_amount) As total_sales FROM Products AS P JOIN Sales AS S ON P.sku = S.sku GROUP BY P.sku, P.product_description; -- table-valued function CREATE FUNCTION dbo.GetTotalSales(@sku INT) RETURNS TABLE AS RETURN(SELECT SUM(sale_amount) AS total_sales FROM Sales WHERE sku = @sku); -- query using table-valued function with CROSS APPLY SELECT sku, product_description, total_sales FROM Products AS P CROSS APPLY dbo.GetTotalSales(P.sku) AS S;
  • 33.
  • 34. DECLARE PriceUpdates CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR SELECT sku, price FROM NewPrices; OPEN PriceUpdates; FETCH NEXT FROM PriceUpdates INTO @sku, @price; WHILE @@FETCH_STATUS = 0 BEGIN UPDATE ProductPrices SET price = @price, effective_start_date = CURRENT_TIMESTAMP WHERE sku = @sku; FETCH NEXT FROM PriceUpdates INTO @sku, @price; END
  • 35. UPDATE ProductPrices SET price = (SELECT N.price FROM NewPrices AS N WHERE N.sku = ProductPrices.sku), effective_start_date = CURRENT_TIMESTAMP WHERE EXISTS(SELECT * FROM NewPrices AS N WHERE N.sku = ProductPrices.sku);