SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 
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
 
List Processing in ABAP
List Processing in ABAPList Processing in ABAP
List Processing in ABAPsapdocs. info
 
Dynamic websites lec2
Dynamic websites lec2Dynamic websites lec2
Dynamic websites lec2Belal Arfa
 
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
 

Ähnlich wie 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
 
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
 
List Processing in ABAP
List Processing in ABAPList Processing in ABAP
List Processing in ABAP
 
Dynamic websites lec2
Dynamic websites lec2Dynamic websites lec2
Dynamic websites lec2
 
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
 
ADV DB SCREENSHOTS
ADV DB SCREENSHOTSADV DB SCREENSHOTS
ADV DB SCREENSHOTS
 

Kürzlich hochgeladen

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 

Kürzlich hochgeladen (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 

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);