PostgreSQL Tutorial

Data Types

Querying & Filtering Data

Managing Tables

Modifying Data

Conditionals

Control Flow

Transactions & Constraints

Working with JOINS & Schemas

Roles & Permissions

Working with Sets

Subquery & CTEs

User-defined Functions

Important In-Built Functions

PostgreSQL PL/pgSQL

Variables & Constants

Stored Procedures

Working with Triggers

Working with Views & Indexes

Errors & Exception Handling

PostgreSQL - SMALLINT Integer Data Type

In PostgreSQL, SMALLINT is an integer data type. Here's a brief overview:

  1. Size and Range:

    • Storage size: 2 bytes
    • Range: -32768 to 32767
  2. Usage:

    It's used to store numbers that have a smaller range, and when storage efficiency is a concern. For many applications, INTEGER or BIGINT might be more commonly used, but in cases where you know the values won't exceed the SMALLINT range, it's more storage-efficient.

  3. Examples:

    CREATE TABLE student (
        id SERIAL PRIMARY KEY,
        grade SMALLINT NOT NULL
    );
    

    In the above example, the grade column is defined as a SMALLINT, which is suitable if you're certain that the grade values will be within the range of -32768 to 32767.

  4. Casting:

    You can cast values to SMALLINT explicitly, but if the value is outside the permissible range, you'll get an error.

    SELECT 32000::SMALLINT;  -- This will work
    SELECT 33000::SMALLINT;  -- This will throw an error
    
  5. Advantages:

    • Space Savings: In large tables with millions or billions of rows, choosing SMALLINT over INTEGER can result in significant space savings.
    • Performance: Smaller data sizes can sometimes translate to faster query performance due to reduced disk I/O and better cache utilization.
  6. Considerations:

    • Overflow: If a value exceeds the range of SMALLINT, you'll get an error. It's essential to be sure of the data range before opting for this data type.
    • Compatibility: If your application or tools expect an INTEGER and you provide a SMALLINT, there could be type compatibility issues.

Remember that the right data type choice depends on the specific needs of your application and database schema. Always think about both the current and future requirements before finalizing your data type choices.

  1. SMALLINT in PostgreSQL example: To create a table with a SMALLINT column, you can use the following SQL example:

    CREATE TABLE example_table (
       id SERIAL PRIMARY KEY,
       smallint_column SMALLINT
    );
    
  2. PostgreSQL create table with SMALLINT: Example of creating a table with a SMALLINT column:

    CREATE TABLE example_table (
       id SERIAL PRIMARY KEY,
       smallint_column SMALLINT
    );
    
  3. PostgreSQL cast to SMALLINT: You can cast a value to SMALLINT using the :: syntax:

    SELECT '123'::SMALLINT;