📖 Scenario: You are building a simple user management system where each user needs a unique identifier that is hard to guess. Instead of using regular numbers, you want to use UUIDs (Universally Unique Identifiers) to identify users securely.
🎯 Goal: Create a PostgreSQL table with a uuid column as the primary key. Then, configure the table to automatically generate a new UUID for each user when a record is inserted.
📋 What You'll Learn
Create a table named users with a column id of type uuid.
Set the id column as the primary key.
Add a column username of type text.
Configure the id column to automatically generate a UUID using the gen_random_uuid() function from the pgcrypto extension.
Enable the pgcrypto extension if not already enabled.
💡 Why This Matters
🌍 Real World
UUIDs are widely used in real applications to uniquely identify records in a way that is hard to guess or collide, especially in distributed systems.
💼 Career
Understanding how to use UUIDs in databases is important for backend developers and database administrators to design secure and scalable systems.
Progress0 / 4 steps
1
Enable the pgcrypto extension
Write the SQL command to enable the pgcrypto extension in PostgreSQL so you can use the gen_random_uuid() function.
PostgreSQL
Hint
This extension provides the gen_random_uuid() function to generate UUIDs.
2
Create the users table with UUID primary key
Write the SQL command to create a table named users with two columns: id of type uuid as the primary key, and username of type text.
PostgreSQL
Hint
Use uuid as the data type for id and set it as the primary key.
3
Set default UUID generation for id column
Alter the users table so that the id column automatically generates a UUID using gen_random_uuid() when a new row is inserted.
PostgreSQL
Hint
Add DEFAULT gen_random_uuid() to the id column definition.
4
Insert a user without specifying id
Write an SQL insert statement to add a new user with username 'alice' into the users table without specifying the id. The id should be generated automatically.
PostgreSQL
Hint
Do not include the id column in the insert statement so it uses the default UUID.
Practice
(1/5)
1. What is the main purpose of using a UUID type in PostgreSQL?
easy
A. To store unique identifiers that avoid duplicates across tables or systems
B. To store large text data efficiently
C. To perform mathematical calculations faster
D. To create indexes automatically on a table
Solution
Step 1: Understand UUID purpose
UUID stands for Universally Unique Identifier, designed to be unique across space and time.
Step 2: Identify its use in PostgreSQL
PostgreSQL uses UUID to store unique IDs that avoid duplicates, especially in distributed systems.
Final Answer:
To store unique identifiers that avoid duplicates across tables or systems -> Option A
Quick Check:
UUID = Unique ID storage [OK]
Hint: UUIDs are for unique IDs, not for text or math [OK]
Common Mistakes:
Confusing UUID with text or numeric types
Thinking UUID speeds up math operations
Assuming UUID auto-creates indexes
2. Which of the following is the correct way to generate a random UUID in PostgreSQL?
easy
A. SELECT uuid_generate_v4();
B. SELECT random_uuid();
C. SELECT gen_random_uuid();
D. SELECT create_uuid();
Solution
Step 1: Recall PostgreSQL UUID functions
PostgreSQL's pgcrypto extension provides gen_random_uuid() to generate random UUIDs.
Step 2: Check function names
uuid_generate_v4() is from another extension (uuid-ossp), not default. The others are invalid.
Final Answer:
SELECT gen_random_uuid(); -> Option C
Quick Check:
Random UUID function = gen_random_uuid() [OK]
Hint: Use gen_random_uuid() with pgcrypto extension [OK]
Common Mistakes:
Using uuid_generate_v4() without enabling uuid-ossp
Typing random_uuid() which does not exist
Confusing function names
3. Given the table creation and insert statements below, what will be the output of the SELECT query?
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE users (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name TEXT);
INSERT INTO users (name) VALUES ('Alice'), ('Bob');
SELECT id, name FROM users ORDER BY name;
medium
A. Two rows with NULL ids for Alice and Bob
B. Two rows with unique UUIDs for Alice and Bob, ordered by name
C. Syntax error because gen_random_uuid() is not allowed in DEFAULT
D. One row only because UUID duplicates cause conflict
Solution
Step 1: Understand table and insert behavior
The table uses gen_random_uuid() as default for id. Inserting names without specifying id generates unique UUIDs automatically.
Step 2: Analyze SELECT output
The SELECT query returns all rows ordered by name, showing unique UUIDs for Alice and Bob.
Final Answer:
Two rows with unique UUIDs for Alice and Bob, ordered by name -> Option B
4. You run the following commands but get an error: ERROR: function gen_random_uuid() does not exist. What is the most likely fix?
SELECT gen_random_uuid();
medium
A. Change the query to SELECT random_uuid();
B. Use uuid_generate_v4() instead without any extension
C. Restart PostgreSQL server to refresh functions
D. Enable the pgcrypto extension using CREATE EXTENSION pgcrypto;
Solution
Step 1: Identify cause of missing function
The error means gen_random_uuid() is not available because the pgcrypto extension is not enabled.
Step 2: Apply correct fix
Enabling pgcrypto with CREATE EXTENSION pgcrypto; adds the function.
Final Answer:
Enable the pgcrypto extension using CREATE EXTENSION pgcrypto; -> Option D
Quick Check:
Missing function = enable pgcrypto [OK]
Hint: Enable pgcrypto extension to use gen_random_uuid() [OK]
Common Mistakes:
Trying uuid_generate_v4() without enabling uuid-ossp
Restarting server unnecessarily
Using random_uuid() which does not exist
5. You want to create a table that stores user sessions with a UUID primary key generated automatically, but also want to insert a specific UUID sometimes. Which table definition and insert statement is correct?
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE sessions (
session_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id INT
);
-- Insert with automatic UUID
INSERT INTO sessions (user_id) VALUES (101);
-- Insert with specific UUID
INSERT INTO sessions (session_id, user_id) VALUES ('550e8400-e29b-41d4-a716-446655440000', 102);
hard
A. This setup works correctly, allowing both automatic and manual UUID insertion
B. You cannot insert a specific UUID if DEFAULT is set for the column
C. You must disable the default to insert specific UUIDs
D. The UUID must be generated outside PostgreSQL and inserted as text
Solution
Step 1: Understand DEFAULT with manual insert
Setting DEFAULT to gen_random_uuid() means if no value is given, PostgreSQL generates one automatically.
Step 2: Check manual UUID insertion
When you specify session_id explicitly, PostgreSQL uses that value instead of the default.
Step 3: Confirm correctness
This allows both automatic UUID generation and manual UUID insertion in the same table.
Final Answer:
This setup works correctly, allowing both automatic and manual UUID insertion -> Option A
Quick Check:
DEFAULT allows manual override [OK]
Hint: DEFAULT UUID generates only if no value given [OK]
Common Mistakes:
Thinking DEFAULT blocks manual inserts
Trying to disable default for manual UUIDs
Assuming UUID must be generated outside PostgreSQL
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.