SMALLINT Datatype in MySQL

  • In MySQL Workbench, the SMALLINT data type is used to store small integer values with a larger range compared to TINYINT. It occupies 2 bytes (16 bits) of storage and can represent whole numbers. Like other integer data types, SMALLINT can be signed or unsigned, providing flexibility based on the range of values you need to store.
Let's delve into the details of the SMALLINT data type:
  • SMALLINT (Signed):
    • Size: 2 bytes (16 bits)
    • Range: The signed SMALLINT data type can store values from -32,768 to 32,767.
    • Usage: Use the signed SMALLINT when you need to store small integer values that can be both positive and negative.
Example of creating a table with a signed SMALLINT column:


    CREATE TABLE example_table (
        id SMALLINT,
        quantity SMALLINT
    );

  • SMALLINT UNSIGNED (Unsigned):
    • Size: 2 bytes (16 bits)
    • Range: The unsigned SMALLINT data type can store values from 0 to 65,535.
    • Usage: Use the unsigned SMALLINT when you need to store small integer values that are always non-negative (positive).
Example of creating a table with an unsigned SMALLINT column:


    CREATE TABLE example_table (
        user_id SMALLINT UNSIGNED,
        score SMALLINT UNSIGNED
    );

  • The SMALLINT data type is a good choice when you need to store relatively small integer values, but the range of values goes beyond what TINYINT can handle. It is commonly used for columns representing quantities, counters, or identifiers that are expected to stay within the range of a 16-bit integer.
  • However, if you expect to store larger integer values or need more extensive range coverage, consider using larger integer data types such as INT or BIGINT.
When selecting between signed and unsigned SMALLINT, consider the nature of the data you are dealing with:
  • Use Signed SMALLINT: When you need to represent small integer values that can be both positive and negative.
  • Use Unsigned SMALLINT: When you need to represent small integer values that are guaranteed to be non-negative (positive) and you want to maximize the range of positive values.
  • As with any data type, choosing the appropriate size and type is crucial for ensuring data accuracy and storage efficiency in your MySQL database. Using a data type that is too large may lead to unnecessary storage consumption, while using a data type that is too small can result in data truncation or loss of precision.

No comments:

Post a Comment

Date and Time related aggregation functions ($year, $month, $dayOfMonth, $hour, $minute, $second, $dayOfWeek, $dateToString, $dateSubtract, $dateAdd, $isoWeek, $isoDayOfWeek, $dateTrunc, $dateFromString, $dateToParts, $dateFromParts, $dateDiff, $week)

In this blog post, we will explore Date/Time-related Aggregation Functions in MongoDB. MongoDB provides a robust set of aggregation operator...