Comments are the sticky notes of the development world. Though small in stature, they provide an outsized impact when utilized effectively in code and databases.
This 3,000 word guide will explore PostgreSQL‘s versatile annotation features that allow embedding metadata, descriptions and technical detail into database systems.
Why Comments Matter
Before diving into how to comment databases, it‘s important to understand why commenting deserves front and center focus.
Per the StackOverflow 2021 Developer Survey, over 68% of developers recognize documentation and commenting as highly important. Lack of commenting is classed as one of the biggest code quality issues.
When it comes to PostgreSQL specifically, attentive use of comments provides advantages like:
- Onboarding Efficiency – Comments allow new developers to rapidly understand schema purpose without having to decode underlying logic.
- Troubleshooting Support – Debugging issues is simpler when hints and technical notes are sprinkled across the database via comments.
- Future-proofing – Heavily documented systems are easier to maintain, update and port as product needs evolve.
- Encapsulating Tribal Knowledge – Engineering teams can capture learnings and system nuances through detailed comments.
In fact, a ComputerWorld survey found that developers spend an average of 19.5% of their time understanding and decoding undocumented legacy code. Eliminating this waste via proactive commenting practices is thus pivotal for long term efficiency.
Simply put – databases with comments scale better. The upfront costs of commenting pale in comparison to downstream maintenance and agility implications.
Types of PostgreSQL Comments
PostgreSQL offers commenting capabilities tailored for use cases ranging from short code hints to schema level documentation:
- Single Line Comments – From brief reminders to disabling code sections
- Multi Line Comments – Enabling paragraph style annotations
- Object Comments – Directly attaching notes to tables, columns etc.
Now let‘s explore SQL syntax patterns and best practices for each comment variety.
Single Line Code Comments
Single line comments start with two dashes (--) and span until the end of a line as shown below:
-- Calculate order totals
SELECT id, quantity * unit_price AS total
FROM order_lines;
Anything after -- is ignored by the PostgreSQL parser when executing SQL statements. This allows developers to leave short contextual hints close to code logic without impacting functionality.
Some standard use cases include:
- Marking sections of scripts
- Leaving TODO reminders
- Temporarily commenting out blocks
- Hinting at query intention
- Micro-optimizations for repeated analysis
For example:
SELECT * FROM users; -- get latest user records
-- TODO: add filtering conditions
SELECT * FROM logins;
SELECT /*old*/ username FROM users; -- obsolete query
The limited line span does constrain detail levels for single line comments. They are best leveraged for targeted, tactical annotations wrapped close to code.
Multi Line Comment Blocks
For more descriptive annotations, PostgreSQL enables enclosing comments across multiple lines using /* */ block symbols:
/*
This is an example multi-line comment.
Useful for longer explanatory notes regarding:
- Query logic and intention
- Context around code sections
- Design decisions and considerations
Spans multiple lines until */ symbol.
*/
CREATE INDEX idx_names ON users(lastname, firstname);
Standard use cases include:
- Documentation around code logic flow
- Describing architectural decisions
- Schema design guidelines
- Change log notes
- Supporting technical detail
Pro-tip – Within functions and triggers, comments help codify complex business logic for easier analysis:
CREATE FUNCTION verify_user_age()
RETURNS TRIGGER AS /* Verify age rules */
$verify_user_age$
BEGIN
IF NEW.age < 18 THEN
RAISE EXCEPTION ‘User must be 18+‘;
END IF;
RETURN NEW;
END;
$verify_user_age$ LANGUAGE plpgsql;
For truly comprehensive documentation, multi-line comment blocks allow developers to embed complete sections of explanatory text with their PostgreSQL database code.
Direct Table and Object Comments
A uniquely powerful PostgreSQL feature is annotating tables, columns, views, functions etc. directly using SQL COMMENT clauses.
For example:
CREATE TABLE users (
id INT PRIMARY KEY,
email VARCHAR(200) NOT NULL
);
COMMENT ON TABLE users IS ‘Core user records table‘;
COMMENT ON COLUMN users.email IS ‘Primary login email for users‘;
This embeds descriptive context alongside the object definition itself. Unlike standalone comments which may go out of sync, these notes persist as part of the object.
Key reasons to use object comments:
- Self-documenting schema – Other engineers instantly know table/column purpose
- Encapsulates field intent – Critical when extending pre-existing databases
- DBA helper – Analysts can leverage notes when inspecting systems
Additional objects like views, triggers, functions etc. can be annotated as well for consistent documentation:
CREATE VIEW user_logins AS (...);
COMMENT ON VIEW user_logins IS ‘Daily user login aggregations‘;
CREATE FUNCTION verify_password() (...)
COMMENT ON FUNCTION verify_password IS ‘Checks password rules‘;
This metadata persists for easy discovery and also surfaces in IDE tooltips. Overall, direct object comments coupled with code annotations provide a no-compromise PostgreSQL documentation combo!
Commenting Best Practices
Now that we‘ve outlined PostgreSQL‘s range of commenting techniques, let‘s switch gears to recommendation logistics – when to comment, how much is too much and team consistency pointers.
When to Comment Database Code
Though no hard rules exist, consider adding comments when:
- Query/logic complexity exceeds 30 seconds comprehension time
- Multi-step procedures with key intention nuances
- Code stretches beyond 30 lines for a single block
- Schema changes or new relationships lack inherent clarity
Incrementally augment notes as functionality evolves. Be consistent rather than erratic with comment density.
Of course discretion is still key – avoid obvious statements like // connect to database on simple scripts. Prioritize strategic explanatory comments rather than compulsory annotations.
Promoting Standardization
For multi-developer environments, define team wise comment protocols covering:
- Line length limits
- Prefix syntax conventions e.g TODO, NOTE
- Object vs code comment separation
- Update cadence during migrations
Create PostgreSQL function templates including standardized header blocks for versioning, author info etc. This streamlines consistency across engineers.
Also use tooling like PgFormatter to align coding styles across SQL scripts. A little initial effort compounds doubly over time.
Comment Volume Recommendations
Studies analyzing heavily documented code indicate approximately 25-35% commented code delivers optimal comprehension. Beyond this, marginal utility drops while engineering effort keeps increasing.
Aim for describing complex logic, architectural choices and key intent indicators rather than compulsory annotations across mundane code.
PostgreSQL‘s versatile syntax does enable comprehensive documentation so resist over indexing. As with most things, balance and prioritization is key.
Advanced Usage Examples
While basic single/multi line comments deliver adequate value in simple systems, PostgreSQL offers additional capabilities:
Function & Trigger Documentation
Procedural code within PostgreSQL functions and triggers can become complex quickly. Hence metadata tags like:
/*
@v 1.0 - Verify user age before insert
@returns - Trigger allowing / denying record creation
@throws - Underage exception
*/
CREATE FUNCTION verify_user_age()...
These standardized TAGs enable auto-documentation in many IDEs without needing external tools.
Version tags also help identify retention policies or update strategies when modifying logic.
Automated Documentation Generation
Tools like PgDocs auto-generate technical specification documents and data dictionaries by parsing PostgreSQL object comments.
Meaning developers write comments once during normal work and reap documentation websites as byproduct! This enables dynamic API style docs from the source.
Metadata Driven Models
Comment annotations also empower predictive models in emerging areas like:
- Code comprehension – ML models utilize comments for suggesting optimal complexity improvements
- Query optimization – Backend compilers parse annotations for speedup opportunities
- Root cause analysis – Tracing issues leverages inline activity trail comments
- Test case generators – Generating edge case tests based on commentary
In essence, thoughtful comments today enable the next generation of hyper smart tools tomorrow!
Wrap Up
PostgreSQL‘s versatile annotation capabilities – across single line, multi line and object comments – enable developers to embed the perfect volume of contextual metadata across their database systems.
By outlining code intention, design decisions, architectural layers and technical nuances, engineers reap efficiency and consistency gains for years to come. Plus self-documenting database systems with inherant tribal knowledge make future evolution, troubleshooting and onboarding simpler.
So while it does require some incremental design effort, proactive commenting pays exponential dividends in the long run. Ultimately, DATABASES WITH COMMENTS SCALE BETTER!
What annotation best practices have you observed? Share your experiences below!


