0% found this document useful (0 votes)
18 views6 pages

PostgreSQL Data Types and Examples

The document provides an overview of PostgreSQL data types, including numeric, character, boolean, date/time, UUID, array, and JSON types, along with their descriptions and examples. It also includes a cheat sheet for PostgreSQL functions, covering string, numeric, date/time, aggregate, conditional, JSON, array, and window functions, with explanations and examples for each. This comprehensive guide serves as a reference for understanding PostgreSQL's capabilities and syntax.

Uploaded by

learnazurehari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views6 pages

PostgreSQL Data Types and Examples

The document provides an overview of PostgreSQL data types, including numeric, character, boolean, date/time, UUID, array, and JSON types, along with their descriptions and examples. It also includes a cheat sheet for PostgreSQL functions, covering string, numeric, date/time, aggregate, conditional, JSON, array, and window functions, with explanations and examples for each. This comprehensive guide serves as a reference for understanding PostgreSQL's capabilities and syntax.

Uploaded by

learnazurehari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

 Postgres Data types

🔹 1. Numeric Types

Data Type Description Example


SMALLINT 2 bytes, -32,768 to 32,767 123
INTEGER / INT 4 bytes, -2B to +2B 10000
BIGINT 8 bytes, large numbers 9223372036854775807
DECIMAL(p,s) / NUMERIC(p,s) Exact precision (e.g., money) 999.99
REAL 4-byte floating point 3.14
DOUBLE PRECISION 8-byte float 3.1415926535
SERIAL Auto-incrementing integer 1, 2, 3...

🔹 2. Character Types

Data Type Description Example


CHAR(n) Fixed-length (padded) 'abc '
VARCHAR(n) Variable-length with limit 'hello'
TEXT Variable unlimited length 'any string'

🔹 3. Boolean Type

Data Type Description Example


BOOLEAN TRUE / FALSE / NULL TRUE

🔹 4. Date/Time Types

Data Type Description Example


DATE Calendar date (YYYY-MM-DD) '2025-04-12'
TIME Time of day '13:30:00'
TIMESTAMP Date + time '2025-04-12 13:30'
TIMESTAMPTZ Timestamp with timezone '2025-04-12 13:30+00'
INTERVAL Time duration '2 days', '3 hours'

🔹 5. UUID
Data Type Description Example
UUID Universally Unique Identifier 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'

🔹 6. Array Type

Data Type Description Example


TEXT[], INT[] One-dimensional arrays '{1, 2, 3}' or '{a,b,c}'

🔹 7. JSON & JSONB

Data Type Description Example


JSON
Textual '{"name":
JSON "John"}'
Binary
'{"name":
JSONB JSON "John"}'
(faster)

PostgreSQL Functions Cheat Sheet

🔹 1. String Functions
Function Description Example
Data Type Description Example

Returns length
LENGTH(str) LENGTH('hello') → 5
of a string

Converts to
UPPER(str) 'abc' → 'ABC'
uppercase

Converts to
LOWER(str) 'ABC' → 'abc'
lowercase

Concatenates
CONCAT(a, b) 'a' + 'b' → 'ab'
strings

SUBSTRING(str FROM Extract 'abcdef' FROM 2 FOR


x FOR y) substring 3 → 'bcd'

Removes
TRIM(str) ' hello ' → 'hello'
spaces

POSITION(substr IN Position of
'l' IN 'hello' → 3
str) substring

REPLACE(str, from, Replace


'dog' → 'cat'
to) substring

🔹 2. Numeric / Math Functions


Function Description Example

ROUND(num, Round a ROUND(3.456, 2) →


decimals) number 3.46

CEIL(num) Round up CEIL(2.3) → 3

FLOOR(num) Round down FLOOR(2.9) → 2

ABS(num) Absolute value ABS(-5) → 5

x raised to
POWER(x, y) POWER(2, 3) → 8
power y

MOD(x, y) Modulus MOD(10, 3) → 1


Data Type Description Example

🔹 3. Date & Time Functions


Function Description Example

CURRENT_DATE Current date '2025-04-12'

CURRENT_TIME Current time '14:05:00'

Current
NOW() '2025-04-12 14:05:00'
timestamp

Age from AGE('2000-01-01') →


AGE(date)
current date 25 years
EXTRACT(part FROM EXTRACT(YEAR FROM
date)
Extract part NOW()) → 2025

DATE_PART(part, Alias of DATE_PART('month',


date) EXTRACT NOW())

TO_CHAR(timestamp, TO_CHAR(NOW(), 'YYYY-


format)
Format date MM-DD')

🔹 4. Aggregate Functions
Function Description Example

Number of
COUNT(*) COUNT(*) → 5
rows

SUM(column) Sum of values SUM(salary)

AVG(column) Average value AVG(salary)

MAX(column) Highest value MAX(salary)

MIN(column) Lowest value MIN(salary)

STRING_AGG(str, Concatenate STRING_AGG(name, ',


delimiter) strings ')

🔹 5. Conditional Functions
Data Type Description Example
Descriptio
Function Example
n

COALESCE(val1, First non-


COALESCE(NULL, 'default')
val2, ...) null value

Returns
NULLIF(a, b) NULL if NULLIF(5, 5) → NULL
equal

Conditional \nsql\nCASE WHEN salary >


CASE 50000 THEN 'High' ELSE
logic 'Low' END\n

🔹 6. JSON Functions
Function Description Example

Get JSON json_column-


->
object field >'name'

Get field as json_column-


->>
text >>'name'

Expand JSON Returns key-


jsonb_each()
object value pairs

Unnest JSON
jsonb_array_elements() Loop over array
array

🔹 7. Array Functions
Descriptio
Function Example
n

array_length(arr, Length of array_length('{1,2,3}',


dim) array 1)

Convert
unnest(arr) array to unnest('{1,2,3}')
rows
Data Type Description Example
Descriptio
Function Example
n

array_append(arr, Add
array_append(arr, 4)
val) element

🔹 8. Window Functions
Function Description Example

RANK() Ranking with RANK() OVER(ORDER BY


OVER(...) ties salary)

Ranking
DENSE_RANK()
without gaps

ROW_NUMBER() Unique row ID

SUM() Cumulative SUM(salary)


OVER(...) sum OVER(PARTITION BY dept)

Previous/next
LAG() / LEAD() LAG(salary) OVER(...)
row

Common questions

Powered by AI

The UUID data type in PostgreSQL provides a globally unique identifier, which differs from traditional numerical identifiers by being not sequential and designed for universality across systems. Its main advantages are that it avoids conflicts in a distributed environment and enhances security by not exposing item counts as easily as sequential IDs.

PostgreSQL uses the BIGINT data type to handle large integers, which uses 8 bytes of storage. The maximum value it can store is 9,223,372,036,854,775,807.

The SERIAL data type in PostgreSQL is used for auto-incrementing integer fields. It is commonly applied in cases where unique identifiers for rows (such as primary keys) are required, allowing the database to automatically generate sequential numbers as new rows are inserted.

Conditional logic in PostgreSQL can be implemented using the CASE statement. For example, CASE WHEN salary > 50000 THEN 'High' ELSE 'Low' END classifies employee salaries as 'High' if they exceed 50,000, otherwise they are classified as 'Low'.

The UPPER() function in PostgreSQL is used to convert a given string to uppercase. For example, converting 'abc' using UPPER('abc') results in 'ABC'.

In PostgreSQL, the JSON data type stores data in a textual form, while JSONB stores data in a binary format. JSONB offers advantages in terms of performance because it allows for faster access and manipulation of JSON data due to its binary storage format.

PostgreSQL supports multi-dimensional arrays by allowing one-dimensional arrays to be nested. The array_length() function is used to determine the length of a specific dimension in an array. For example, array_length('{1,2,3}', 1) returns the size of the first dimension.

In PostgreSQL, window functions can compute a cumulative sum by using the SUM() function with an OVER clause that partitions data by department. For example, using SUM(salary) OVER(PARTITION BY dept) allows the calculation of a running total of salaries within each department without resetting across departments.

The COALESCE function in PostgreSQL is used to return the first non-null value from a list of arguments. It is useful in handling NULL values by providing a default value when actual data is missing. For example, COALESCE(NULL, 'default') would return 'default'.

The NUMERIC data type in PostgreSQL offers exact precision and is preferred for financial data to avoid rounding errors common in floating-point representations. Unlike floating-point types, which can introduce small precision errors due to binary computation, NUMERIC is designed for precise arithmetic operations.

You might also like