尊敬的 微信汇率:1円 ≈ 0.046089 元 支付宝汇率:1円 ≈ 0.04618元 [退出登录]
SlideShare a Scribd company logo
SQL Antipatterns 
Krishnakumar S
Design Patterns 
• A solution to a recurring problem, in a context 
• Abstracts a recurring design structure 
• Distills design experience 
• Pattern consists of a problem and a solution
Antipatterns 
• A solution to a recurring problem, in a context 
• Generates problems than solution 
• Go from problem to bad solution 
• Antipattern consists of two solutions 
• One which is beneficial 
• One which is problematic
Why learning antipatterns? 
“Identifying bad practices can be as valuable as 
identifying good practices” - Ward Cunningham 
Antipatterns identify and categorize the common 
mistakes in software practice 
“If debugging is the process of removing bugs, 
then programming must be the process of 
putting them in.” – Edsger W. Dijkstra
SQL Antipatterns 
Database Design Database Creation 
CREATE TABLE BugsProducts 
( 
bug_id INTEGER REFERENCES Bugs, 
product VARCHAR(100) REFERENCES 
Products, 
PRIMARY KEY (bug_id, product) 
); 
Query 
SELECT b.product, COUNT(*) 
FROM BugsProducts AS b 
GROUP BY b.product; 
Application 
SELECT b.product, COUNT(*) 
FROM BugsProducts AS b 
GROUP BY b.product;
SQL Antipatterns 
Design Creation Query Application 
Jaywalking 
Cross walking 
Jaywalking 
Example Problem 
Storing list of authors for a book… 
Book Name Authors 
Code Complete Steve McConnell 
Design Patterns Erich Gamma, Richard Helm, Ralph Johnson, John 
Vlissides 
Intro. to Automata Theory Jeffrey Ullman, John Hopcroft 
Assigning role based menu access… 
Menu Name Role Accessibility 
Reset Password Admin 
Account Heads Senior Accountant, Accounts Manager 
YTD Sales Report CFO, Sales Manager, Sales Rep
SQL Antipatterns 
Design Creation Query Application 
Jaywalking 
Objective 
1. Avoid Intersection table 
2. Avoid joins and thus minimize query plan complexity
SQL Antipatterns 
Design Creation Query Application 
Jaywalking 
Implementation 
CREATE TABLE Menu 
( 
MenuID INT, 
Menu VARCHAR(50), 
Module VARCHAR(50), 
AccessibileTo VARCHAR(500), 
CONSTRAINT PK_Menu 
PRIMARY KEY CLUSTERED 
( 
MenuID 
) 
) 
GO 
INSERT INTO Menu (MenuID, Menu, Module, AccessibileTo) VALUES 
(1, 'Reset Password', 'Administration', 'Admin'), 
(2, 'Account Heads', 'Finance', 'Senior Accountant, Accounts Manager'), 
(3, 'YTD Sales Report', 'Report', 'CFO, Sales Manager, Sales Rep');
SQL Antipatterns 
Design Creation Query Application 
Jaywalking 
New problems… 
Violation of First normal form 
Cannot chose a right data type – You can enter Admin, Sales Rep, 1, 2, banana 
Cannot use foreign key constraints – No referential integrity 
Cannot enforce uniqueness – 1, 2, 3, 4, 3, 3, 2 
Cannot easily modify the values in the column 
What happens if the length of values exceeds the column limit? 
How do you search for menus accessible for Admin and CFO? No indexing is possible 
How many roles have access to Current Year Budget Reports? Aggregation is difficult 
How do you join the table with Role table? 
Storing integer number as character take space than storing as integer? 
Workarounds include splitting functions that will be inefficient?
SQL Antipatterns 
Design Creation Query Application 
Jaywalking 
Solution : Create an intersection table 
Menu MenuAccess Role 
Intersection table 
CREATE TABLE dbo.Menu 
( 
MenuID INT, 
Menu VARCHAR(50), 
Module VARCHAR(50) 
CONSTRAINT PK_Menu PRIMARY KEY 
CLUSTERED 
( 
MenuID 
) 
) 
GO 
CREATE TABLE dbo.Role 
( 
RoleID INT, 
Name VARCHAR(50), 
CreatedDate DATETIME, 
CONSTRAINT PK_Role PRIMARY KEY 
CLUSTERED 
( 
RoleID 
) 
) 
GO 
CREATE TABLE dbo.MenuAccess 
( 
MenuAccessID INT, 
MenuID INT, 
RoleID INT, 
CONSTRAINT FK_MenuAccess_Menu 
FOREIGN KEY (MenuID) 
REFERENCES Menu (MenuID), 
CONSTRAINT FK_MenuAccess_Role 
FOREIGN KEY (RoleID) 
REFERENCES dbo.Role (RoleID) 
) 
GO
SQL Antipatterns 
Design Creation Query Application 
Keyless Entry 
Example Problem 
I need a Supplier and a Invoice table… 
Invoice table stores number from Supplier table, to 
identify the supplier; however….. 
I don’t want to make the design complex…. 
The sentence I’m about to tell you is a secret ! … 
I don’t like keys ! Keys and Constraints limit flexibility!
SQL Antipatterns 
Design Creation Query Application 
Keyless Entry 
Objective 
1. Avoid Update/Delete/Insert conflicts 
2. Avoid complexity around foreign key constraints
SQL Antipatterns 
Design Creation Query Application 
Keyless Entry 
Implementation 
Create tables without any FOREIGN KEY constraints
SQL Antipatterns 
Design Creation Query Application 
Keyless Entry 
New problems… 
Breaking the foundation of relational database - Constraints 
Introduce meaningless data – Authors without any books or Orders without customers 
Cannot utilize the query optimizations due to constraints – Some RDBMS utilizes 
FOREIGN KEY and CHECK constraints to optimize queries 
Need to implement custom solutions to check integrity on a later stage 
Forced to implement periodic checks to find orphan rows
SQL Antipatterns 
Design Creation Query Application 
Keyless Entry 
Solution : Implement referential integrity through FOREIGN KEY constraints 
Use cascading referential integrity constraints. 
CREATE TABLE dbo.MenuAccess 
( 
MenuAccessID INT, 
MenuID INT, 
RoleID INT, 
CONSTRAINT FK_MenuAccess_Menu 
FOREIGN KEY (MenuID) 
REFERENCES dbo.Menu (MenuID) 
ON DELETE CASCADE 
ON UPDATE CASCADE, 
CONSTRAINT FK_MenuAccess_Role 
FOREIGN KEY (RoleID) 
REFERENCES dbo.Role (RoleID) 
ON DELETE SET NULL 
ON UPDATE CASCADE, 
) 
GO 
You can even disable and enable FOREIGN KEY, 
if needed. 
-- Disable FOREIGN KEY 
ALTER TABLE MenuAccess 
NOCHECK CONSTRAINT FK_MenuAccess_Menu; 
-- Enable FOREIGN KEY 
ALTER TABLE MenuAccess 
WITH CHECK 
CHECK CONSTRAINT FK_MenuAccess_Menu;
SQL Antipatterns 
Design Creation Query Application 
‘31 Flavors’ 
Example Problem 
Our bug tracking software supports only three bug 
statuses 
NEW 
INPROGRESS 
FIXED 
This will never change (I guess!)
SQL Antipatterns 
Design Creation Query Application 
‘31 Flavors’ 
Objective 
1. Restrict a column’s values to a fixed set of values 
2. Column never contains an invalid entry 
3. Simplifies usage and query development
SQL Antipatterns 
Design Creation Query Application 
‘31 Flavors’ 
Implementation 
CREATE TABLE dbo.Bugs 
( 
BugID INT, 
ModuleID INT, 
Description VARCHAR(200), 
-- Other columns 
BugStatus VARCHAR(20), 
CONSTRAINT CHK_BugStatus 
CHECK (BugStatus IN 
('NEW' , 'IN PROGRESS' , 'FIXED')) 
); 
GO
SQL Antipatterns 
Design Creation Query Application 
‘31 Flavors’ 
New problems… 
What are the available status values? 
SELECT DISTINCT BugStatus FROM dbo.Bugs; 
After few months, the QA team decides to add a new status ‘Duplicate’. How do you do 
that? 
Later the team has instructed to change ‘Fixed’ status to ‘Resolved’
SQL Antipatterns 
Design Creation Query Application 
‘31 Flavors’ 
Solution : Create a lookup table and use DRI 
CREATE TABLE dbo.BugStatus 
( 
BugStatusID INT, 
Status VARCHAR(20), 
Description VARCHAR(100), 
CONSTRAINT PK_BugStatus 
PRIMARY KEY CLUSTERED 
(BugStatusID) 
) 
GO 
CREATE TABLE dbo.Bugs 
( 
-- Other columns 
BugStatusID INT, 
CONSTRAINT FK_Bugs_BugStatus 
FOREIGN KEY (BugStatusID) 
REFERENCES dbo.BugStatus 
(BugStatusID) 
); 
GO 
INSERT INTO dbo.BugStatus (BugStatusID, Status, Description) VALUES 
(1, 'NEW', 'Once again a new bug reported'), 
(2, 'IN PROGRESS', 'Team is working hard on this'), 
(3, 'FIXED', 'The issues fixed for the time being!');
SQL Antipatterns 
Design Creation Query Application 
Fear of Unknown 
"There are things known, and there are things unknown, And 
in between are the Doors." ~ Jim Morrison 
Example Problem 
Our library stores information on books and periodicals 
Both have a name, publisher, language, and number of pages 
However ISBN is applicable to books and ISSN is for 
periodicals.
SQL Antipatterns 
Design Creation Query Application 
Fear of Unknown 
Objective 
Storing values that are not available or not applicable
SQL Antipatterns 
Design Creation Query Application 
Fear of Unknown 
Implementation 
CREATE TABLE dbo.Collection 
( 
ID INT NOT NULL, 
Name VARCHAR(100) NOT NULL, 
Year INT NOT NULL, 
PublisherID INT NOT NULL, 
-- Applicable to Books 
Edition INT NULL, 
ISBN VARCHAR(20) NULL, 
Binding VARCHAR(20) NULL 
CHECK 
Binding IN ('HARDCOVER', 'PAPERBACK')), 
-- Applicable to periodicals 
FrequencyID INT NULL 
REFERENCES dbo.Frequency (FrequencyID), 
Volume INT NULL, 
Issue INT NULL, 
ISSN VARCHAR(10) NULL 
) 
GO
SQL Antipatterns 
Design Creation Query Application 
Fear of Unknown 
New problems… 
ID Name Year PublisherID Edition ISBN Binding FrequencyID Volume Issue ISSN 
1 Introduction to Algorithms 1990 2 3978-0-262-03384-8 PAPERBACK 
2Code Complete 1993 5 1 978-1-55615-484-3 PAPERBACK 
3 Dr. Dobb's Journal 2009 12 3 34 2 1044-789X 
4The C Programming Language 1978 1 10-262-51087-2 PAPERBACK 
5 SQL Server Pro 1999 22 3 7 3 1522-2187 
What is the result of SELECT ID FROM dbo.Collection WHERE FrequencyID != 3;? 
Ans. (0) rows affected 
What is the result of 
SELECT 
Name + ‘,‘ + Edition + ‘(‘ + ISSN + ‘)’ 
FROM dbo.Collection WHERE ID = 2; 
Ans. NULL 
What is the result of SELECT COUNT(Volume) FROM dbo.Collection;? 
Ans. 2
SQL Antipatterns 
Design Creation Query Application 
Fear of Unknown 
Understanding NULL 
… in expression 
… in Boolean expression 
Expression Expected Actual 
NULL = 0 TRUE Unknown 
NULL = 12345 FALSE Unknown 
NULL <> 12345 TRUE Unknown 
NULL + 12345 12345 Unknown 
NULL + ‘ABC’ ABC Unknown 
NULL = NULL TRUE Unknown 
NULL <> NULL FALSE Unknown 
Expression Expected Actual 
NULL AND TRUE FALSE Unknown 
NULL AND FALSE FALSE FALSE 
NULL OR FALSE FALSE Unknown 
NULL OR TRUE TRUE TRUE 
NOT (NULL) TRUE Unknown
SQL Antipatterns 
Design Creation Query Application 
Fear of Unknown 
Understanding NULL 
NULL is not a value in a column 
NULL is a marker/construct in SQL for representing missing information 
"...it follows that a “type” that “contains a null” isn’t a type, 
a “tuple” that “contains a null” isn’t a tuple, 
a “relation” that “contains a null” isn’t a relation, and 
a “relvar” that contains a null isn’t a relvar. 
It follows further that nulls do serious violence to the relational model, and this 
dictionary therefore has very little to say regarding most null-related concepts“ 
– C . J. Date – The Relational Database Dictionary
SQL Antipatterns 
Design Creation Query Application 
Fear of Unknown 
Solution: Avoid usage of NULL as far as possible 
There are three reasons for NULL creep in to database table… 
Inapplicable NULL 
The ISSN of periodical is 
inapplicable to a book 
Solution: 
Design specialized tables 
with applicable columns. 
Create a Book table and a 
Periodical table 
Inapplicable NULL should 
be avoided 
Not yet applicable NULL 
The Number of copies of 
the book is currently not 
available, but will soon be 
available 
Solution: 
Give a default value until 
the value is available 
e.g.: ISO scheme for sex: 
0 = UNKNOWN 
1 = MALE 
2 = FEMALE 
9 = NOT APPLICABLE 
Nice to know NULL 
The comment for a book 
has no business value and 
will only used for 
reporting 
Solution: 
This column can contain 
the marker NULL.
SQL Antipatterns 
Design Creation Query Application 
Pseudo Key Neat-Freak 
…D oor ythoius plikaett tehrins… p?attern…? 
1 2 3 
89 4 144 5 233 
6 
21 7 34 8 55 
9 
13 8 5 
10 11 12 
Example Problem 
I used auto generated pseudo key for BookID in Book table 
Today morning when I query the table I found gaps in BookID numbers…! 
Books are missing! 
How the database miss it! 
Is that a bug! 
Clean it up and make it sequential! Born of a Pseudo Key Neat-Freak
SQL Antipatterns 
Design Creation Query Application 
Pseudo Key Neat-Freak 
Objective 
1. Pseudo key numbers should always be in sequential order 
2. There should not be any gaps between two adjacent pseudo key numbers
SQL Antipatterns 
Design Creation Query Application 
Pseudo Key Neat-Freak 
Implementation 
1. Do not use auto generating numbers; instead write custom 
queries to find the next number for the table 
2. Periodically run maintenance scripts to fill the gaps 
Gaps and Islands – Itzik Ben-Gan (MVP Deep Dives Vol. 1) 
10,000,000 rows with 10,000 gaps in every 1,000 rows
SQL Antipatterns 
Design Creation Query Application 
Pseudo Key Neat-Freak 
New problems… 
Any custom solution will cause locking and concurrency issues in application 
Gap filling algorithms are time consuming and resource intensive 
What about missed the propagation of renumbered ID to child tables? You finally 
introduce ‘Keyless Entry’ Antipattern. Think about a query that returns “Art of 
computer programming Vol 1” by Chetan Bhagat by joining Book and Author 
tables 
Nightmare starts if almost all tables have pseudo keys
SQL Antipatterns 
Design Creation Query Application 
Pseudo Key Neat-Freak 
Solution 
Use natural keys as far as possible 
Get over it: Don’t try to renumber a pseudo key. Train the mind to take the 
‘Pseudo Key’ as ‘Pseudo’; it has no business value 
Another argument for reusing the numbers: 
“After three years the ID will reach the maximum number! I don’t want to 
waste values…” 
BIGINT (8 Byte), 263 – 1 = Max. value 9,223,372,036,854,775,807 
1 Day = 86400 Seconds 
1,000 insertions/sec = 106751991167 days ~ 292,471,208 Years 
Note: Pseudo keys are row identifiers; not row numbers
SQL Antipatterns 
References 
SQL Antipatterns – Bill Karwin Applied Mathematics for 
Database Professional – 
Lex de Haan & Toon 
Koppelaars
Questions?
Thank You

More Related Content

What's hot

Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
Mario Sangiorgio
 
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
joaomatosf_
 
Models for hierarchical data
Models for hierarchical dataModels for hierarchical data
Models for hierarchical data
Karwin Software Solutions LLC
 
Extensible Data Modeling
Extensible Data ModelingExtensible Data Modeling
Extensible Data Modeling
Karwin Software Solutions LLC
 
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Christian Schneider
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold
Philip Schwarz
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
Haim Michael
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
Hitesh-Java
 
Clean code
Clean codeClean code
Clean code
ifnu bima
 
An introduction to SQLAlchemy
An introduction to SQLAlchemyAn introduction to SQLAlchemy
An introduction to SQLAlchemy
mengukagan
 
Clean code
Clean code Clean code
Clean code
Achintya Kumar
 
Clean Code
Clean CodeClean Code
Clean Code
ISchwarz23
 
L11 array list
L11 array listL11 array list
L11 array list
teach4uin
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
José Paumard
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
EastBanc Tachnologies
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
Vicente García Díaz
 
Spock Testing Framework - The Next Generation
Spock Testing Framework - The Next GenerationSpock Testing Framework - The Next Generation
Spock Testing Framework - The Next Generation
BTI360
 
Vue-3-Cheat-Sheet.pdf
Vue-3-Cheat-Sheet.pdfVue-3-Cheat-Sheet.pdf
Vue-3-Cheat-Sheet.pdf
LarsHunze1
 
Kotlin presentation
Kotlin presentation Kotlin presentation
Kotlin presentation
MobileAcademy
 

What's hot (20)

Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
 
Models for hierarchical data
Models for hierarchical dataModels for hierarchical data
Models for hierarchical data
 
Extensible Data Modeling
Extensible Data ModelingExtensible Data Modeling
Extensible Data Modeling
 
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Clean code
Clean codeClean code
Clean code
 
An introduction to SQLAlchemy
An introduction to SQLAlchemyAn introduction to SQLAlchemy
An introduction to SQLAlchemy
 
Clean code
Clean code Clean code
Clean code
 
Clean Code
Clean CodeClean Code
Clean Code
 
L11 array list
L11 array listL11 array list
L11 array list
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Spock Testing Framework - The Next Generation
Spock Testing Framework - The Next GenerationSpock Testing Framework - The Next Generation
Spock Testing Framework - The Next Generation
 
Vue-3-Cheat-Sheet.pdf
Vue-3-Cheat-Sheet.pdfVue-3-Cheat-Sheet.pdf
Vue-3-Cheat-Sheet.pdf
 
Kotlin presentation
Kotlin presentation Kotlin presentation
Kotlin presentation
 

Similar to Introduction to SQL Antipatterns

Session #4: Treating Databases as First-Class Citizens in Development
Session #4: Treating Databases as First-Class Citizens in DevelopmentSession #4: Treating Databases as First-Class Citizens in Development
Session #4: Treating Databases as First-Class Citizens in Development
Steve Lange
 
PHX - Session #4 Treating Databases as First-Class Citizens in Development
PHX - Session #4 Treating Databases as First-Class Citizens in DevelopmentPHX - Session #4 Treating Databases as First-Class Citizens in Development
PHX - Session #4 Treating Databases as First-Class Citizens in Development
Steve Lange
 
TechDays Tunisia - Visual Studio & SQL Server, Better Together - Ayman El-Hattab
TechDays Tunisia - Visual Studio & SQL Server, Better Together - Ayman El-HattabTechDays Tunisia - Visual Studio & SQL Server, Better Together - Ayman El-Hattab
TechDays Tunisia - Visual Studio & SQL Server, Better Together - Ayman El-Hattab
Ayman El-Hattab
 
70 433
70 43370 433
Geek Sync | Rewriting Bad SQL Code 101
Geek Sync | Rewriting Bad SQL Code 101Geek Sync | Rewriting Bad SQL Code 101
Geek Sync | Rewriting Bad SQL Code 101
IDERA Software
 
Access 04
Access 04Access 04
Access 04
Alexander Babich
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of Purity
Victor Rentea
 
Avoiding cursors with sql server 2005 tech republic
Avoiding cursors with sql server 2005   tech republicAvoiding cursors with sql server 2005   tech republic
Avoiding cursors with sql server 2005 tech republic
Kaing Menglieng
 
Productive Debugging
Productive DebuggingProductive Debugging
Productive Debugging
iThink
 
Triggers and Stored Procedures
Triggers and Stored ProceduresTriggers and Stored Procedures
Triggers and Stored Procedures
Tharindu Weerasinghe
 
Beyond SQL - Comparing SQL to TypeQL
Beyond SQL - Comparing SQL to TypeQLBeyond SQL - Comparing SQL to TypeQL
Beyond SQL - Comparing SQL to TypeQL
Vaticle
 
SQL Server Development Tools & Processes Using Visual Studio 2010
SQL Server Development Tools & Processes Using Visual Studio 2010 SQL Server Development Tools & Processes Using Visual Studio 2010
SQL Server Development Tools & Processes Using Visual Studio 2010
Ayman El-Hattab
 
Meg bernal insight2014 4219
Meg bernal insight2014 4219Meg bernal insight2014 4219
Meg bernal insight2014 4219
Peter Schouboe
 
Apex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsApex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong Foundations
Salesforce Developers
 
Advanced Index Tuning
Advanced Index TuningAdvanced Index Tuning
Advanced Index Tuning
Quest Software
 
Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
Karwin Software Solutions LLC
 
8 sql injection
8   sql injection8   sql injection
8 sql injection
drewz lin
 
PNWPHP -- What are Databases so &#%-ing Difficult
PNWPHP -- What are Databases so &#%-ing DifficultPNWPHP -- What are Databases so &#%-ing Difficult
PNWPHP -- What are Databases so &#%-ing Difficult
Dave Stokes
 
Professional Code Reviews - Bogdan Gusiev
Professional Code Reviews - Bogdan GusievProfessional Code Reviews - Bogdan Gusiev
Professional Code Reviews - Bogdan Gusiev
Ruby Meditation
 
Sql vs no sql diponkar paul-april 2020-Toronto PASS
Sql vs no sql   diponkar paul-april 2020-Toronto PASSSql vs no sql   diponkar paul-april 2020-Toronto PASS
Sql vs no sql diponkar paul-april 2020-Toronto PASS
Diponkar Paul
 

Similar to Introduction to SQL Antipatterns (20)

Session #4: Treating Databases as First-Class Citizens in Development
Session #4: Treating Databases as First-Class Citizens in DevelopmentSession #4: Treating Databases as First-Class Citizens in Development
Session #4: Treating Databases as First-Class Citizens in Development
 
PHX - Session #4 Treating Databases as First-Class Citizens in Development
PHX - Session #4 Treating Databases as First-Class Citizens in DevelopmentPHX - Session #4 Treating Databases as First-Class Citizens in Development
PHX - Session #4 Treating Databases as First-Class Citizens in Development
 
TechDays Tunisia - Visual Studio & SQL Server, Better Together - Ayman El-Hattab
TechDays Tunisia - Visual Studio & SQL Server, Better Together - Ayman El-HattabTechDays Tunisia - Visual Studio & SQL Server, Better Together - Ayman El-Hattab
TechDays Tunisia - Visual Studio & SQL Server, Better Together - Ayman El-Hattab
 
70 433
70 43370 433
70 433
 
Geek Sync | Rewriting Bad SQL Code 101
Geek Sync | Rewriting Bad SQL Code 101Geek Sync | Rewriting Bad SQL Code 101
Geek Sync | Rewriting Bad SQL Code 101
 
Access 04
Access 04Access 04
Access 04
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of Purity
 
Avoiding cursors with sql server 2005 tech republic
Avoiding cursors with sql server 2005   tech republicAvoiding cursors with sql server 2005   tech republic
Avoiding cursors with sql server 2005 tech republic
 
Productive Debugging
Productive DebuggingProductive Debugging
Productive Debugging
 
Triggers and Stored Procedures
Triggers and Stored ProceduresTriggers and Stored Procedures
Triggers and Stored Procedures
 
Beyond SQL - Comparing SQL to TypeQL
Beyond SQL - Comparing SQL to TypeQLBeyond SQL - Comparing SQL to TypeQL
Beyond SQL - Comparing SQL to TypeQL
 
SQL Server Development Tools & Processes Using Visual Studio 2010
SQL Server Development Tools & Processes Using Visual Studio 2010 SQL Server Development Tools & Processes Using Visual Studio 2010
SQL Server Development Tools & Processes Using Visual Studio 2010
 
Meg bernal insight2014 4219
Meg bernal insight2014 4219Meg bernal insight2014 4219
Meg bernal insight2014 4219
 
Apex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsApex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong Foundations
 
Advanced Index Tuning
Advanced Index TuningAdvanced Index Tuning
Advanced Index Tuning
 
Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
 
8 sql injection
8   sql injection8   sql injection
8 sql injection
 
PNWPHP -- What are Databases so &#%-ing Difficult
PNWPHP -- What are Databases so &#%-ing DifficultPNWPHP -- What are Databases so &#%-ing Difficult
PNWPHP -- What are Databases so &#%-ing Difficult
 
Professional Code Reviews - Bogdan Gusiev
Professional Code Reviews - Bogdan GusievProfessional Code Reviews - Bogdan Gusiev
Professional Code Reviews - Bogdan Gusiev
 
Sql vs no sql diponkar paul-april 2020-Toronto PASS
Sql vs no sql   diponkar paul-april 2020-Toronto PASSSql vs no sql   diponkar paul-april 2020-Toronto PASS
Sql vs no sql diponkar paul-april 2020-Toronto PASS
 

Recently uploaded

❣VIP Call Girls Chennai 💯Call Us 🔝 7737669865 🔝💃Independent Chennai Escorts S...
❣VIP Call Girls Chennai 💯Call Us 🔝 7737669865 🔝💃Independent Chennai Escorts S...❣VIP Call Girls Chennai 💯Call Us 🔝 7737669865 🔝💃Independent Chennai Escorts S...
❣VIP Call Girls Chennai 💯Call Us 🔝 7737669865 🔝💃Independent Chennai Escorts S...
jasodak99
 
Optimizing Feldera: Integrating Advanced UDFs and Enhanced SQL Functionality ...
Optimizing Feldera: Integrating Advanced UDFs and Enhanced SQL Functionality ...Optimizing Feldera: Integrating Advanced UDFs and Enhanced SQL Functionality ...
Optimizing Feldera: Integrating Advanced UDFs and Enhanced SQL Functionality ...
mparmparousiskostas
 
Do People Really Know Their Fertility Intentions? Correspondence between Sel...
Do People Really Know Their Fertility Intentions?  Correspondence between Sel...Do People Really Know Their Fertility Intentions?  Correspondence between Sel...
Do People Really Know Their Fertility Intentions? Correspondence between Sel...
Xiao Xu
 
Classifying Shooting Incident Fatality in New York project presentation
Classifying Shooting Incident Fatality in New York project presentationClassifying Shooting Incident Fatality in New York project presentation
Classifying Shooting Incident Fatality in New York project presentation
Boston Institute of Analytics
 
Call Girls Lucknow 8923113531 Independent Call Girl Service in Lucknow
Call Girls Lucknow 8923113531 Independent Call Girl Service in LucknowCall Girls Lucknow 8923113531 Independent Call Girl Service in Lucknow
Call Girls Lucknow 8923113531 Independent Call Girl Service in Lucknow
hiju9823
 
Royal-Class Call Girls Thane🌹9967824496🌹369+ call girls @₹6K-18K/full night cash
Royal-Class Call Girls Thane🌹9967824496🌹369+ call girls @₹6K-18K/full night cashRoyal-Class Call Girls Thane🌹9967824496🌹369+ call girls @₹6K-18K/full night cash
Royal-Class Call Girls Thane🌹9967824496🌹369+ call girls @₹6K-18K/full night cash
Ak47
 
machine learning notes by Andrew Ng and Tengyu Ma
machine learning notes by Andrew Ng and Tengyu Mamachine learning notes by Andrew Ng and Tengyu Ma
machine learning notes by Andrew Ng and Tengyu Ma
Vijayabaskar Uthirapathy
 
Erotic Call Girls Hyderabad🫱9352988975🫲 High Quality Call Girl Service Right ...
Erotic Call Girls Hyderabad🫱9352988975🫲 High Quality Call Girl Service Right ...Erotic Call Girls Hyderabad🫱9352988975🫲 High Quality Call Girl Service Right ...
Erotic Call Girls Hyderabad🫱9352988975🫲 High Quality Call Girl Service Right ...
meenusingh4354543
 
Call Girls Hyderabad (india) ☎️ +91-7426014248 Hyderabad Call Girl
Call Girls Hyderabad  (india) ☎️ +91-7426014248 Hyderabad  Call GirlCall Girls Hyderabad  (india) ☎️ +91-7426014248 Hyderabad  Call Girl
Call Girls Hyderabad (india) ☎️ +91-7426014248 Hyderabad Call Girl
sapna sharmap11
 
AI WITH THE HELP OF NAGALAND CAN WIN. DOWNLOAD NOW
AI WITH THE HELP OF NAGALAND CAN WIN. DOWNLOAD NOWAI WITH THE HELP OF NAGALAND CAN WIN. DOWNLOAD NOW
AI WITH THE HELP OF NAGALAND CAN WIN. DOWNLOAD NOW
arash10gamer
 
🔥College Call Girls Kolkata 💯Call Us 🔝 8094342248 🔝💃Top Class Call Girl Servi...
🔥College Call Girls Kolkata 💯Call Us 🔝 8094342248 🔝💃Top Class Call Girl Servi...🔥College Call Girls Kolkata 💯Call Us 🔝 8094342248 🔝💃Top Class Call Girl Servi...
🔥College Call Girls Kolkata 💯Call Us 🔝 8094342248 🔝💃Top Class Call Girl Servi...
rukmnaikaseen
 
Hyderabad Call Girls Service 🔥 9352988975 🔥 High Profile Call Girls Hyderabad
Hyderabad Call Girls Service 🔥 9352988975 🔥 High Profile Call Girls HyderabadHyderabad Call Girls Service 🔥 9352988975 🔥 High Profile Call Girls Hyderabad
Hyderabad Call Girls Service 🔥 9352988975 🔥 High Profile Call Girls Hyderabad
binna singh$A17
 
satta matka Dpboss guessing Kalyan matka Today Kalyan Panel Chart Kalyan Jodi...
satta matka Dpboss guessing Kalyan matka Today Kalyan Panel Chart Kalyan Jodi...satta matka Dpboss guessing Kalyan matka Today Kalyan Panel Chart Kalyan Jodi...
satta matka Dpboss guessing Kalyan matka Today Kalyan Panel Chart Kalyan Jodi...
#kalyanmatkaresult #dpboss #kalyanmatka #satta #matka #sattamatka
 
❻❸❼⓿❽❻❷⓿⓿❼KALYAN MATKA CHART FINAL OPEN JODI PANNA FIXXX DPBOSS MATKA RESULT ...
❻❸❼⓿❽❻❷⓿⓿❼KALYAN MATKA CHART FINAL OPEN JODI PANNA FIXXX DPBOSS MATKA RESULT ...❻❸❼⓿❽❻❷⓿⓿❼KALYAN MATKA CHART FINAL OPEN JODI PANNA FIXXX DPBOSS MATKA RESULT ...
❻❸❼⓿❽❻❷⓿⓿❼KALYAN MATKA CHART FINAL OPEN JODI PANNA FIXXX DPBOSS MATKA RESULT ...
#kalyanmatkaresult #dpboss #kalyanmatka #satta #matka #sattamatka
 
🔥Call Girl Price Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servic...
🔥Call Girl Price Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servic...🔥Call Girl Price Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servic...
🔥Call Girl Price Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servic...
Ak47
 
Delhi Call Girls Karol Bagh 👉 9711199012 👈 unlimited short high profile full ...
Delhi Call Girls Karol Bagh 👉 9711199012 👈 unlimited short high profile full ...Delhi Call Girls Karol Bagh 👉 9711199012 👈 unlimited short high profile full ...
Delhi Call Girls Karol Bagh 👉 9711199012 👈 unlimited short high profile full ...
mona lisa $A12
 
🔥Night Call Girls Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servi...
🔥Night Call Girls Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servi...🔥Night Call Girls Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servi...
🔥Night Call Girls Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servi...
yuvishachadda
 
一比一原版(sfu学位证书)西蒙弗雷泽大学毕业证如何办理
一比一原版(sfu学位证书)西蒙弗雷泽大学毕业证如何办理一比一原版(sfu学位证书)西蒙弗雷泽大学毕业证如何办理
一比一原版(sfu学位证书)西蒙弗雷泽大学毕业证如何办理
gebegu
 
Interview Methods - Marital and Family Therapy and Counselling - Psychology S...
Interview Methods - Marital and Family Therapy and Counselling - Psychology S...Interview Methods - Marital and Family Therapy and Counselling - Psychology S...
Interview Methods - Marital and Family Therapy and Counselling - Psychology S...
PsychoTech Services
 
A review of I_O behavior on Oracle database in ASM
A review of I_O behavior on Oracle database in ASMA review of I_O behavior on Oracle database in ASM
A review of I_O behavior on Oracle database in ASM
Alireza Kamrani
 

Recently uploaded (20)

❣VIP Call Girls Chennai 💯Call Us 🔝 7737669865 🔝💃Independent Chennai Escorts S...
❣VIP Call Girls Chennai 💯Call Us 🔝 7737669865 🔝💃Independent Chennai Escorts S...❣VIP Call Girls Chennai 💯Call Us 🔝 7737669865 🔝💃Independent Chennai Escorts S...
❣VIP Call Girls Chennai 💯Call Us 🔝 7737669865 🔝💃Independent Chennai Escorts S...
 
Optimizing Feldera: Integrating Advanced UDFs and Enhanced SQL Functionality ...
Optimizing Feldera: Integrating Advanced UDFs and Enhanced SQL Functionality ...Optimizing Feldera: Integrating Advanced UDFs and Enhanced SQL Functionality ...
Optimizing Feldera: Integrating Advanced UDFs and Enhanced SQL Functionality ...
 
Do People Really Know Their Fertility Intentions? Correspondence between Sel...
Do People Really Know Their Fertility Intentions?  Correspondence between Sel...Do People Really Know Their Fertility Intentions?  Correspondence between Sel...
Do People Really Know Their Fertility Intentions? Correspondence between Sel...
 
Classifying Shooting Incident Fatality in New York project presentation
Classifying Shooting Incident Fatality in New York project presentationClassifying Shooting Incident Fatality in New York project presentation
Classifying Shooting Incident Fatality in New York project presentation
 
Call Girls Lucknow 8923113531 Independent Call Girl Service in Lucknow
Call Girls Lucknow 8923113531 Independent Call Girl Service in LucknowCall Girls Lucknow 8923113531 Independent Call Girl Service in Lucknow
Call Girls Lucknow 8923113531 Independent Call Girl Service in Lucknow
 
Royal-Class Call Girls Thane🌹9967824496🌹369+ call girls @₹6K-18K/full night cash
Royal-Class Call Girls Thane🌹9967824496🌹369+ call girls @₹6K-18K/full night cashRoyal-Class Call Girls Thane🌹9967824496🌹369+ call girls @₹6K-18K/full night cash
Royal-Class Call Girls Thane🌹9967824496🌹369+ call girls @₹6K-18K/full night cash
 
machine learning notes by Andrew Ng and Tengyu Ma
machine learning notes by Andrew Ng and Tengyu Mamachine learning notes by Andrew Ng and Tengyu Ma
machine learning notes by Andrew Ng and Tengyu Ma
 
Erotic Call Girls Hyderabad🫱9352988975🫲 High Quality Call Girl Service Right ...
Erotic Call Girls Hyderabad🫱9352988975🫲 High Quality Call Girl Service Right ...Erotic Call Girls Hyderabad🫱9352988975🫲 High Quality Call Girl Service Right ...
Erotic Call Girls Hyderabad🫱9352988975🫲 High Quality Call Girl Service Right ...
 
Call Girls Hyderabad (india) ☎️ +91-7426014248 Hyderabad Call Girl
Call Girls Hyderabad  (india) ☎️ +91-7426014248 Hyderabad  Call GirlCall Girls Hyderabad  (india) ☎️ +91-7426014248 Hyderabad  Call Girl
Call Girls Hyderabad (india) ☎️ +91-7426014248 Hyderabad Call Girl
 
AI WITH THE HELP OF NAGALAND CAN WIN. DOWNLOAD NOW
AI WITH THE HELP OF NAGALAND CAN WIN. DOWNLOAD NOWAI WITH THE HELP OF NAGALAND CAN WIN. DOWNLOAD NOW
AI WITH THE HELP OF NAGALAND CAN WIN. DOWNLOAD NOW
 
🔥College Call Girls Kolkata 💯Call Us 🔝 8094342248 🔝💃Top Class Call Girl Servi...
🔥College Call Girls Kolkata 💯Call Us 🔝 8094342248 🔝💃Top Class Call Girl Servi...🔥College Call Girls Kolkata 💯Call Us 🔝 8094342248 🔝💃Top Class Call Girl Servi...
🔥College Call Girls Kolkata 💯Call Us 🔝 8094342248 🔝💃Top Class Call Girl Servi...
 
Hyderabad Call Girls Service 🔥 9352988975 🔥 High Profile Call Girls Hyderabad
Hyderabad Call Girls Service 🔥 9352988975 🔥 High Profile Call Girls HyderabadHyderabad Call Girls Service 🔥 9352988975 🔥 High Profile Call Girls Hyderabad
Hyderabad Call Girls Service 🔥 9352988975 🔥 High Profile Call Girls Hyderabad
 
satta matka Dpboss guessing Kalyan matka Today Kalyan Panel Chart Kalyan Jodi...
satta matka Dpboss guessing Kalyan matka Today Kalyan Panel Chart Kalyan Jodi...satta matka Dpboss guessing Kalyan matka Today Kalyan Panel Chart Kalyan Jodi...
satta matka Dpboss guessing Kalyan matka Today Kalyan Panel Chart Kalyan Jodi...
 
❻❸❼⓿❽❻❷⓿⓿❼KALYAN MATKA CHART FINAL OPEN JODI PANNA FIXXX DPBOSS MATKA RESULT ...
❻❸❼⓿❽❻❷⓿⓿❼KALYAN MATKA CHART FINAL OPEN JODI PANNA FIXXX DPBOSS MATKA RESULT ...❻❸❼⓿❽❻❷⓿⓿❼KALYAN MATKA CHART FINAL OPEN JODI PANNA FIXXX DPBOSS MATKA RESULT ...
❻❸❼⓿❽❻❷⓿⓿❼KALYAN MATKA CHART FINAL OPEN JODI PANNA FIXXX DPBOSS MATKA RESULT ...
 
🔥Call Girl Price Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servic...
🔥Call Girl Price Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servic...🔥Call Girl Price Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servic...
🔥Call Girl Price Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servic...
 
Delhi Call Girls Karol Bagh 👉 9711199012 👈 unlimited short high profile full ...
Delhi Call Girls Karol Bagh 👉 9711199012 👈 unlimited short high profile full ...Delhi Call Girls Karol Bagh 👉 9711199012 👈 unlimited short high profile full ...
Delhi Call Girls Karol Bagh 👉 9711199012 👈 unlimited short high profile full ...
 
🔥Night Call Girls Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servi...
🔥Night Call Girls Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servi...🔥Night Call Girls Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servi...
🔥Night Call Girls Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Escorts Servi...
 
一比一原版(sfu学位证书)西蒙弗雷泽大学毕业证如何办理
一比一原版(sfu学位证书)西蒙弗雷泽大学毕业证如何办理一比一原版(sfu学位证书)西蒙弗雷泽大学毕业证如何办理
一比一原版(sfu学位证书)西蒙弗雷泽大学毕业证如何办理
 
Interview Methods - Marital and Family Therapy and Counselling - Psychology S...
Interview Methods - Marital and Family Therapy and Counselling - Psychology S...Interview Methods - Marital and Family Therapy and Counselling - Psychology S...
Interview Methods - Marital and Family Therapy and Counselling - Psychology S...
 
A review of I_O behavior on Oracle database in ASM
A review of I_O behavior on Oracle database in ASMA review of I_O behavior on Oracle database in ASM
A review of I_O behavior on Oracle database in ASM
 

Introduction to SQL Antipatterns

  • 2. Design Patterns • A solution to a recurring problem, in a context • Abstracts a recurring design structure • Distills design experience • Pattern consists of a problem and a solution
  • 3. Antipatterns • A solution to a recurring problem, in a context • Generates problems than solution • Go from problem to bad solution • Antipattern consists of two solutions • One which is beneficial • One which is problematic
  • 4. Why learning antipatterns? “Identifying bad practices can be as valuable as identifying good practices” - Ward Cunningham Antipatterns identify and categorize the common mistakes in software practice “If debugging is the process of removing bugs, then programming must be the process of putting them in.” – Edsger W. Dijkstra
  • 5. SQL Antipatterns Database Design Database Creation CREATE TABLE BugsProducts ( bug_id INTEGER REFERENCES Bugs, product VARCHAR(100) REFERENCES Products, PRIMARY KEY (bug_id, product) ); Query SELECT b.product, COUNT(*) FROM BugsProducts AS b GROUP BY b.product; Application SELECT b.product, COUNT(*) FROM BugsProducts AS b GROUP BY b.product;
  • 6. SQL Antipatterns Design Creation Query Application Jaywalking Cross walking Jaywalking Example Problem Storing list of authors for a book… Book Name Authors Code Complete Steve McConnell Design Patterns Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides Intro. to Automata Theory Jeffrey Ullman, John Hopcroft Assigning role based menu access… Menu Name Role Accessibility Reset Password Admin Account Heads Senior Accountant, Accounts Manager YTD Sales Report CFO, Sales Manager, Sales Rep
  • 7. SQL Antipatterns Design Creation Query Application Jaywalking Objective 1. Avoid Intersection table 2. Avoid joins and thus minimize query plan complexity
  • 8. SQL Antipatterns Design Creation Query Application Jaywalking Implementation CREATE TABLE Menu ( MenuID INT, Menu VARCHAR(50), Module VARCHAR(50), AccessibileTo VARCHAR(500), CONSTRAINT PK_Menu PRIMARY KEY CLUSTERED ( MenuID ) ) GO INSERT INTO Menu (MenuID, Menu, Module, AccessibileTo) VALUES (1, 'Reset Password', 'Administration', 'Admin'), (2, 'Account Heads', 'Finance', 'Senior Accountant, Accounts Manager'), (3, 'YTD Sales Report', 'Report', 'CFO, Sales Manager, Sales Rep');
  • 9. SQL Antipatterns Design Creation Query Application Jaywalking New problems… Violation of First normal form Cannot chose a right data type – You can enter Admin, Sales Rep, 1, 2, banana Cannot use foreign key constraints – No referential integrity Cannot enforce uniqueness – 1, 2, 3, 4, 3, 3, 2 Cannot easily modify the values in the column What happens if the length of values exceeds the column limit? How do you search for menus accessible for Admin and CFO? No indexing is possible How many roles have access to Current Year Budget Reports? Aggregation is difficult How do you join the table with Role table? Storing integer number as character take space than storing as integer? Workarounds include splitting functions that will be inefficient?
  • 10. SQL Antipatterns Design Creation Query Application Jaywalking Solution : Create an intersection table Menu MenuAccess Role Intersection table CREATE TABLE dbo.Menu ( MenuID INT, Menu VARCHAR(50), Module VARCHAR(50) CONSTRAINT PK_Menu PRIMARY KEY CLUSTERED ( MenuID ) ) GO CREATE TABLE dbo.Role ( RoleID INT, Name VARCHAR(50), CreatedDate DATETIME, CONSTRAINT PK_Role PRIMARY KEY CLUSTERED ( RoleID ) ) GO CREATE TABLE dbo.MenuAccess ( MenuAccessID INT, MenuID INT, RoleID INT, CONSTRAINT FK_MenuAccess_Menu FOREIGN KEY (MenuID) REFERENCES Menu (MenuID), CONSTRAINT FK_MenuAccess_Role FOREIGN KEY (RoleID) REFERENCES dbo.Role (RoleID) ) GO
  • 11. SQL Antipatterns Design Creation Query Application Keyless Entry Example Problem I need a Supplier and a Invoice table… Invoice table stores number from Supplier table, to identify the supplier; however….. I don’t want to make the design complex…. The sentence I’m about to tell you is a secret ! … I don’t like keys ! Keys and Constraints limit flexibility!
  • 12. SQL Antipatterns Design Creation Query Application Keyless Entry Objective 1. Avoid Update/Delete/Insert conflicts 2. Avoid complexity around foreign key constraints
  • 13. SQL Antipatterns Design Creation Query Application Keyless Entry Implementation Create tables without any FOREIGN KEY constraints
  • 14. SQL Antipatterns Design Creation Query Application Keyless Entry New problems… Breaking the foundation of relational database - Constraints Introduce meaningless data – Authors without any books or Orders without customers Cannot utilize the query optimizations due to constraints – Some RDBMS utilizes FOREIGN KEY and CHECK constraints to optimize queries Need to implement custom solutions to check integrity on a later stage Forced to implement periodic checks to find orphan rows
  • 15. SQL Antipatterns Design Creation Query Application Keyless Entry Solution : Implement referential integrity through FOREIGN KEY constraints Use cascading referential integrity constraints. CREATE TABLE dbo.MenuAccess ( MenuAccessID INT, MenuID INT, RoleID INT, CONSTRAINT FK_MenuAccess_Menu FOREIGN KEY (MenuID) REFERENCES dbo.Menu (MenuID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FK_MenuAccess_Role FOREIGN KEY (RoleID) REFERENCES dbo.Role (RoleID) ON DELETE SET NULL ON UPDATE CASCADE, ) GO You can even disable and enable FOREIGN KEY, if needed. -- Disable FOREIGN KEY ALTER TABLE MenuAccess NOCHECK CONSTRAINT FK_MenuAccess_Menu; -- Enable FOREIGN KEY ALTER TABLE MenuAccess WITH CHECK CHECK CONSTRAINT FK_MenuAccess_Menu;
  • 16. SQL Antipatterns Design Creation Query Application ‘31 Flavors’ Example Problem Our bug tracking software supports only three bug statuses NEW INPROGRESS FIXED This will never change (I guess!)
  • 17. SQL Antipatterns Design Creation Query Application ‘31 Flavors’ Objective 1. Restrict a column’s values to a fixed set of values 2. Column never contains an invalid entry 3. Simplifies usage and query development
  • 18. SQL Antipatterns Design Creation Query Application ‘31 Flavors’ Implementation CREATE TABLE dbo.Bugs ( BugID INT, ModuleID INT, Description VARCHAR(200), -- Other columns BugStatus VARCHAR(20), CONSTRAINT CHK_BugStatus CHECK (BugStatus IN ('NEW' , 'IN PROGRESS' , 'FIXED')) ); GO
  • 19. SQL Antipatterns Design Creation Query Application ‘31 Flavors’ New problems… What are the available status values? SELECT DISTINCT BugStatus FROM dbo.Bugs; After few months, the QA team decides to add a new status ‘Duplicate’. How do you do that? Later the team has instructed to change ‘Fixed’ status to ‘Resolved’
  • 20. SQL Antipatterns Design Creation Query Application ‘31 Flavors’ Solution : Create a lookup table and use DRI CREATE TABLE dbo.BugStatus ( BugStatusID INT, Status VARCHAR(20), Description VARCHAR(100), CONSTRAINT PK_BugStatus PRIMARY KEY CLUSTERED (BugStatusID) ) GO CREATE TABLE dbo.Bugs ( -- Other columns BugStatusID INT, CONSTRAINT FK_Bugs_BugStatus FOREIGN KEY (BugStatusID) REFERENCES dbo.BugStatus (BugStatusID) ); GO INSERT INTO dbo.BugStatus (BugStatusID, Status, Description) VALUES (1, 'NEW', 'Once again a new bug reported'), (2, 'IN PROGRESS', 'Team is working hard on this'), (3, 'FIXED', 'The issues fixed for the time being!');
  • 21. SQL Antipatterns Design Creation Query Application Fear of Unknown "There are things known, and there are things unknown, And in between are the Doors." ~ Jim Morrison Example Problem Our library stores information on books and periodicals Both have a name, publisher, language, and number of pages However ISBN is applicable to books and ISSN is for periodicals.
  • 22. SQL Antipatterns Design Creation Query Application Fear of Unknown Objective Storing values that are not available or not applicable
  • 23. SQL Antipatterns Design Creation Query Application Fear of Unknown Implementation CREATE TABLE dbo.Collection ( ID INT NOT NULL, Name VARCHAR(100) NOT NULL, Year INT NOT NULL, PublisherID INT NOT NULL, -- Applicable to Books Edition INT NULL, ISBN VARCHAR(20) NULL, Binding VARCHAR(20) NULL CHECK Binding IN ('HARDCOVER', 'PAPERBACK')), -- Applicable to periodicals FrequencyID INT NULL REFERENCES dbo.Frequency (FrequencyID), Volume INT NULL, Issue INT NULL, ISSN VARCHAR(10) NULL ) GO
  • 24. SQL Antipatterns Design Creation Query Application Fear of Unknown New problems… ID Name Year PublisherID Edition ISBN Binding FrequencyID Volume Issue ISSN 1 Introduction to Algorithms 1990 2 3978-0-262-03384-8 PAPERBACK 2Code Complete 1993 5 1 978-1-55615-484-3 PAPERBACK 3 Dr. Dobb's Journal 2009 12 3 34 2 1044-789X 4The C Programming Language 1978 1 10-262-51087-2 PAPERBACK 5 SQL Server Pro 1999 22 3 7 3 1522-2187 What is the result of SELECT ID FROM dbo.Collection WHERE FrequencyID != 3;? Ans. (0) rows affected What is the result of SELECT Name + ‘,‘ + Edition + ‘(‘ + ISSN + ‘)’ FROM dbo.Collection WHERE ID = 2; Ans. NULL What is the result of SELECT COUNT(Volume) FROM dbo.Collection;? Ans. 2
  • 25. SQL Antipatterns Design Creation Query Application Fear of Unknown Understanding NULL … in expression … in Boolean expression Expression Expected Actual NULL = 0 TRUE Unknown NULL = 12345 FALSE Unknown NULL <> 12345 TRUE Unknown NULL + 12345 12345 Unknown NULL + ‘ABC’ ABC Unknown NULL = NULL TRUE Unknown NULL <> NULL FALSE Unknown Expression Expected Actual NULL AND TRUE FALSE Unknown NULL AND FALSE FALSE FALSE NULL OR FALSE FALSE Unknown NULL OR TRUE TRUE TRUE NOT (NULL) TRUE Unknown
  • 26. SQL Antipatterns Design Creation Query Application Fear of Unknown Understanding NULL NULL is not a value in a column NULL is a marker/construct in SQL for representing missing information "...it follows that a “type” that “contains a null” isn’t a type, a “tuple” that “contains a null” isn’t a tuple, a “relation” that “contains a null” isn’t a relation, and a “relvar” that contains a null isn’t a relvar. It follows further that nulls do serious violence to the relational model, and this dictionary therefore has very little to say regarding most null-related concepts“ – C . J. Date – The Relational Database Dictionary
  • 27. SQL Antipatterns Design Creation Query Application Fear of Unknown Solution: Avoid usage of NULL as far as possible There are three reasons for NULL creep in to database table… Inapplicable NULL The ISSN of periodical is inapplicable to a book Solution: Design specialized tables with applicable columns. Create a Book table and a Periodical table Inapplicable NULL should be avoided Not yet applicable NULL The Number of copies of the book is currently not available, but will soon be available Solution: Give a default value until the value is available e.g.: ISO scheme for sex: 0 = UNKNOWN 1 = MALE 2 = FEMALE 9 = NOT APPLICABLE Nice to know NULL The comment for a book has no business value and will only used for reporting Solution: This column can contain the marker NULL.
  • 28. SQL Antipatterns Design Creation Query Application Pseudo Key Neat-Freak …D oor ythoius plikaett tehrins… p?attern…? 1 2 3 89 4 144 5 233 6 21 7 34 8 55 9 13 8 5 10 11 12 Example Problem I used auto generated pseudo key for BookID in Book table Today morning when I query the table I found gaps in BookID numbers…! Books are missing! How the database miss it! Is that a bug! Clean it up and make it sequential! Born of a Pseudo Key Neat-Freak
  • 29. SQL Antipatterns Design Creation Query Application Pseudo Key Neat-Freak Objective 1. Pseudo key numbers should always be in sequential order 2. There should not be any gaps between two adjacent pseudo key numbers
  • 30. SQL Antipatterns Design Creation Query Application Pseudo Key Neat-Freak Implementation 1. Do not use auto generating numbers; instead write custom queries to find the next number for the table 2. Periodically run maintenance scripts to fill the gaps Gaps and Islands – Itzik Ben-Gan (MVP Deep Dives Vol. 1) 10,000,000 rows with 10,000 gaps in every 1,000 rows
  • 31. SQL Antipatterns Design Creation Query Application Pseudo Key Neat-Freak New problems… Any custom solution will cause locking and concurrency issues in application Gap filling algorithms are time consuming and resource intensive What about missed the propagation of renumbered ID to child tables? You finally introduce ‘Keyless Entry’ Antipattern. Think about a query that returns “Art of computer programming Vol 1” by Chetan Bhagat by joining Book and Author tables Nightmare starts if almost all tables have pseudo keys
  • 32. SQL Antipatterns Design Creation Query Application Pseudo Key Neat-Freak Solution Use natural keys as far as possible Get over it: Don’t try to renumber a pseudo key. Train the mind to take the ‘Pseudo Key’ as ‘Pseudo’; it has no business value Another argument for reusing the numbers: “After three years the ID will reach the maximum number! I don’t want to waste values…” BIGINT (8 Byte), 263 – 1 = Max. value 9,223,372,036,854,775,807 1 Day = 86400 Seconds 1,000 insertions/sec = 106751991167 days ~ 292,471,208 Years Note: Pseudo keys are row identifiers; not row numbers
  • 33. SQL Antipatterns References SQL Antipatterns – Bill Karwin Applied Mathematics for Database Professional – Lex de Haan & Toon Koppelaars
  翻译: