CodexBloom - Programming Q&A Platform

Struggling with SQL Migration for RESTful API: Handling Multiple Related Tables and Performance

๐Ÿ‘€ Views: 12 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-09-06
postgresql sql-server api-development SQL

I'm upgrading from an older version and I've been banging my head against this for hours... I've looked through the documentation and I'm still confused about Currently developing a RESTful API for a migration project that involves moving user data from an old SQL Server 2012 database to PostgreSQL 13. One of my challenges is efficiently querying multiple related tables while maintaining performance. The data structure is fairly complex, with a `Users` table linked to `Orders`, `Profiles`, and `Settings` tables. Each user can have multiple orders and settings preferences, which complicates the migration process. I've started by mapping out the relationships in the new database schema. Hereโ€™s a simplified version of my current SQL query trying to fetch user details along with their recent orders: ```sql SELECT u.id, u.name, o.order_date, o.amount FROM Users u LEFT JOIN Orders o ON u.id = o.user_id WHERE o.order_date >= NOW() - INTERVAL '30 days' ORDER BY o.order_date DESC; ``` The results are coming back as expected, but Iโ€™m concerned about how it will scale. When testing with larger datasets, it's noticeably slower. Iโ€™ve also tried introducing indexes on the `user_id` column in the `Orders` table, but it hasn't made a significant impact. Additionally, I considered using Common Table Expressions (CTEs) to break down the query into more manageable parts, but Iโ€™m unsure if that would help with performance. Here's an example of what I tried: ```sql WITH RecentOrders AS ( SELECT user_id, order_date, amount FROM Orders WHERE order_date >= NOW() - INTERVAL '30 days' ) SELECT u.id, u.name, ro.order_date, ro.amount FROM Users u LEFT JOIN RecentOrders ro ON u.id = ro.user_id; ``` This approach seems cleaner, but Iโ€™m not convinced itโ€™s optimized for speed. Any advice on best practices for managing complex queries like this during migration? Should I consider denormalization in some cases to improve read performance? Looking forward to suggestions on both SQL practices and potential tooling that might assist with this migration process. My development environment is macOS. Any ideas what could be causing this? For context: I'm using Sql on Debian. Has anyone dealt with something similar? I'm on Windows 11 using the latest version of Sql. What's the correct way to implement this?