SlideShare a Scribd company logo
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

More Related Content

What's hot

List Processing in ABAP
List Processing in ABAPList Processing in ABAP
List Processing in ABAP
sapdocs. info
 
Sql wksht-5
Sql wksht-5Sql wksht-5
Sql wksht-5
Mukesh Tekwani
 
AskTom Office Hours about Database Migrations
AskTom Office Hours about Database MigrationsAskTom Office Hours about Database Migrations
AskTom Office Hours about Database Migrations
Jasmin Fluri
 
ABAP Advanced List
ABAP Advanced ListABAP Advanced List
ABAP Advanced List
sapdocs. info
 
Single row functions
Single row functionsSingle row functions
Single row functions
Balqees Al.Mubarak
 
Sql wksht-1
Sql wksht-1Sql wksht-1
Sql wksht-1
Mukesh Tekwani
 
Les03
Les03Les03
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
Sergey Petrunya
 
Les03
Les03Les03
1 z1 051
1 z1 0511 z1 051
1 z1 051
AHMED ENNAJI
 
e computer notes - Single row functions
e computer notes - Single row functionse computer notes - Single row functions
e computer notes - Single row functions
ecomputernotes
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
Vineeta Garg
 
Single row functions
Single row functionsSingle row functions
Single row functions
Soumyajit Dutta
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraints
Vineeta Garg
 
Les03
Les03Les03
Oracle sql analytic functions
Oracle sql analytic functionsOracle sql analytic functions
Oracle sql analytic functions
mamamowebby
 
Dialog Programming Overview
Dialog Programming OverviewDialog Programming Overview
Dialog Programming Overview
sapdocs. info
 
Sql query [select, sub] 4
Sql query [select, sub] 4Sql query [select, sub] 4
Sql query [select, sub] 4
Dr. C.V. Suresh Babu
 
Clauses
ClausesClauses

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 advance
NaviSoft
 
DOAG: Visual SQL Tuning
DOAG: Visual SQL TuningDOAG: Visual SQL Tuning
DOAG: Visual SQL Tuning
Kyle Hailey
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
Stewart Rogers
 
Sql interview questions and answers
Sql interview questions and  answersSql interview questions and  answers
Sql interview questions and answers
sheibansari
 
MYSQL.ppt
MYSQL.pptMYSQL.ppt
MYSQL.ppt
webhostingguy
 
Introduction to MySQL
Introduction to MySQLIntroduction to MySQL
Introduction to MySQL
Giuseppe Maxia
 
Introduction to Mysql
Introduction to MysqlIntroduction to Mysql
Introduction to Mysql
Tushar Chauhan
 
MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
webhostingguy
 
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
iimjobs 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 Common SQL Programming Mistakes

SQL sheet
SQL sheetSQL sheet
SQL sheet
Suman singh
 
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.pdfiiiijuyyttfffgyyuyyyyyhhh
NaveeN547338
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricks
Yanli Liu
 
Databricks Sql cheatseet for professional exam
Databricks Sql cheatseet for professional examDatabricks Sql cheatseet for professional exam
Databricks Sql cheatseet for professional exam
RupiniSarguru
 
Database Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingDatabase Management System - SQL Advanced Training
Database Management System - SQL Advanced Training
Moutasm 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 sql
bharatjanadharwarud
 
Oracle SQL Model Clause
Oracle SQL Model ClauseOracle SQL Model Clause
Oracle SQL Model Clause
Scott Wesley
 
List Processing in ABAP
List Processing in ABAPList Processing in ABAP
List Processing in ABAP
sapdocs. info
 
Dynamic websites lec2
Dynamic websites lec2Dynamic websites lec2
Dynamic websites lec2
Belal 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.docx
clarebernice
 
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
Plamen Ratchev
 
Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库
renguzi
 
08_SQL OLAP DBMS DB2 GROUP BY CUBE ROLL UP .pptx
08_SQL OLAP DBMS DB2 GROUP BY CUBE ROLL UP .pptx08_SQL OLAP DBMS DB2 GROUP BY CUBE ROLL UP .pptx
08_SQL OLAP DBMS DB2 GROUP BY CUBE ROLL UP .pptx
ssuser52d6bf
 
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 Tips Calculate Running Totals.pptx
SQL Tips Calculate Running Totals.pptxSQL Tips Calculate Running Totals.pptx
SQL Tips Calculate Running Totals.pptx
Select Distinct Limited
 
Inner joins
Inner joinsInner joins
Using Inner-Joins (SQL)
Using Inner-Joins (SQL)Using Inner-Joins (SQL)
Using Inner-Joins (SQL)
Christopher Singleton
 
ADV DB SCREENSHOTS
ADV DB SCREENSHOTSADV DB SCREENSHOTS
ADV DB SCREENSHOTS
Joshua Mamuda
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answers
Nawaz Sk
 

Similar to 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
 
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
 
Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库
 
08_SQL OLAP DBMS DB2 GROUP BY CUBE ROLL UP .pptx
08_SQL OLAP DBMS DB2 GROUP BY CUBE ROLL UP .pptx08_SQL OLAP DBMS DB2 GROUP BY CUBE ROLL UP .pptx
08_SQL OLAP DBMS DB2 GROUP BY CUBE ROLL UP .pptx
 
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
 
Inner joins
Inner joinsInner joins
Inner joins
 
Using Inner-Joins (SQL)
Using Inner-Joins (SQL)Using Inner-Joins (SQL)
Using Inner-Joins (SQL)
 
ADV DB SCREENSHOTS
ADV DB SCREENSHOTSADV DB SCREENSHOTS
ADV DB SCREENSHOTS
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answers
 

Recently uploaded

Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 

Recently uploaded (20)

Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 

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