Creating Databases and Tables in PostgreSQL
# CHAPTER 4
Creating Databases and Tables in PostgreSQL
1. Introduction
You have installed PostgreSQL, opened pgAdmin, and learned the theory of normalization. Now it is time to write code. The SQL language is divided into sub-languages. Creating the physical structures (databases, tables, columns) is called Data Definition Language (DDL). In this chapter, we will act as database architects, writing the SQL commands that construct the blank canvases where our data will eventually live.2. Learning Objectives
By the end of this chapter, you will be able to:-
Use
CREATE DATABASEto initialize a new database.
- Switch between databases using the CLI.
-
Use
CREATE TABLEto architect columns and data types.
- Understand basic PostgreSQL syntax rules.
-
Use
DROP TABLEto permanently delete structures.
3. Creating a Database
A PostgreSQL cluster can hold hundreds of distinct databases. Let's create one for a new University application.Open the pgAdmin Query Tool (or the psql CLI) and type:
*Note: In pgAdmin, you may need to right-click the "Databases" tab and hit "Refresh" to see your new university_db appear in the left sidebar.*
Important: If you are using psql (the command line), you must explicitly connect to the new database before creating tables inside it. Type \c university_db to switch connections. In pgAdmin, simply open a new Query Tool specifically on the university_db node.
4. Creating a Table
Now that we are insideuniversity_db, let's create a table to hold our students. We use the CREATE TABLE command, followed by a list of columns and their designated "Data Types" (which we will cover deeply in Chapter 5).
Breaking down the syntax:
-
CREATE TABLE students: Declares the name of the table.
-
( ... ): All columns are defined inside parentheses.
-
student_id SERIAL PRIMARY KEY:SERIALtells PostgreSQL to automatically increment the ID (1, 2, 3).PRIMARY KEYmakes it the unique identifier.
-
VARCHAR(50): Text that is a maximum of 50 characters long.
-
,: Every column definition is separated by a comma. (Do NOT put a comma after the final column!).
-
;: Every SQL statement must end with a semicolon.
5. Viewing Table Structures
If you want to verify that your table was created correctly:-
In psql (CLI): Type
\d students
-
In pgAdmin: Expand
university_db->Schemas->public->Tables. Right-clickstudentsand selectProperties.
6. Deleting a Table (DROP)
If you made a mistake and want to start over, you can permanently obliterate the table and all data inside it using theDROP command.
7. Mini Project: Student Management Schema
Let's build a two-table relational schema for our university. We need Students and Courses, and we need to link them.*(Notice we created professors first. You cannot create a child table that references a parent if the parent doesn't exist yet!)*
8. Common Mistakes
- Trailing Commas: The most common syntax error for beginners is leaving a comma after the final column definition.
(id SERIAL, name VARCHAR(50), );
*Right:* (id SERIAL, name VARCHAR(50) );
-
Case Sensitivity: Unquoted identifiers (like table names) are automatically folded to lowercase in PostgreSQL. If you type
CREATE TABLE Users, PostgreSQL saves it asusers. Do not use Capital letters or Spaces in table names. Usesnake_case.
9. Best Practices
-
Use
IF NOT EXISTS: When writing automated deployment scripts, always useCREATE TABLE IF NOT EXISTS users. This prevents the script from crashing if it is run twice by accident.
10. Exercises
-
1.
Write the SQL command to create a
departmentstable with an auto-incrementing primary key and a department name.
-
2.
In the
psqlcommand line tool, what shortcut command is used to list the columns and structure of a specific table?
11. SQL Challenges
Write the DDL command to completely destroy a database namedold_test_db.
12. MCQ Quiz with Answers
What is the purpose of the SERIAL keyword in a PostgreSQL table definition?
If you are writing a script that creates a Users table and an Orders table, and Orders contains a Foreign Key pointing to Users, which table MUST be created first?
13. Interview Questions
- Q: Explain what DDL (Data Definition Language) is and provide three examples of DDL commands in PostgreSQL.
- Q: Describe the architectural naming conventions you would enforce when creating Tables and Columns in a PostgreSQL enterprise database.
14. FAQs
Q: What is thepublic schema in pgAdmin?
A: In PostgreSQL, a Database contains "Schemas". Think of schemas as folders inside the database. By default, all tables you create are placed into the public schema folder unless you specify otherwise.
15. Summary
You are now capable of architecting digital infrastructure. By utilizing theCREATE DATABASE and CREATE TABLE commands, you can construct the foundational arrays of columns and keys required to safely house complex relational data.
16. Next Chapter Recommendation
In our table creations, we used terms likeVARCHAR and INTEGER. If you choose the wrong data type, you will waste hard drive space or crash your application. In Chapter 5: PostgreSQL Data Types Explained, we will master the strict typing system of PostgreSQL.