Distribute Customer Data with Hash Partitioning
Creating a Hash-Partitioned Table
Write a PostgreSQL query to create a partitioned table for customers based on customer ID using hash partitioning.
Solution:
-- Create a partitioned table for customer data using hash partitioning.
CREATE TABLE Customers (
-- Define an auto-incrementing primary key column named customer_id.
customer_id SERIAL PRIMARY KEY,
-- Define a non-nullable column name of type TEXT.
name TEXT NOT NULL,
-- Define a non-nullable column email of type TEXT.
email TEXT NOT NULL
) PARTITION BY HASH (customer_id);
Explanation:
- Purpose of the Query:
- Uses hash partitioning to distribute customer data evenly.
- Key Components:
- PARTITION BY HASH (customer_id): Assigns data to partitions based on a hash function.
- Real-World Application:
- Useful for evenly distributing workload across partitions.
Notes:
- Hash partitioning is best for high-cardinality columns like unique IDs.
For more Practice: Solve these Related Problems:
- Write a PostgreSQL query to create a partitioned table for user sessions using hash partitioning based on a session_id column.
- Write a PostgreSQL query to create a partitioned table for order records using hash partitioning on an order_id column.
- Write a PostgreSQL query to create a partitioned table for vehicle registrations using hash partitioning on a registration_number column.
- Write a PostgreSQL query to create a partitioned table for bank transactions using hash partitioning on a transaction_id column.
Go to:
- Comprehensive Guide to Table Partitioning in PostgreSQL Exercises Home. ↩
- PostgreSQL Exercises Home ↩
PREV : Creating Partitions for a List-Partitioned Table.
NEXT : Creating Partitions for a Hash-Partitioned Table.
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
