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);
Common SQL Programming Mistakes
Common SQL Programming Mistakes

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 Common SQL Programming Mistakes

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
 
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
 
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
 
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
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answersNawaz Sk
 

Ähnlich wie Common SQL Programming Mistakes (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
 
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
 
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
 
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
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answers
 

Kürzlich hochgeladen

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
[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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Kürzlich hochgeladen (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.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
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Common SQL Programming Mistakes

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