Write readable code

Applying SQL to Real-World Problems

Dmitriy (Dima) Gorenshteyn

Lead Data Scientist, Memorial Sloan Kettering Cancer Center

Capitalize SQL commands

Original

select 
  title as film_title, 
  description as film_description
from rental as r
join inventory as i
  on r.inventory_id = i.inventory_id
join film as f
  on i.film_id = f.film_id
where f.length > 90
  and f.replacement_cost > 20;

Improved

SELECT 
  title AS film_title, 
  description AS film_description
FROM rental AS r
JOIN inventory AS i
  ON r.inventory_id = i.inventory_id
JOIN film AS f
  ON i.film_id = f.film_id
WHERE f.length > 90
  AND f.replacement_cost > 20;
Applying SQL to Real-World Problems

Use new lines & indentation

Original

SELECT title, description
FROM rental AS r
JOIN inventory AS i
ON r.inventory_id = i.inventory_id
JOIN film AS f ON i.film_id = f.film_id
WHERE f.length > 90 AND f.replacement_cost > 20;

Improved

SELECT title, 
       description 
FROM rental AS r
JOIN inventory AS i
  ON r.inventory_id = i.inventory_id
JOIN film AS f
  ON i.film_id = f.film_id
WHERE f.length > 90
  AND f.replacement_cost > 20;
Applying SQL to Real-World Problems

Use snake_case

Original

SELECT 
  title expensivelongtitle, 
  description expensivelongdescription
FROM rental AS r
...

Improved

SELECT 
  title expensive_long_title, 
  description expensive_long_description
FROM rental AS r
...
Applying SQL to Real-World Problems

Use IN instead of many OR statements

Original

SELECT 
    address_id,  
    district 
FROM address
WHERE district = 'Texas'
  OR district = 'Bihar'
  OR district = 'Chiba'
  OR district = 'Chiayi'
  OR district = 'Gois';

Improved

SELECT 
    address_id,  
    district 
FROM address
WHERE district IN ('Texas', 'Bihar', 'Chiba', 
                   'Chiayi', 'Gois');
Applying SQL to Real-World Problems

Use BETWEEN when possible

Original

SELECT 
  title, 
  description
FROM film
WHERE replacement_cost > 15
  AND replacement_cost < 25;

Improved

SELECT 
  title, 
  description
FROM film
WHERE replacement_cost BETWEEN 15 AND 25;
Applying SQL to Real-World Problems

Let's practice!

Applying SQL to Real-World Problems

Preparing Video For Download...