Normalising the data¶
Normalisation is the division of attributes or table columns into several relations or tables so that no redundancies are included.
Example¶
In the following example, we normalise the language in which the books were published.
To do this, we first create a new table
languages
with the columnsid
andlanguage_code
:6cursor.execute( 7 """CREATE TABLE languages 8 (id INTEGER PRIMARY KEY AUTOINCREMENT, 9 language_code VARCHAR(2))"""
Then we create the values
de
anden
in this table:12cursor.execute( 13 """INSERT INTO languages (language_code) 14 VALUES ('de')""" 15) 16 17cursor.execute( 18 """INSERT INTO languages (language_code)
Since SQLite does not support
MODIFY COLUMN
, we now create a temporary tabletemp
with all columns frombooks
and a columnlanguage_code
that uses the columnid
from thelanguages
table as a foreign key:22cursor.execute( 23 """CREATE TABLE "temp" ( 24 "id" INTEGER, 25 "title" TEXT, 26 "language_code" INTEGER REFERENCES languages(id), 27 "language" TEXT, 28 "author" TEXT, 29 "license" TEXT, 30 "release_date" DATE, 31 PRIMARY KEY("id" AUTOINCREMENT) 32 )"""
Now we transfer the values from the
books
table to thetemp
table:35cursor.execute( 36 """INSERT INTO temp (title,language,author,license,release_date) 37 SELECT title,language,author,license,release_date FROM books"""
Transfer the specification of the language in
books
as theid
of the data records from thelanguages
table totemp
.40cursor.execute( 41 """UPDATE temp 42 SET language_code = 1 43 WHERE language = 'de'""" 44)
Now we can delete the
languages
column in thetemp
table:55cursor.execute("""ALTER TABLE temp DROP COLUMN language""")
Note
DROP COLUMN
can only be used from Python versions from 3.8 that were released after 27 April 2021.With older Python versions, another table would have to be created that no longer contains the languages column and then the data records from
temp
would have to be inserted into this table.The
books
table can now also be deleted:57cursor.execute("""DROP TABLE books""")
And finally, the
temp
table can be renamedbooks
:59cursor.execute("""ALTER TABLE temp RENAME TO books""")