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
In PostgreSQL, SMALLINT
is an integer data type. Here's a brief overview:
Size and Range:
-32768 to 32767
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.
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
.
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
Advantages:
SMALLINT
over INTEGER
can result in significant space savings.Considerations:
SMALLINT
, you'll get an error. It's essential to be sure of the data range before opting for this data type.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.
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 );
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 );
PostgreSQL cast to SMALLINT:
You can cast a value to SMALLINT using the ::
syntax:
SELECT '123'::SMALLINT;