Understanding Columns and Rows
Tables are fundamentally composed of columns and rows. Columns represent different attributes of the data. For example, in a users table, you might include columns for the user’s name, age, gender, email, and addresses. Each column is designed to store a specific type of information.
Data Types in PostgreSQL
Just as programming languages have data types, so do databases. When defining a column, you must specify its data type based on the attribute’s nature. For numeric values—such as the total number of likes or retweets in a social media app—use integer or decimal types, similar to Python’s integers and floats. For text-based data like names, emails, or addresses, PostgreSQL offers data types such as VARCHAR (which stands for varying character) and TEXT, analogous to Python strings. Additionally, PostgreSQL supports Boolean values (true/false), just like Python. When you need to represent a collection of values, PostgreSQL provides an array type, much like Python lists. However, it is often more effective to establish a separate table when dealing with multiple related items.
Primary Keys
When creating a table, you designate one or more columns as the primary key. The primary key uniquely identifies each record in the table, ensuring no two rows share the same key. While this is commonly an “ID” column, any unique attribute—such as an email address in a users table—can serve as the primary key. Other unique identifiers like phone numbers or social security numbers can also be used.
Column Constraints
In addition to specifying data types, you can enforce extra constraints on table columns to maintain data integrity.Unique Constraint
A unique constraint ensures that every entry in a specific column contains a distinct value. For example, if you want to ensure that no two users have the same name, you can add a unique constraint to the name column. PostgreSQL then validates entries, throwing an error if a duplicate is detected.
Not Null Constraint
By default, PostgreSQL allows columns to contain null values. For instance, if you create a user without specifying a name or age, PostgreSQL will store a null value in those columns. To enforce that certain columns always contain a valid entry, you can apply a NOT NULL constraint. This ensures that any attempt to insert a record without a necessary value will result in an error.
Ensuring your constraints are well-defined is key to maintaining the integrity and reliability of your database.