Data Science Hub
  • Data Science Hub
  • STATISTICS
    • Introduction
    • Fundamentals
      • Data Types
      • Central Tendency, Asymmetry, and Variability
      • Sampling
      • Confidence Interval
      • Hypothesis Testing
    • Distributions
      • Exponential Distribution
    • A/B Testing
      • Sample Size Calculation
      • Multiple Testing
  • Database
    • Database Fundamentals
    • Database Management Systems
    • Data Warehouse vs Data Lake
  • SQL
    • SQL Basics
      • Creating and Modifying Tables/Views
      • Data Types
      • Joins
    • SQL Rules
    • SQL Aggregate Functions
    • SQL Window Functions
    • SQL Data Manipulation
      • String Operations
      • Date/Time Operations
    • SQL Descriptive Stats
    • SQL Tips
    • SQL Performance Tuning
    • SQL Customization
    • SQL Practice
      • Designing Databases
        • Spotify Database Design
      • Most Commonly Asked
      • Mixed Queries
      • Popular Websites For SQL Practice
        • SQLZoo
          • World - BBC Tables
            • SUM and COUNT Tutorial
            • SELECT within SELECT Tutorial
            • SELECT from WORLD Tutorial
            • Select Quiz
            • BBC QUIZ
            • Nested SELECT Quiz
            • SUM and COUNT Quiz
          • Nobel Table
            • SELECT from Nobel Tutorial
            • Nobel Quiz
          • Soccer / Football Tables
            • JOIN Tutorial
            • JOIN Quiz
          • Movie / Actor / Casting Tables
            • More JOIN Operations Tutorial
            • JOIN Quiz 2
          • Teacher - Dept Tables
            • Using Null Quiz
          • Edinburgh Buses Table
            • Self join Quiz
        • HackerRank
          • SQL (Basic)
            • Select All
            • Select By ID
            • Japanese Cities' Attributes
            • Revising the Select Query I
            • Revising the Select Query II
            • Revising Aggregations - The Count Function
            • Revising Aggregations - The Sum Function
            • Revising Aggregations - Averages
            • Average Population
            • Japan Population
            • Population Density Difference
            • Population Census
            • African Cities
            • Average Population of Each Continent
            • Weather Observation Station 1
            • Weather Observation Station 2
            • Weather Observation Station 3
            • Weather Observation Station 4
            • Weather Observation Station 6
            • Weather Observation Station 7
            • Weather Observation Station 8
            • Weather Observation Station 9
            • Weather Observation Station 10
            • Weather Observation Station 11
            • Weather Observation Station 12
            • Weather Observation Station 13
            • Weather Observation Station 14
            • Weather Observation Station 15
            • Weather Observation Station 16
            • Weather Observation Station 17
            • Weather Observation Station 18
            • Weather Observation Station 19
            • Higher Than 75 Marks
            • Employee Names
            • Employee Salaries
            • The Blunder
            • Top Earners
            • Type of Triangle
            • The PADS
          • SQL (Intermediate)
            • Weather Observation Station 5
            • Weather Observation Station 20
            • New Companies
            • The Report
            • Top Competitors
            • Ollivander's Inventory
            • Challenges
            • Contest Leaderboard
            • SQL Project Planning
            • Placements
            • Symmetric Pairs
            • Binary Tree Nodes
            • Interviews
            • Occupations
          • SQL (Advanced)
            • Draw The Triangle 1
            • Draw The Triangle 2
            • Print Prime Numbers
            • 15 Days of Learning SQL
          • TABLES
            • City - Country
            • Station
            • Hackers - Submissions
            • Students
            • Employee - Employees
            • Occupations
            • Triangles
        • StrataScratch
          • Netflix
            • Oscar Nominees Table
            • Nominee Filmography Table
            • Nominee Information Table
          • Audible
            • Easy - Audible
          • Spotify
            • Worldwide Daily Song Ranking Table
            • Billboard Top 100 Year End Table
            • Daily Rankings 2017 US
          • Google
            • Easy - Google
            • Medium - Google
            • Hard - Google
        • LeetCode
          • Easy
  • Python
    • Basics
      • Variables and DataTypes
        • Lists
        • Dictionaries
      • Control Flow
      • Functions
    • Object Oriented Programming
      • Restaurant Modeler
    • Pythonic Resources
    • Projects
  • Machine Learning
    • Fundamentals
      • Supervised Learning
        • Classification Algorithms
          • k-Nearest Neighbors
            • kNN Parameters & Attributes
          • Logistic Regression
        • Classification Report
      • UnSupervised Learning
        • Clustering
          • Evaluation
      • Preprocessing
        • Scalers: Standard vs MinMax
        • Feature Selection vs Dimensionality Reduction
        • Encoding
    • Frameworks
    • Machine Learning in Advertising
    • Natural Language Processing
      • Stopwords
      • Name Entity Recognition (NER)
      • Sentiment Analysis
        • Agoda Reviews - Part I - Scraping Reviews, Detecting Languages, and Preprocessing
        • Agoda Reviews - Part II - Sentiment Analysis and WordClouds
    • Recommendation Systems
      • Spotify Recommender System - Artists
  • Geospatial Analysis
    • Geospatial Analysis Basics
    • GSA at Work
      • Web Scraping and Mapping
  • GIT
    • GIT Essentials
    • Connecting to GitHub
  • FAQ
    • Statistics
  • Cloud Computing
    • Introduction to Cloud Computing
    • Google Cloud Platform
  • Docker
    • What is Docker?
Powered by GitBook
On this page
  • 1. Common Data Types
  • 1.1. Character Data Types
  • 1.2. Numeric Data Types
  • 1.3. Date/Time Data Types
  • 1.4. Arrays
  • 2. Displaying Existing Tables' Columns and Their DataTypes
  • 2.1. Displaying All TABLES existed in a Database
  • 2.2. Displaying All COLUMNs in a Table
  • 2.3. Displaying only the Column Names and the Data Types in a Table

Was this helpful?

  1. SQL
  2. SQL Basics

Data Types

Last updated 7 months ago

Was this helpful?

This section will cover common datatypes in PostgreSQL and show us how to determine the data type of a column in an existing table. For detailed list of data types, please visit:

1. Common Data Types

1.1. Character Data Types

  • CHAR (fixed length)

  • VARCHAR (variable-length with limit)

  • TEXT (unlimited length)

1.2. Numeric Data Types

  • INT (4 bytes)

  • DECIMAL(variable)

  • SERIAL(2 bytes)

1.3. Date/Time Data Types

  • DATE(stores date data. ISO 3601 format standard: 'yyyy-mm-dd'; e.g. '2024-01-01'),

  • TIME(stores time data with microsecond precision with or without time zone, ex '03:15:33.467'),

  • TIMESTAMP(stores date and time data with or without timezone. e.g. '2023-01-21 02:06:11.86123+00' )

  • INTERVAL(stores date and time data as a period of time in years, months, days, hours, seconds, etc. e.g. '7 days')

The SQL standard requires that writing just timestamp be equivalent to timestamp without time zone, and PostgreSQL honors that behavior. timestamptz is accepted as an abbreviation for timestamp with time zone; this is a PostgreSQL extension.

To check the timezones, abbreviations, offsets from the UTC, and whether the timezone follows daylight saving time procedure, you can query PostGRES' pg_timezone_names table.

SELECT * FROM pg_timezone_names

Example including a week interval:

SELECT
    rental_date,
-- Calculate the 7-day return date
    rental_date + INTERVAL '7 days' AS return_date
FROM books;

1.4. Arrays

Much like arrays in typical programming languages, we have the capability to generate multi-dimensional arrays with different lengths for any native data type. To illustrate how to use arrays let us first create a table and populate it:

Note that Array indexing starts at 1 (not 0)

CREATE TABLE students (
     student_id int,
     full_name varchar(100),
     email text[][],  -- array of email type (personal, student) and email addresses
     scores int[] -- array of exam scores: math, physics, chemistry, biology
);

INSERT INTO students VALUES (1, 'Keanu Frees', '{{"personal","keanu.frees@gmail.com"},{"student","kf@dshub.edu"}}', '{98,95,100,91}');
INSERT INTO students VALUES (2, 'Natalie Parton', '{{"personal","natalie.parton@gmail.com"},{"student","np24@dshub.edu"}}', '{87,85,93,90}');
INSERT INTO students VALUES (3, 'SJ Brown', '{{ARRAY[NULL],ARRAY[NULL]},{"student","sj@dshub.edu"}}', '{100,99,89,95}');
INSERT INTO students VALUES (4, 'Morgan Freewill', '{{"personal","morgan.rebel@gmail.com"},{"student","morganr@dshub.edu"}}', '{93,94,91,97}');


-- Accessing ARRAYs 
SELECT
	student_id,
	full_name,
	email[1][1] AS email_type,
	email[1][2] AS email_address,
	scores[1] AS math_score
FROM student_arrays
-- 1) Filter only students with 'personal' emails
-- WHERE email[1][1]='personal';

-- or
-- WHERE 'personal' = ANY(email);

-- or with 'contains operator @>'
WHERE email @> ARRAY['personal'];

/* OUTPUT
student_id full_name	email_type	email_address		math_score
1	Keanu Frees	personal	keanu.frees@gmail.com		98
2	Natalie Parton	personal	natalie.parton@gmail.com	87
4	Morgan Freewill	personal	morgan.freewill@gmail.com	93
*/



SELECT
	student_id,
	full_name,
	email[1][1] AS email_type,
	email[1][2] AS email_address,
	scores[1] AS math_score
FROM student_arrays
-- Filter students with 'student' emails
WHERE email[1][1]='student';

/* OUTPUT
NULL because indexing is incorrent
*/

2. Displaying Existing Tables' Columns and Their DataTypes

2.1. Displaying All TABLES existed in a Database

-- Select all columns from the TABLES system database
SELECT * 
FROM INFORMATION_SCHEMA.TABLES
-- Filter by schema
WHERE table_schema = 'public'
-- Sort by table name
ORDER BY table_name;

2.2. Displaying All COLUMNs in a Table

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'city';

2.3. Displaying only the Column Names and the Data Types in a Table

SELECT 
    column_name,
    data_type
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'city';

For more data manipulation examples check out page.

SQL Data Wrangling
https://www.postgresql.org/docs/current/datatype.html
Numeric Data Type List (Credit: )
postgresql.org