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
languageswith the columnsidandlanguage_code:6cursor.execute( 7 """CREATE TABLE languages 8 (id INTEGER PRIMARY KEY AUTOINCREMENT, 9 language_code VARCHAR(2))"""
Then we create the values
deandenin 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 tabletempwith all columns frombooksand a columnlanguage_codethat uses the columnidfrom thelanguagestable 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
bookstable to thetemptable: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
booksas theidof the data records from thelanguagestable totemp.40cursor.execute( 41 """UPDATE temp 42 SET language_code = 1 43 WHERE language = 'de'""" 44)
Now we can delete the
languagescolumn in thetemptable:55cursor.execute("""ALTER TABLE temp DROP COLUMN language""")
Note
DROP COLUMNcan 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
tempwould have to be inserted into this table.The
bookstable can now also be deleted:57cursor.execute("""DROP TABLE books""")
And finally, the
temptable can be renamedbooks:59cursor.execute("""ALTER TABLE temp RENAME TO books""")