👊 Data Types & Constraint
💬 Data Types :
An attribute that specifies the type of data in a column of our databse table.
PostgreSQL supports a wide variety of data types, broadly categorized into numeric, character, date/time, Boolean, Binary array, JSON, and other specilized types like UUID and Geometric types.
These types are used to store different kinds in the database.
(1). Numeric Types :
(A). Integer : PostgreSQL offers several integer types :
(i). Smallint (2 bytes)
(ii). bigint (8 bytes)
(iii). Integer (4 Bytes)
(iv). Serial - is the same as integer except that PostgreSQL will automatically
generate and populate values into the SERIAL column.
This is similar to AUTO_INCREAMENT .
( B ). Floating Types : - Are used to storing numbers with fractional parts.
(i). Real (4 bytes) -
(ii). Double Precision (8 bytes ) - It Offers higher Precision.
( C ). Decimal Types :
(i). Numeric & Decimal - With optional precision and scale are for exact numerical values, allowing for user- defined precision and scale.
(2). Character Types :
(A). Character : PostgreSQL offers several Character types :
(i). Char (Fix-length) - Stores fixed length character strings, with a specified number
of characters.
(ii). Varchar (Variable-length) - Stores variable length character strings, with a maximum length
(iii). Text (Variable-length) - Stores unlimited length charcter strings, essentially equivalent to varchar without a length constraint.
(3). Date and Time Types :
(i). Date : Stores only date values (Year, Month, Day).
(ii). Time : Stores only time values (Hour, minutes, second, millisecond).
(iii). Timestamp : Stores both Date and time(Also variants with or without time -
zone information).
(iv). Interval : Represents a time interval( difference between two timestamps).
(4). Boolean Types :
Boolean : Stores true or false values.
💬 Most Widely Used are :
- Numeric - INT DOUBLE FLOAT DECIMAL
- String - VARCHAR
- Date - DATE
- Boolean - BOOLEAN
CREATE TABLE Person(Id SERIAL, NAME VARCHAR(20), Country VARCHAR(25), Job_Title VARCHAR(30), Salary DOUBLE PRECISION);
💬 Constraint :
- A Constraint in PostgreSQL is a rule applied to a column.
- Constraints are rules that restrict the type and range of data that can be inserted into a table or column.
- Constraint are rules applied to table columns to enforce data integrity and ensure consistency.
- Common Constraint are types include Primary Key, Foreign Key, NOT NULL, UNIQUE, and Check Constraints.
CREATE TABLE Person (Id SERIAL Primary Key,Name TEXT NOT NULL);
CREATE TABLE Person (Id SERIAL Primary Key,);
CREATE TABLE Person (Id INTEGER References Person1( Id ));
CREATE TABLE Person (Name TEXT UNIQUE);
CREATE TABLE Person (Salary NUMERIC CHECK (Salary >= 0));
CREATE TABLE users (id SERIAL PRIMARY KEY,name TEXT NOT NULL,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
Comments