Data types and constraints of Mysql database
Everyone knows that the data in the database is stored in the data table. In order to store the data more accurately and ensure the correctness and validity of the data in the table, you can add some mandatory verifications for the table when creating the table, such as: data type and constraint.
1. Data type
Data type refers to specifying the data type for the fields in the table when creating the table. Only when the data meets the type requirements can it be stored. The principle of using data types is to use enough. Try to use small value ranges instead of large ones. This can save more storage space.
Common data types are as follows:
- Integer: int, bit
- Decimal: decimal
- String: varchar, char
- Date and time: date, time, datetime
- Enumeration type (enum)
Data type description:
- Decimal represents a floating-point number, such as decimal(5, 2) represents a coexistence of 5 digits, and a decimal occupies 2 digits.
- char represents a fixed-length character string, such as char(3), if you fill with'ab', a space will be added as'ab', and 3 represents the number of characters
- Varchar represents a variable-length character string, such as varchar(3), it will store “ab” when filling with “ab”, and 3 represents the number of characters
- For files such as pictures, audios, videos, etc., they are not stored in the database, but uploaded to a server, and then the storage path of the file is stored in the table
- The string text means storing large texts. It is recommended when the characters are greater than 4000, such as technical blogs.
2. Data constraints
Constraints refer to additional requirements for data on the basis of data type restrictions.
Common constraints are as follows:
- Primary key: The order of physical storage. MySQL recommends that the primary key field of all tables is called id and the type is int unsigned.
- Not null not null: Blank values are not allowed in this field. Unique: The value of this field is not allowed to be repeated.
- Default default: When the value corresponding to the field is not filled in, the default value will be used. If it is filled in, it shall prevail.
- Foreign key: Constraint on the relationship field. When filling in the value for the relationship field, it will check whether the value exists in the associated table. If it exists, the filling is successful, if it does not exist, the filling fails and an exception is thrown.
3. Data type appendix table
-
Integer type
-
String
-
Time type
to sum up
Commonly used data types:
- Integer: int, bit
- Decimal: decimal
- String: varchar, char
- Date and time: date, time, datetime
- Enumeration type (enum)
Common constraints:
- Primary key constraint
- Not null constraint not null
- Unique constraint
- Default constraint
- Foreign key constraints
Data types and constraints ensure the accuracy and completeness of the data in the table