pythonsqlpython-3.xsqlitesqlite3-python

How to set a maximum integer value for a column in SQL?


I am creating a Python program for learning new words with the flash cards method. For this, I need an SQL database where a table is a pair of languages. When the user answers correctly, the value of the words pair increases by 1, but it should not exceed 4. How can I limit the maximum value of the corresponding column?

I'd like to inscribe this rule with sqlite3 into the database itself. Of course, the maximum can be set on the Python side, but it would complicate the code considerably.

Actually, I've tried to google it, but could not find the correct answer. By now, the function creating the dictionary is:

def create_dictionary ():
    lang1 = input('Insert first language: ')
    lang2 = input('Insert second language: ')
    dict_name = (lang1 + "_" + lang2)
    cur = conn.cursor()
    cur.execute('''CREATE TABLE IF NOT EXISTS {tab}
  (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
  {word1}   TEXT UNIQUE,
  {word2}   TEXT UNIQUE,
  box12   INTEGER,
  box21   INTEGER);'''.format(tab = dict_name, word1 = lang1, word2 = lang2))  
    print("Table created successfully")
    conn.commit()
    cur.close()

Solution

  • There are basically 2 approaches.

    1. Column constraint: You can set a constraint on the column to ensure that only values within a certain range are allowed. When using this approach your python function should throw an error it the value excceeds the limit.
    CREATE TABLE table (
        id INTEGER PRIMARY KEY,
        value_column INTEGER CHECK (value_column <= 4)
    );
    
    1. Application logic: You can add own logic to your API in order to ensure that the value does not exceed 4.