@@ -29,17 +29,49 @@ We''ll go over the most common database performance pitfalls so that you know ho
2929
3030#### Normalize (but not too much)
3131
32- Your database schema should be made so that one piece of information
33- is stored in only one place in the database.
34- For instance, if you are modelling sales that happen in stores, the sales table should
32+ Your database schema should be [normalized](https://en.wikipedia.org/wiki/Database_normalization):
33+ one piece of information should be stored in only one place in the database.
34+ This is a good practice that will not only make your queries faster,
35+ but also make it impossible to store incoherent data.
36+
37+ For instance, if you are modelling sales that happen in stores, the sales table should
3538contain a foreign key to another table named stores.
36- This way, when you need to display the list of stores in your application, you don' ' t have to
39+ It should not contain the full store name.
40+
41+ This way, when you need to display the list of stores in your application, you don' ' t have to
3742run a slow `select distinct store from sales`, that would have to go through your millions of sales
38- (*even if you have an index on the store column*),
43+ (*even if you have an index on the store column*), you just query the tiny `stores` table directly.
3944
40- ### Use database indices
45+ [Denormalization](https://en.wikipedia.org/wiki/Denormalization) can be introduced
46+ only after you have already normalized your data, and is often not required at all.
47+
48+ ### Use views
49+
50+ Querying normalized views can be cumbersome.
51+ `select store_name, sum(paid_eur) from sale group by store_name`
52+ is more readable than
53+
54+ ```sql
55+ select store.name, sum(sale.paid_eur)
56+ from sales
57+ inner join stores on sale.store_id = store.store_id
58+ group by store_name
59+ ```
4160
42- ### Use (materialized) views
61+ To work around that, you can create views that contain
62+ useful table joins so that you do not have to duplicate them in all your queries:
63+
64+ ```sql
65+ create view enriched_sales as
66+ select sales.sales_eur, sales.client_id, store.store_name
67+ from sales
68+ inner join store
69+ ```
70+
71+ #### Materialized views
72+
73+
74+ ### Use database indices
4375
4476### Query performance debugging
4577
0 commit comments