SlideShare uma empresa Scribd logo
1 de 39
SQL START!
ANCONA, 28 SETTEMBRE 2012
SQL START!
ANCONA, 28 SETTEMBRE 2012
SQL Server Worst Practices
Gianluca Sartori
gianluca.sartori@sqlconsulting.it
Tecnosistemi Marche
Thanks to our sponsors:
#sqlstart
Gianluca Sartori
• Independent SQL Server
consultant
• Works with SQL Server since version 7
• MCTS, MCITP, MCT
• DBA @ Scuderia Ferrari
Agenda
• Best practices or Worst practices?
• What can wrong?
– Design
– Development
– Installation
– Administration
Disclaimer:
• Not everything is black or white
• «It depends» is the most likely answer
There are edge cases when one of these worst
practices is the only possible solution
Best Practices vs. Worst Practices
• Why Best Practices are not enough
– Too many
– No time
– Lack of experience
– Not clear what happens if we don’t follow them
• Why Worst Practices help
– They show the mistakes to avoid
– We can learn from someone else’s mistakes
Worst Practices Areas
Design Development Installation Administration
Schema design
Naming
Data Types
Environment HW validation
OS configuration
SQL installation
Recovery
Security
Capacity
Performance
Monitoring
Code
Test
Schema Design
• Not normalizing the schema
– 1NF:
A key, atomic attributes only
– 2NF:
Every attribute depends on the whole key
– 3NF:
Every attribute depends only on the key
«The key, the whole key, nothing but the key,
so help me Codd»
Clues of denormalization
• Repeating data  redundancies
• Inconsistent data between tables anomalies
• Data separated by «,»
• Ex: john@gmail.com, john@business.com
• Structired data in «notes» columns
• Columns with a numeric suffix
– Ex: Zone1, Zone2, Zone3 …
Schema Design Worst Practices
• No Primary Key o surrogate keys only
– «Id» is not the only possible key!
• No Foreign Keys
– They’re «awkward»
• No CHECK constraint
– The application will guarantee consistency…
• Wrong data types
– Zip code, Telephone Number
– Dates saved as strings
• Use of NULL where not necessary
• Use of «dummy» data (ex: ‘.’ , 0)
Schema Design Worst Practices
• Inconsistent naming conventions
– Plural o singular?
– Italian / English
– Hungarian Notation
• tbl…
• vw...
• User objects with reserved system names
• Use of the sp_ prefix
– … less problematic than it might seem!
Lookup Tables
Orders
PK order_id int
order_date datetime
FK2 customer_id int
FK1 status_id char(2)
FK3 priority_id tinyint
Order_Status
PK status_id char(2)
status_description nvarchar(50)
Customers
PK customer_id int
name varchar(100)
address varchar(50)
ZIP char(5)
city nvarchar(50)
FK2 state_id char(2)
FK1 country_id char(3)
Countries
PK country_id char(3)
description nvarchar(50)
States
PK state_id char(2)
description nvarchar(50)
Order_Priorities
PK priority_id tinyint
priority_description nvarchar(50)
One lookup table for each attribute
OTLT: One True Lookup Table
Orders
PK order_id int
order_date datetime
FK1 customer_id int
status_id char(2)
priority_id tinyint
Customers
PK customer_id int
name nvarchar(100)
address nvarchar(50)
ZIP char(5)
city nvarchar(50)
state_id char(2)
country_id char(3)
LookupTable
PK table_name sysname
PK lookup_code nvarchar(500)
lookup_description nvarchar(4000)
CREATE TABLE LookupTable (
table_name sysname,
lookup_code nvarchar(500),
lookup_description nvarchar(4000)
)
One lookup table for all attributes
OTLT: One True Lookup Table
• No Foreign Keys
• Generic data types  nvarchar(?)
– Implicit Conversions
• CHECK constraints are hard to define
• Locking
CHECK(
CASE
WHEN lookup_code = 'states' AND lookup_code LIKE '[A-Z][A-Z]' THEN 1
WHEN lookup_code = 'priorities' AND lookup_code LIKE '[0-9]' THEN 1
WHEN lookup_code = 'countries' AND lookup_code LIKE '[0-9][0-9][0-9]' THEN 1
WHEN lookup_code = 'status' AND lookup_code LIKE '[A-Z][A-Z]' THEN 1
ELSE 0
END = 1
)
EAV: Entity, Attribute, Value
Customers
PK customer_id int
name nvarchar(100)
address nvarchar(50)
ZIP char(5)
city nvarchar(50)
state_id char(2)
country_id char(3)
AttributeNames
PK attribute_id int
PK,FK1 entity_id int
attribute_name nvarchar(128)
AttributeValues
PK,FK1 attribute_id int
PK,FK1 entity_id int
PK,FK2,FK3 id int
value nvarchar(4000)
Entities
PK entity_id int
entity_name nvarchar(128)
Orders
PK order_id int
order_date datetime
customer_id int
status_id char(2)
priority_id tinyint
EAV: Entity, Attribute, Value
• Disadvantages:
– Generic data types  Ex: varchar(4000)
– No Foreign Keys
– No CHECK constraints
– Multiple accesses to the same table
• One access per attribute
• Advantages
– Dynamic schema: no need to alter the database
• Replication, distributed environments
EAV: Entity, Attribute, Value
• Workaround:
– PIVOT / Crosstab
– View + INSTEAD OF triggers
• Alternatives:
– SPARSE columns
– XML
– Key-value store databases
• Azure Table storage, Redis
– Document-oriented databases
• MongoDB, RavenDB
DEMO:
EAV Design
Development Worst Practices
Development Environment
• No database schema versioning
• No abstraction level
– Views, Functions, Stored Procedures
• Development with sysadmin privileges
– In produzione it won’t be sysadmin!
Development Worst Practices
Code
• No transactions
• No error handling
– @@ERROR is a thing of the past!
• Wrong isolation levels
– NOLOCK = no consistency!
• SELECT *
• Dynamic SQL with hardcoded literals
• Code vulnerable to SQL injection
Development Worst Practices
Test
• Not testing all the code
– Representative data volumes
• Test in production
– Can alter production data
– Interferes with production users
• Test in development environment
– Useful at most for unit tests
Installation Worst Practices
• Using inadequate or unbalanced HW
• Installing accepting all the defaults
– Data files on the system drive!
• Installing unused components
• Installing multiple services on the same
machine
I/O Worst Practices
• Choosing a wrong RAID level
– RAID 0 offers no protection!
• Planning storage with capacity in mind
• Partition misalignment
• Using the default allocation unit (4Kb)
What does a database need?
Brent Ozar
Administration Worst Practices
Backup and Recovery
• No backup
– With FULL recovery it’s a timebomb
– Ignoraring RPO and RTO
• No test restores
• No consistency checks
– DBCC REPAIR_ALLOW_DATA_LOSS
Our responsibility is to perform restores, not backups!
Administration Worst Practices
Security
• Too many sysadmin
• Using SQL Authentication
– Weak passwords
• 123
• P4$$w0rd
• Same as username
• No auditing
Administration Worst Practices
Capacity
• Not checking disk space
– No space left = database halted!
– Am I taking backups?
• Relying on autogrow
• Not presizing tempdb
– Different file size = striping penalty
Administration Worst Practices
Maintenance
• Not maintaining indexes and statistics
• Using catch-all maintenance plans
• Updating statistics after rebuilding indexes
Performance Tuning
Performance Worst Practices
Query Optimization
RBAR: Row By Agonizing Row
– Cursors
– WHILE loops
– App-side cursors
– Scalar and multi-statement functions
Jeff Moden
Let’s use set-based code
The optimizer knows better
Performance Worst Practices
Query Optimization
• One query to rule them all
– The optimizer is good, not perfect
– «divide et impera» delivers better performance
• DISTINCT for all queries
• Query HINTs
Performance Worst Practices
Indexing
• Accepting all suggestions from Tuning Advisor
• Duplicate indexes
• An index for each column
– Indexes are not for free!
• Suboptimal Clustered Index
– Unique
– Small
– Unchanging
– Ever increasing or decreasing
Prefer NEWSEQUENTIALID()
over NEWID()
Performance Worst Practices
Server Tuning
• «Throwing HW» at the problem
– A faster machine won’t fix structural issues
• Using «advanced» options without testing
– NT Fibers (lightweight pooling)
– Priority Boost
Administration Worst Practices
Monitoring
• Reactive paradigm (no monitoring)
• Lack of alerting
– Severity > 16
• Too much noise in alerts
– Everybody will just ignore them altogether
Resources
Free Tool:
Best Practices Analyzer
• Highlights configuration parameters that don’t
comply with best practices
• Highlights potential problems
• Offers recommendations
http://www.microsoft.com/en-us/download/details.aspx?id=15289
Risorse
Free e-book:
Troubleshooting
SQL Server
• Jonathan Kehayias
• Ted Krueger
– Gail Shaw
– Paul Randal
http://www.simple-talk.com/books/sql-books/troubleshooting-
sql-server-a-guide-for-the-accidental-dba/
Thank you!
Don’t forget to complete the
Feedback forms
Tell us about this session on Twitter
#sqlstart

Mais conteúdo relacionado

Mais procurados

Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeExcella
 
Campus days 2013 - Instrumentation
Campus days 2013 - InstrumentationCampus days 2013 - Instrumentation
Campus days 2013 - InstrumentationAnders Lybecker
 
Part of the DLM story: Get your Database under Source Control - SQL In The City
Part of the DLM story: Get your Database under Source Control - SQL In The City Part of the DLM story: Get your Database under Source Control - SQL In The City
Part of the DLM story: Get your Database under Source Control - SQL In The City Red Gate Software
 
WALA Tutorial at PLDI 2010
WALA Tutorial at PLDI 2010WALA Tutorial at PLDI 2010
WALA Tutorial at PLDI 2010Julian Dolby
 
How to Un-Flake Flaky Tests - A New Hire's Toolkit
How to Un-Flake Flaky Tests - A New Hire's ToolkitHow to Un-Flake Flaky Tests - A New Hire's Toolkit
How to Un-Flake Flaky Tests - A New Hire's ToolkitZachary Attas
 
Unit Testing Oracle PL/SQL Code: utPLSQL, Excel and More
Unit Testing Oracle PL/SQL Code: utPLSQL, Excel and MoreUnit Testing Oracle PL/SQL Code: utPLSQL, Excel and More
Unit Testing Oracle PL/SQL Code: utPLSQL, Excel and MoreSteven Feuerstein
 

Mais procurados (6)

Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Campus days 2013 - Instrumentation
Campus days 2013 - InstrumentationCampus days 2013 - Instrumentation
Campus days 2013 - Instrumentation
 
Part of the DLM story: Get your Database under Source Control - SQL In The City
Part of the DLM story: Get your Database under Source Control - SQL In The City Part of the DLM story: Get your Database under Source Control - SQL In The City
Part of the DLM story: Get your Database under Source Control - SQL In The City
 
WALA Tutorial at PLDI 2010
WALA Tutorial at PLDI 2010WALA Tutorial at PLDI 2010
WALA Tutorial at PLDI 2010
 
How to Un-Flake Flaky Tests - A New Hire's Toolkit
How to Un-Flake Flaky Tests - A New Hire's ToolkitHow to Un-Flake Flaky Tests - A New Hire's Toolkit
How to Un-Flake Flaky Tests - A New Hire's Toolkit
 
Unit Testing Oracle PL/SQL Code: utPLSQL, Excel and More
Unit Testing Oracle PL/SQL Code: utPLSQL, Excel and MoreUnit Testing Oracle PL/SQL Code: utPLSQL, Excel and More
Unit Testing Oracle PL/SQL Code: utPLSQL, Excel and More
 

Semelhante a SQL Server Worst Practices - EN

SQL Explore 2012: P&T Part 1
SQL Explore 2012: P&T Part 1SQL Explore 2012: P&T Part 1
SQL Explore 2012: P&T Part 1sqlserver.co.il
 
U-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersU-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersMichael Rys
 
ATLRUG Rails Security Presentation - 9/10/2014
ATLRUG Rails Security Presentation - 9/10/2014ATLRUG Rails Security Presentation - 9/10/2014
ATLRUG Rails Security Presentation - 9/10/2014jasnow
 
SQL Server Tips & Tricks
SQL Server Tips & TricksSQL Server Tips & Tricks
SQL Server Tips & TricksIke Ellis
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server DatabasesColdFusionConference
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsOracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsZohar Elkayam
 
An Approach to Sql tuning - Part 1
An Approach to Sql tuning - Part 1An Approach to Sql tuning - Part 1
An Approach to Sql tuning - Part 1Navneet Upneja
 
Ten query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should knowTen query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should knowKevin Kline
 
Saleforce For Domino Dogs
Saleforce For Domino DogsSaleforce For Domino Dogs
Saleforce For Domino DogsMark Myers
 
Efficient working with Databases in LabVIEW - Sam Sharp (MediaMongrels Ltd) -...
Efficient working with Databases in LabVIEW - Sam Sharp (MediaMongrels Ltd) -...Efficient working with Databases in LabVIEW - Sam Sharp (MediaMongrels Ltd) -...
Efficient working with Databases in LabVIEW - Sam Sharp (MediaMongrels Ltd) -...MediaMongrels Ltd
 
SQLSaturday 664 - Troubleshoot SQL Server performance problems like a Microso...
SQLSaturday 664 - Troubleshoot SQL Server performance problems like a Microso...SQLSaturday 664 - Troubleshoot SQL Server performance problems like a Microso...
SQLSaturday 664 - Troubleshoot SQL Server performance problems like a Microso...Marek Maśko
 
Tips & Tricks SQL in the City Seattle 2014
Tips & Tricks SQL in the City Seattle 2014Tips & Tricks SQL in the City Seattle 2014
Tips & Tricks SQL in the City Seattle 2014Ike Ellis
 
ECMDay2015 - Kent Agerlund – Configuration Manager 2012 – A Site Review
ECMDay2015 - Kent Agerlund – Configuration Manager 2012 – A Site ReviewECMDay2015 - Kent Agerlund – Configuration Manager 2012 – A Site Review
ECMDay2015 - Kent Agerlund – Configuration Manager 2012 – A Site ReviewKenny Buntinx
 
Query Tuning for Database Pros & Developers
Query Tuning for Database Pros & DevelopersQuery Tuning for Database Pros & Developers
Query Tuning for Database Pros & DevelopersCode Mastery
 
Understanding SQL Server 2016 Always Encrypted
Understanding SQL Server 2016 Always EncryptedUnderstanding SQL Server 2016 Always Encrypted
Understanding SQL Server 2016 Always EncryptedEd Leighton-Dick
 
ATLRUG Security Workshop - 9/10/2014
ATLRUG  Security Workshop - 9/10/2014 ATLRUG  Security Workshop - 9/10/2014
ATLRUG Security Workshop - 9/10/2014 jasnow
 
A data driven etl test framework sqlsat madison
A data driven etl test framework sqlsat madisonA data driven etl test framework sqlsat madison
A data driven etl test framework sqlsat madisonTerry Bunio
 
Agile db testing_techniques
Agile db testing_techniquesAgile db testing_techniques
Agile db testing_techniquesTarik Essawi
 

Semelhante a SQL Server Worst Practices - EN (20)

Breaking data
Breaking dataBreaking data
Breaking data
 
SQL Explore 2012: P&T Part 1
SQL Explore 2012: P&T Part 1SQL Explore 2012: P&T Part 1
SQL Explore 2012: P&T Part 1
 
Day 4 - Models
Day 4 - ModelsDay 4 - Models
Day 4 - Models
 
U-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersU-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for Developers
 
ATLRUG Rails Security Presentation - 9/10/2014
ATLRUG Rails Security Presentation - 9/10/2014ATLRUG Rails Security Presentation - 9/10/2014
ATLRUG Rails Security Presentation - 9/10/2014
 
SQL Server Tips & Tricks
SQL Server Tips & TricksSQL Server Tips & Tricks
SQL Server Tips & Tricks
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server Databases
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsOracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
 
An Approach to Sql tuning - Part 1
An Approach to Sql tuning - Part 1An Approach to Sql tuning - Part 1
An Approach to Sql tuning - Part 1
 
Ten query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should knowTen query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should know
 
Saleforce For Domino Dogs
Saleforce For Domino DogsSaleforce For Domino Dogs
Saleforce For Domino Dogs
 
Efficient working with Databases in LabVIEW - Sam Sharp (MediaMongrels Ltd) -...
Efficient working with Databases in LabVIEW - Sam Sharp (MediaMongrels Ltd) -...Efficient working with Databases in LabVIEW - Sam Sharp (MediaMongrels Ltd) -...
Efficient working with Databases in LabVIEW - Sam Sharp (MediaMongrels Ltd) -...
 
SQLSaturday 664 - Troubleshoot SQL Server performance problems like a Microso...
SQLSaturday 664 - Troubleshoot SQL Server performance problems like a Microso...SQLSaturday 664 - Troubleshoot SQL Server performance problems like a Microso...
SQLSaturday 664 - Troubleshoot SQL Server performance problems like a Microso...
 
Tips & Tricks SQL in the City Seattle 2014
Tips & Tricks SQL in the City Seattle 2014Tips & Tricks SQL in the City Seattle 2014
Tips & Tricks SQL in the City Seattle 2014
 
ECMDay2015 - Kent Agerlund – Configuration Manager 2012 – A Site Review
ECMDay2015 - Kent Agerlund – Configuration Manager 2012 – A Site ReviewECMDay2015 - Kent Agerlund – Configuration Manager 2012 – A Site Review
ECMDay2015 - Kent Agerlund – Configuration Manager 2012 – A Site Review
 
Query Tuning for Database Pros & Developers
Query Tuning for Database Pros & DevelopersQuery Tuning for Database Pros & Developers
Query Tuning for Database Pros & Developers
 
Understanding SQL Server 2016 Always Encrypted
Understanding SQL Server 2016 Always EncryptedUnderstanding SQL Server 2016 Always Encrypted
Understanding SQL Server 2016 Always Encrypted
 
ATLRUG Security Workshop - 9/10/2014
ATLRUG  Security Workshop - 9/10/2014 ATLRUG  Security Workshop - 9/10/2014
ATLRUG Security Workshop - 9/10/2014
 
A data driven etl test framework sqlsat madison
A data driven etl test framework sqlsat madisonA data driven etl test framework sqlsat madison
A data driven etl test framework sqlsat madison
 
Agile db testing_techniques
Agile db testing_techniquesAgile db testing_techniques
Agile db testing_techniques
 

Mais de Gianluca Sartori

SQL Server 2016 New Security Features
SQL Server 2016 New Security FeaturesSQL Server 2016 New Security Features
SQL Server 2016 New Security FeaturesGianluca Sartori
 
Responding to extended events in near real time
Responding to extended events in near real timeResponding to extended events in near real time
Responding to extended events in near real timeGianluca Sartori
 
Sql server security in an insecure world
Sql server security in an insecure worldSql server security in an insecure world
Sql server security in an insecure worldGianluca Sartori
 
TSQL Advanced Query Techniques
TSQL Advanced Query TechniquesTSQL Advanced Query Techniques
TSQL Advanced Query TechniquesGianluca Sartori
 
My Query is slow, now what?
My Query is slow, now what?My Query is slow, now what?
My Query is slow, now what?Gianluca Sartori
 
SQL Server Benchmarking, Baselining and Workload Analysis
SQL Server Benchmarking, Baselining and Workload AnalysisSQL Server Benchmarking, Baselining and Workload Analysis
SQL Server Benchmarking, Baselining and Workload AnalysisGianluca Sartori
 
A performance tuning methodology
A performance tuning methodologyA performance tuning methodology
A performance tuning methodologyGianluca Sartori
 
SQL Server Worst Practices
SQL Server Worst PracticesSQL Server Worst Practices
SQL Server Worst PracticesGianluca Sartori
 

Mais de Gianluca Sartori (9)

Benchmarking like a pro
Benchmarking like a proBenchmarking like a pro
Benchmarking like a pro
 
SQL Server 2016 New Security Features
SQL Server 2016 New Security FeaturesSQL Server 2016 New Security Features
SQL Server 2016 New Security Features
 
Responding to extended events in near real time
Responding to extended events in near real timeResponding to extended events in near real time
Responding to extended events in near real time
 
Sql server security in an insecure world
Sql server security in an insecure worldSql server security in an insecure world
Sql server security in an insecure world
 
TSQL Advanced Query Techniques
TSQL Advanced Query TechniquesTSQL Advanced Query Techniques
TSQL Advanced Query Techniques
 
My Query is slow, now what?
My Query is slow, now what?My Query is slow, now what?
My Query is slow, now what?
 
SQL Server Benchmarking, Baselining and Workload Analysis
SQL Server Benchmarking, Baselining and Workload AnalysisSQL Server Benchmarking, Baselining and Workload Analysis
SQL Server Benchmarking, Baselining and Workload Analysis
 
A performance tuning methodology
A performance tuning methodologyA performance tuning methodology
A performance tuning methodology
 
SQL Server Worst Practices
SQL Server Worst PracticesSQL Server Worst Practices
SQL Server Worst Practices
 

Último

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
🐬 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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
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
 

Último (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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...
 
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...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 

SQL Server Worst Practices - EN

  • 1. SQL START! ANCONA, 28 SETTEMBRE 2012
  • 2. SQL START! ANCONA, 28 SETTEMBRE 2012 SQL Server Worst Practices Gianluca Sartori gianluca.sartori@sqlconsulting.it
  • 5. Gianluca Sartori • Independent SQL Server consultant • Works with SQL Server since version 7 • MCTS, MCITP, MCT • DBA @ Scuderia Ferrari
  • 6. Agenda • Best practices or Worst practices? • What can wrong? – Design – Development – Installation – Administration
  • 7. Disclaimer: • Not everything is black or white • «It depends» is the most likely answer There are edge cases when one of these worst practices is the only possible solution
  • 8. Best Practices vs. Worst Practices • Why Best Practices are not enough – Too many – No time – Lack of experience – Not clear what happens if we don’t follow them • Why Worst Practices help – They show the mistakes to avoid – We can learn from someone else’s mistakes
  • 9. Worst Practices Areas Design Development Installation Administration Schema design Naming Data Types Environment HW validation OS configuration SQL installation Recovery Security Capacity Performance Monitoring Code Test
  • 10. Schema Design • Not normalizing the schema – 1NF: A key, atomic attributes only – 2NF: Every attribute depends on the whole key – 3NF: Every attribute depends only on the key «The key, the whole key, nothing but the key, so help me Codd»
  • 11. Clues of denormalization • Repeating data  redundancies • Inconsistent data between tables anomalies • Data separated by «,» • Ex: john@gmail.com, john@business.com • Structired data in «notes» columns • Columns with a numeric suffix – Ex: Zone1, Zone2, Zone3 …
  • 12. Schema Design Worst Practices • No Primary Key o surrogate keys only – «Id» is not the only possible key! • No Foreign Keys – They’re «awkward» • No CHECK constraint – The application will guarantee consistency… • Wrong data types – Zip code, Telephone Number – Dates saved as strings • Use of NULL where not necessary • Use of «dummy» data (ex: ‘.’ , 0)
  • 13. Schema Design Worst Practices • Inconsistent naming conventions – Plural o singular? – Italian / English – Hungarian Notation • tbl… • vw... • User objects with reserved system names • Use of the sp_ prefix – … less problematic than it might seem!
  • 14. Lookup Tables Orders PK order_id int order_date datetime FK2 customer_id int FK1 status_id char(2) FK3 priority_id tinyint Order_Status PK status_id char(2) status_description nvarchar(50) Customers PK customer_id int name varchar(100) address varchar(50) ZIP char(5) city nvarchar(50) FK2 state_id char(2) FK1 country_id char(3) Countries PK country_id char(3) description nvarchar(50) States PK state_id char(2) description nvarchar(50) Order_Priorities PK priority_id tinyint priority_description nvarchar(50) One lookup table for each attribute
  • 15. OTLT: One True Lookup Table Orders PK order_id int order_date datetime FK1 customer_id int status_id char(2) priority_id tinyint Customers PK customer_id int name nvarchar(100) address nvarchar(50) ZIP char(5) city nvarchar(50) state_id char(2) country_id char(3) LookupTable PK table_name sysname PK lookup_code nvarchar(500) lookup_description nvarchar(4000) CREATE TABLE LookupTable ( table_name sysname, lookup_code nvarchar(500), lookup_description nvarchar(4000) ) One lookup table for all attributes
  • 16. OTLT: One True Lookup Table • No Foreign Keys • Generic data types  nvarchar(?) – Implicit Conversions • CHECK constraints are hard to define • Locking CHECK( CASE WHEN lookup_code = 'states' AND lookup_code LIKE '[A-Z][A-Z]' THEN 1 WHEN lookup_code = 'priorities' AND lookup_code LIKE '[0-9]' THEN 1 WHEN lookup_code = 'countries' AND lookup_code LIKE '[0-9][0-9][0-9]' THEN 1 WHEN lookup_code = 'status' AND lookup_code LIKE '[A-Z][A-Z]' THEN 1 ELSE 0 END = 1 )
  • 17. EAV: Entity, Attribute, Value Customers PK customer_id int name nvarchar(100) address nvarchar(50) ZIP char(5) city nvarchar(50) state_id char(2) country_id char(3) AttributeNames PK attribute_id int PK,FK1 entity_id int attribute_name nvarchar(128) AttributeValues PK,FK1 attribute_id int PK,FK1 entity_id int PK,FK2,FK3 id int value nvarchar(4000) Entities PK entity_id int entity_name nvarchar(128) Orders PK order_id int order_date datetime customer_id int status_id char(2) priority_id tinyint
  • 18. EAV: Entity, Attribute, Value • Disadvantages: – Generic data types  Ex: varchar(4000) – No Foreign Keys – No CHECK constraints – Multiple accesses to the same table • One access per attribute • Advantages – Dynamic schema: no need to alter the database • Replication, distributed environments
  • 19. EAV: Entity, Attribute, Value • Workaround: – PIVOT / Crosstab – View + INSTEAD OF triggers • Alternatives: – SPARSE columns – XML – Key-value store databases • Azure Table storage, Redis – Document-oriented databases • MongoDB, RavenDB
  • 21. Development Worst Practices Development Environment • No database schema versioning • No abstraction level – Views, Functions, Stored Procedures • Development with sysadmin privileges – In produzione it won’t be sysadmin!
  • 22. Development Worst Practices Code • No transactions • No error handling – @@ERROR is a thing of the past! • Wrong isolation levels – NOLOCK = no consistency! • SELECT * • Dynamic SQL with hardcoded literals • Code vulnerable to SQL injection
  • 23. Development Worst Practices Test • Not testing all the code – Representative data volumes • Test in production – Can alter production data – Interferes with production users • Test in development environment – Useful at most for unit tests
  • 24. Installation Worst Practices • Using inadequate or unbalanced HW • Installing accepting all the defaults – Data files on the system drive! • Installing unused components • Installing multiple services on the same machine
  • 25. I/O Worst Practices • Choosing a wrong RAID level – RAID 0 offers no protection! • Planning storage with capacity in mind • Partition misalignment • Using the default allocation unit (4Kb)
  • 26. What does a database need? Brent Ozar
  • 27. Administration Worst Practices Backup and Recovery • No backup – With FULL recovery it’s a timebomb – Ignoraring RPO and RTO • No test restores • No consistency checks – DBCC REPAIR_ALLOW_DATA_LOSS Our responsibility is to perform restores, not backups!
  • 28. Administration Worst Practices Security • Too many sysadmin • Using SQL Authentication – Weak passwords • 123 • P4$$w0rd • Same as username • No auditing
  • 29. Administration Worst Practices Capacity • Not checking disk space – No space left = database halted! – Am I taking backups? • Relying on autogrow • Not presizing tempdb – Different file size = striping penalty
  • 30. Administration Worst Practices Maintenance • Not maintaining indexes and statistics • Using catch-all maintenance plans • Updating statistics after rebuilding indexes
  • 32. Performance Worst Practices Query Optimization RBAR: Row By Agonizing Row – Cursors – WHILE loops – App-side cursors – Scalar and multi-statement functions Jeff Moden Let’s use set-based code The optimizer knows better
  • 33. Performance Worst Practices Query Optimization • One query to rule them all – The optimizer is good, not perfect – «divide et impera» delivers better performance • DISTINCT for all queries • Query HINTs
  • 34. Performance Worst Practices Indexing • Accepting all suggestions from Tuning Advisor • Duplicate indexes • An index for each column – Indexes are not for free! • Suboptimal Clustered Index – Unique – Small – Unchanging – Ever increasing or decreasing Prefer NEWSEQUENTIALID() over NEWID()
  • 35. Performance Worst Practices Server Tuning • «Throwing HW» at the problem – A faster machine won’t fix structural issues • Using «advanced» options without testing – NT Fibers (lightweight pooling) – Priority Boost
  • 36. Administration Worst Practices Monitoring • Reactive paradigm (no monitoring) • Lack of alerting – Severity > 16 • Too much noise in alerts – Everybody will just ignore them altogether
  • 37. Resources Free Tool: Best Practices Analyzer • Highlights configuration parameters that don’t comply with best practices • Highlights potential problems • Offers recommendations http://www.microsoft.com/en-us/download/details.aspx?id=15289
  • 38. Risorse Free e-book: Troubleshooting SQL Server • Jonathan Kehayias • Ted Krueger – Gail Shaw – Paul Randal http://www.simple-talk.com/books/sql-books/troubleshooting- sql-server-a-guide-for-the-accidental-dba/
  • 39. Thank you! Don’t forget to complete the Feedback forms Tell us about this session on Twitter #sqlstart

Notas do Editor

  1. Lo scopo non è criticare, ma far capire errori che io per primo ho fatto nella mia carriera
  2. Agganciare la worst practice trascurabile sp_ con Worst Practice tremenda OTLT!!