Paul Laurence (@prlaurence) header
Paul Laurence (@prlaurence) profile picture

Postgres @snowflake @crunchydata. Previously Emerging Companies at @cooleyllp

Charleston, SC
Joined August 2014
Photo by Paul Laurence (@prlaurence)
Paul Laurence retweeted
We've updated our Postgres Playground tutorials (learn while using an in-browser Postgres), and it inspired our latest blog post. A few weeks ago, we set about updating all of the content for the Postgres Playground tutorials. It was a larger change than we initially thought because we launched Postgres Playground with Postgres 14. This got us thinking: "What else have we written that has changed since we wrote it?" We have blog posts that were posted when Postgres 10 was just released, so this idea also turned such a big ask we had to break it into chunks. For this post, we limited it to the "load, storage, indexes, and partitioning" content: crunchydata.com/blog/postgre… If you have anyone interested in the basics of Postgres, point them at the tutorials in the Postgres Playground: crunchydata.com/developers/t…
1
4
1
19
3,339
Paul Laurence retweeted
Exporting a CSV from Postgres? You've probably heard use \copy instead of COPY because it saves locally. But, the \copy command in psql is just a psuedo-command for COPY TO STDOUT. `COPY ... TO '/path/on/server'` writes a file on the database host, as the Postgres user (the server's machine, not on your local machine) `\copy` (in psql) just runs `COPY TO STDOUT` and saves the stream to a path on your local machine. `COPY TO STDOUT` is not psql-only. It is a protocol feature. It's ordinary SQL. The server switches into copy-out and streams bytes. Any client that implements the protocol can consume it: libpq (`PQgetCopyData`), JDBC (`CopyManager.copyOut`), psycopg (`cursor.copy`), and pgx all support it. Key options: `FORMAT csv` Commas, quoting, and escapes that spreadsheet tools expect. `HEADER true` Writes column names as the first line. Column list `\copy orders (sku, price) TO ...` exports only those columns, in that order. Wrap a `SELECT` when you need filters, joins, or expressions. `NULL` In CSV mode, nulls are an unquoted empty string by default. Empty strings are written as `""`. Match the same `NULL '…'` string on import if you override it. `FORCE_QUOTE` Force quotes on non-null values. Handy when a consumer is picky about fields that look like numbers or leading zeros.
1
4
28
1,094
Paul Laurence retweeted
Had another few large TB migrations into Crunchy Bridge recently. It was just over 5 years ago we were doing one of our largest early migrations of over 20 TB into @crunchydata. I used to say I'd never get comfortable with migrating a production database, there is always some risk. Yet, we've done it so much over the recent years that it's really a non-event for us. And migrated from literally everywhere, from RDS, Aurora, Azure, Heroku, self-managed on prem even. It's really great to sit back and watch the team day after day deliver an amazing experience so people can forget about their database and get back to building.
3
2
15
1,995
Paul Laurence retweeted
CDC has always been painful: brittle connectors, upsert overhead, schema changes breaking pipelines. Mirroring takes a different approach — push from inside Postgres via an extension, write to Iceberg, apply transactionally in Snowflake. You press a button. It runs forever. snowflake.com/en/blog/engine…
2
2
16
2,344
Paul Laurence retweeted
Think of Postgres permissioning a series of independent gates (authentication > database > schema > object > row): 1. can the role even connect? (pg_hba.conf) 2. can the role use this database? (CONNECT privilege) 3. can the role see this schema? (USAGE privilege) 4. can the role read/write this object? (SELECT/INSERT/UPDATE/DELETE privileges) 5. can the role see this row? (row-level security policies) Postgres's permission system is complicated when implemented haphazardly. When implemented thoughtfully, most of the confusion disappears. For a basic `SELECT`, a role needs USAGE on a schema and SELECT on a table.
1
6
1
35
3,174
Paul Laurence retweeted
Under what conditions does Postgres materialized a CTE? Just to catch everyone up, think of a CTE as a named result set defined before the main query, and is referenced in the main query. When Postgres materializes a CTE, it executes the CTE once and stores the result in memory or temporary disk space. The unmaterialized CTE, on the other hand, is inlined into the main query and executed as part of the main query's execution plan. So, when does Postgres materialize a CTE? The answer is: when the CTE is referenced multiple times in the main query. If a CTE is only referenced once, Postgres will inline it into the main query and execute it as part of the main query's execution plan. But if a CTE is referenced multiple times, Postgres will materialize it to avoid re-executing the same logic multiple times. Take a look at the annotated attached image of an EXPLAIN for a particularly complex query. In this query, the CTE is named "my_cte" (shout out to Perl folks). You'll see that it is executed once, then referenced as a "CTE Scan" in the main query's execution plan. random() caveats If a CTE has a volatile function (like `random()` and `gen_random_uuid()`), Postgres will materialize it even if it is only referenced once. This is because the result of the CTE could change between executions, and Postgres wants to ensure that the same result is used throughout the main query. Of course, if you want to maximize chaos, you can force it to be `NOT MATERIALIZED` (more on that in a bit). Other scenarios where Postgres will materialize and cannot be inlined include: • When the CTE is recursive (WITH RECURSIVE) • Locking clause (SELECT ... FOR UPDATE) • Data modification (INSERT, UPDATE, DELETE) using a returning clause But those make sense, right? Don't want to lock a table multiple times or have multiple inserts happening inline in a query (you can't choose to maximize chaos with this, as NOT MATERIALIZED will be ignored with these caveats). Forcing (Un)Materialization With CTEs, force materialization or inlining using the `MATERIALIZED` and `NOT MATERIALIZED` keywords. ```sql WITH my_cte AS MATERIALIZED (... ``` or: ```sql WITH my_cte AS NOT MATERIALIZED (... ``` A scenario that might improve with MATERIALIZED on a single use CTE would be if the CTE is expensive on it's own, and creates additional overhead when inlined into the main query. This may happen because of an incorrect ROW estimation by the planner causing it build an unoptimized query plan. A scenario that might improve with NOT MATERIALIZED on a multi-use CTE would be if the CTE is already a efficient index scan. The materialization of an optimized query can be slower. By forcing the CTE and main query to be inlined, the optimizer may benefit from combining WHERE conditionals for the CTE and main query (called "Filter Push Down"). Most of the time, just let Postgres handle it.
10
1
35
2,345
Paul Laurence retweeted
pg_cron is a PostgreSQL extension that runs scheduled jobs inside the database using standard cron syntax. If you find you are building jobs that mostly consist of calling database commands, just let Postgres handle it with pg_cron. It is a simple, reliable, and efficient way to schedule jobs without needing an external scheduler. Setup If you are using a managed Postgres service, `pg_cron` is available on Crunchy Bridge and other modern Postgres providers. If you are running Postgres yourself, you can install `pg_cron` from source or via your package manager. For example, on Ubuntu: ``` sudo apt install postgresql-18-cron ``` It must be loaded at server start via `postgresql.conf`: ``` shared_preload_libraries = 'pg_cron' cron.database_name = 'postgres' ``` By default all jobs run in the database where the extension is installed. `cron.schedule_in_database` can target other databases on the same instance via an argument to the job creation command. Jobs run as the role that created them, and that role requires the necessary table permissions. Getting started After loading the extension, call `cron.schedule` to create a job. Check the documentation for exactly what you want to do, as the method is overloaded (it will behave differently and adapt for the different arguments passed). The most typical example is 3 arguments: first argument is a name for the job, the second is a cron schedule, and the third is the SQL command to run. Check the precise syntax in the documentation for what you are tryign to achieve. [See attached images for examples of scheduling jobs.] Managing & Monitoring Jobs To manage jobs, query the `cron.job` table. Each row is a scheduled job, with its name, schedule, SQL command, and whether it is active. To view a record of every execution, query `cron.job_run_details`. Each row shows when the job started, how long it ran, and whether it succeeded or failed. Failed jobs do not retry, but they do log the error and wait for the next scheduled run. Common use cases: • Data retention: purge old logs • Maintenance: VACUUM a high-churn table nightly • Aggregation: roll up hourly stats • Archive: move old rows to a history table monthly • Refresh materialized views Uncommon use cases While not every one has these problems, `pg_cron` can also be used for: • Batching reads or writes to a remote API when paired with `http` • ETL pipelines that offload old partitions to a data warehouse using `pg_lake` • Use `pg_prewarm` to pre-warm a cache of frequently accessed data before daily peak traffic
2
12
71
3,628
Paul Laurence retweeted
Postgres 19 is almost here, and whew it's packed with awesome! - REPACK CONCURRENTLY! - Graph queries - Partitioning improvements - COPY, SQL, and planner improvements - Logical rep improvements A deep dive on the @Snowflake blog - snowflake.com/en/blog/engine…
6
3
43
3,987
Paul Laurence retweeted
Snowflake Postgres is now Generally Available. Run transactional workloads and analytics on one secure platform. ❄️ 100% community Postgres ❄️ Lift-and-shift migrations ❄️ Built-in HA, backups, and security ❄️ No brittle ETL pipelines Unify apps, analytics, and AI. Learn more: bit.ly/4kPCIee
3
8
1
32
2,652
Paul Laurence retweeted
One of the biggest design choices at @crunchydata when building Crunchy Bridge that now the same design is followed by @Snowflake Postgres is isolated VPCs per Postgres cluster. This deviates from so many other cloud database designs. They're all about multi-tenancy, a shared routing layer, trying to optimize their costs and compute. In reality you get noisy neighbors, have to scale a single load balancer, have less predictable load hops, and well customers are intermingled with other customers. When you start with a dedicated VPC now you can more directly expose the network right to the customer. Want to connect via peer or private link? Sure, we got you. And performance? Well when you're in that dedicated instance you can co-locate in the exact AZ to your compute. To me as a database guy that has helped thousands upon thousands scale their apps and databases co-location within the same AZ is obvious. To others, their trade-offs create real engineering hurdles to overcome. Not to mention all the security risks and trade-offs.
1
1
17
1,558
Paul Laurence retweeted
Was talking with a Snowflake customer today about pg_lake and they were familiar with some of what we've been building but hadn't dug into the details. One thing I realized is what haven't talked in depth about is some of the Postgres extension architecture itself. While I've shared the architecture, how pg_lake is comprised is actually multiple extensions under the covers. In building Citus it was mostly one big monolithic extension, with pg_lake we invested much more in sort of a meta layer for the extension. Pg_lake is itself an extension but that is comprised of several other ones all coordinated under the covers. Think of each extension as an instrument in a band, pg_lake is the conductor, we even have the equipment manager which is the extension that manages all the versions of the various extensions (okay, okay the analogy is breaking down). But the short is this mechanism of smaller composable extensions means we can improve each in small ways without major releases, we can move faster, but with an extension version manager within there we can do this in a safe way. Pg_lake: A postgres extension full of Postgres extensions.
1
2
17
1,798
Paul Laurence retweeted
I’ve long boasted about extensions in Postgres, what you can do to make Postgres work for entirely new use cases is unmatched by other databases. Excited to add graph functionality on Bridge to that list
Crunchy Bridge now supports the Apache AGE graph database extension. Use cipher queries to build and query your graph database.
1
9
1,098
Paul Laurence retweeted
Crunchy Bridge now supports the Apache AGE graph database extension. Use cipher queries to build and query your graph database.
3
2
19
2,273
Paul Laurence retweeted
New open source Postgres extension - pg_lake! 🧊 Create and query Iceberg tables 🔎 Query and import data to Iceberg, Parquet, CSV, JSON, and other object storage files 💾 Export \ copy data to lakehouses github.com/snowflake-labs/pg…
13
17
3
106
4,732
Paul Laurence retweeted
We are still looking for a few more speakers for this year's PostGIS day. Come tell us your story! It doesn't have to be groundbreaking - just sharing stories about production use of PostGIS makes this community stronger. snowflake.com/postgis-day-20…
1
1
8
533
Karen Jex (@karenhjex): Postgres Partitioning Best Practices: Sofia's Story postgr.es/p/7cT
5
1
21
1,540
Paul Laurence retweeted
Postgres 18 will be out later this month. The biggest news is asynchronous I/O which will be turned on by default for clusters and expected to mean read performance gains for everyone. More features and details in our blog ⬇️ crunchydata.com/blog/get-exc…
1
12
2
67
13,246
Paul Laurence retweeted
Other Postgres vendors’ tweets: "Our product is the best!" @crunchydata's tweets: "Here are some tips for everyday Postgres users and some deep-dive internals posts if you really wanna nerd out." 😲 (just kidding - much love to all the Postgres vendors ❤️)
1
4
1
13
2,222