PostgreSQL Naming Conventions Explained
- Characters: Names can only consist of letters (a-z), numbers (0-9), and underscores (_).
- Starting: The name must begin with a letter or underscore.
- Case Sensitivity: By default, PostgreSQL is case-insensitive. This means that "table_name", "TABLE_NAME", and "tablename" are all considered the same. However, you can use double quotes (") to make a name case-sensitive (e.g., "MyTable").
Here are some additional points to consider:
- Uniqueness: Names must be unique within their object type. You can't have two tables with the same name.
- Length: There's a maximum length for names, although it's unlikely you'll reach it in most cases.
Following these conventions helps improve readability and maintainability of your PostgreSQL code. It ensures everyone working on the database understands what each object refers to by its name.
Valid Table Names:
- Following lower case with underscores:
customer_data
- Using CamelCase:
CustomerData
(although less common in PostgreSQL) - Using double quotes for case-sensitivity:
"Product Information"
- Starting with a number:
1customer_table
(needs to start with a letter or underscore) - Using special characters without quotes:
customer&data
(only letters, numbers, and underscores allowed by default) - Duplicate names: Creating two tables named
"users"
(each table name needs to be unique)
Example SQL Statements:
CREATE TABLE customer_data (
id SERIAL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE
);
CREATE TABLE "Product Information" (
product_id INT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
price DECIMAL(10,2)
);
Choosing the Right Method:
The best method depends on your team's preferences, project requirements, and existing codebase. Here are some factors to consider:
- Readability: The chosen style should make it easy to understand what each object represents.
- Consistency: Maintain a consistent style throughout the database for clarity.
- Team Agreement: Make sure everyone on the project understands and agrees to the chosen naming conventions.
Remember:
- Regardless of the method, avoid overly short or cryptic names.
- Use comments in your code to further explain complex objects.
- Tools like linters or code formatters can help enforce naming conventions.
postgresql naming-conventions