Bird
Raised Fist0
PostgreSQLquery~10 mins

Composite types in PostgreSQL - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Composite types
Define Composite Type
Create Table Using Composite Type
Insert Data into Table
Query Data
Access Composite Type Fields
First, you define a composite type, then create a table using it, insert data, query it, and access its fields.
Execution Sample
PostgreSQL
CREATE TYPE address AS (
  street TEXT,
  city TEXT,
  zip_code TEXT
);

CREATE TABLE person (
  id SERIAL PRIMARY KEY,
  name TEXT,
  home_address address
);

INSERT INTO person (name, home_address) VALUES
('Alice', ROW('123 Main St', 'Springfield', '12345'));

SELECT name, home_address.city FROM person;
This code defines a composite type 'address', creates a table 'person' with a column of that type, inserts a row, and queries the city field.
Execution Table
StepActionEvaluationResult
1CREATE TYPE addressDefines composite type with fields street, city, zip_codeType 'address' created
2CREATE TABLE personCreates table with id, name, home_address of type addressTable 'person' created
3INSERT INTO personInsert row with name='Alice' and home_address=('123 Main St','Springfield','12345')Row inserted with id=1
4SELECT name, home_address.city FROM personRetrieve name and city field from home_addressReturns row: name='Alice', city='Springfield'
5End of operationsNo more commandsExecution complete
💡 All commands executed successfully; query returned expected data.
Variable Tracker
VariableStartAfter Step 3Final
address typeundefineddefined with fields street, city, zip_codedefined
person tableundefinedcreated with columns id, name, home_addresscreated
person rowsempty1 row inserted: (1, 'Alice', ('123 Main St', 'Springfield', '12345'))1 row present
Key Moments - 3 Insights
How do you access a field inside a composite type in a SELECT query?
You use dot notation like home_address.city as shown in step 4 of the execution_table.
Can you insert data into a composite type column using a simple tuple?
Yes, as in step 3, you insert data using parentheses with values matching the composite type fields.
Is the composite type created before the table that uses it?
Yes, step 1 creates the composite type before step 2 creates the table that uses it.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of step 4?
AReturns error due to wrong field access
BReturns empty result
CReturns row with name='Alice' and city='Springfield'
DReturns all fields of home_address
💡 Hint
Check the 'Result' column in step 4 of the execution_table.
At which step is the composite type 'address' defined?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column to find when 'CREATE TYPE address' happens.
If you wanted to add a new field 'state' to the composite type, which step would change?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Composite type definition happens in step 1, so changes to its fields affect that step.
Concept Snapshot
Composite types in PostgreSQL:
- Use CREATE TYPE to define a composite type with named fields.
- Use the composite type as a column type in tables.
- Insert data using tuples matching the composite structure.
- Access fields with dot notation (e.g., column.field).
- Composite types help group related data logically.
Full Transcript
This visual execution trace shows how to use composite types in PostgreSQL. First, a composite type named 'address' is created with fields street, city, and zip_code. Then, a table 'person' is created with a column 'home_address' of type 'address'. Next, a row is inserted into 'person' with name 'Alice' and an address tuple. Finally, a SELECT query retrieves the name and the city field from the composite address. The trace highlights how composite types are defined before use, how data is inserted as tuples, and how to access individual fields using dot notation.

Practice

(1/5)
1. What is a composite type in PostgreSQL?
easy
A. A special index type for faster queries
B. A built-in type for storing large text data
C. A custom type that groups multiple related fields together
D. A function that returns multiple rows

Solution

  1. Step 1: Understand the definition of composite types

    Composite types are user-defined types that group several fields into one unit, like a record.
  2. Step 2: Compare with other options

    Options A, B, and D describe unrelated PostgreSQL features, not composite types.
  3. Final Answer:

    A custom type that groups multiple related fields together -> Option C
  4. Quick Check:

    Composite type = grouped fields [OK]
Hint: Composite types group fields like a mini table row [OK]
Common Mistakes:
  • Confusing composite types with arrays
  • Thinking composite types are indexes
  • Mixing composite types with functions
2. Which of the following is the correct syntax to define a composite type named person with fields name (text) and age (integer)?
easy
A. CREATE TYPE person AS (name text, age integer);
B. CREATE TABLE person (name text, age integer);
C. CREATE TYPE person (name text, age integer);
D. CREATE COMPOSITE person AS (name text, age integer);

Solution

  1. Step 1: Recall the syntax for creating composite types

    The correct syntax uses CREATE TYPE with AS and parentheses listing fields and types.
  2. Step 2: Check each option

    CREATE TYPE person AS (name text, age integer); matches the correct syntax. CREATE TABLE person (name text, age integer); creates a table, not a type. CREATE TYPE person (name text, age integer); misses AS keyword. CREATE COMPOSITE person AS (name text, age integer); uses invalid keyword COMPOSITE.
  3. Final Answer:

    CREATE TYPE person AS (name text, age integer); -> Option A
  4. Quick Check:

    CREATE TYPE ... AS (...) is correct [OK]
Hint: Use CREATE TYPE name AS (fields) for composite types [OK]
Common Mistakes:
  • Using CREATE TABLE instead of CREATE TYPE
  • Omitting AS keyword
  • Using non-existent COMPOSITE keyword
3. Given the composite type and table:
CREATE TYPE address AS (city text, zip integer);
CREATE TABLE users (id serial, home address);

What will the query return?
SELECT (home).city FROM users WHERE id = 1;
medium
A. An error because you cannot access composite fields like this
B. The zip code of the home address for user with id 1
C. The entire home composite value as text
D. The city name stored in the home column for user with id 1

Solution

  1. Step 1: Understand composite field access syntax

    Using (home).city extracts the city field from the composite column home.
  2. Step 2: Analyze the query result

    The query selects city from home for user with id 1, so it returns that city name.
  3. Final Answer:

    The city name stored in the home column for user with id 1 -> Option D
  4. Quick Check:

    (column).field extracts field from composite [OK]
Hint: Use (column).field to get composite field value [OK]
Common Mistakes:
  • Trying to access composite fields without parentheses
  • Expecting entire composite instead of single field
  • Confusing city with zip field
4. Identify the error in this code snippet:
CREATE TYPE product_info AS (name text, price numeric);
CREATE TABLE products (id serial, info product_info);
INSERT INTO products (info) VALUES ('Laptop', 999.99);
medium
A. The serial type is invalid for id column
B. The INSERT statement syntax is incorrect for composite type
C. The table products should not use composite types
D. The CREATE TYPE statement is missing a semicolon

Solution

  1. Step 1: Check INSERT syntax for composite types

    When inserting a composite type, values must be wrapped in parentheses or ROW(), not as separate values.
  2. Step 2: Identify the error in the INSERT statement

    The statement tries to insert two separate values without wrapping them as a composite, causing syntax error.
  3. Final Answer:

    The INSERT statement syntax is incorrect for composite type -> Option B
  4. Quick Check:

    Insert composite as (value1, value2) or ROW(...) [OK]
Hint: Wrap composite values in parentheses or use ROW() [OK]
Common Mistakes:
  • Inserting composite fields as separate values
  • Forgetting parentheses around composite values
  • Misunderstanding serial type usage
5. You have a composite type location with fields latitude and longitude. You want to create a function that returns this composite type and use it in a query. Which of the following is the correct way to define the function?
hard
A. CREATE FUNCTION get_location() RETURNS location AS $$ BEGIN RETURN ROW(40.7128, -74.0060); END; $$ LANGUAGE plpgsql;
B. CREATE FUNCTION get_location() RETURNS location AS $$ BEGIN RETURN 40.7128, -74.0060; END; $$ LANGUAGE plpgsql;
C. CREATE FUNCTION get_location() RETURNS TABLE(latitude float, longitude float) AS $$ BEGIN RETURN (40.7128, -74.0060); END; $$ LANGUAGE plpgsql;
D. CREATE FUNCTION get_location() RETURNS location AS $$ BEGIN RETURN '40.7128, -74.0060'; END; $$ LANGUAGE plpgsql;

Solution

  1. Step 1: Understand how to return composite types from functions

    Functions returning composite types must return a row value, typically using ROW() constructor.
  2. Step 2: Analyze each option

    CREATE FUNCTION get_location() RETURNS location AS $$ BEGIN RETURN ROW(40.7128, -74.0060); END; $$ LANGUAGE plpgsql; correctly uses RETURN ROW(...) to return the composite type. CREATE FUNCTION get_location() RETURNS location AS $$ BEGIN RETURN 40.7128, -74.0060; END; $$ LANGUAGE plpgsql; returns multiple values without row constructor (parentheses or ROW()), causing syntax error. CREATE FUNCTION get_location() RETURNS TABLE(latitude float, longitude float) AS $$ BEGIN RETURN (40.7128, -74.0060); END; $$ LANGUAGE plpgsql; returns a table, not the composite type. CREATE FUNCTION get_location() RETURNS location AS $$ BEGIN RETURN '40.7128, -74.0060'; END; $$ LANGUAGE plpgsql; returns a string, not composite.
  3. Final Answer:

    CREATE FUNCTION get_location() RETURNS location AS $$ BEGIN RETURN ROW(40.7128, -74.0060); END; $$ LANGUAGE plpgsql; -> Option A
  4. Quick Check:

    Use RETURN ROW(...) for composite return [OK]
Hint: Use RETURN ROW(...) to return composite types in functions [OK]
Common Mistakes:
  • Returning values without row constructor
  • Returning string instead of composite
  • Confusing RETURNS TABLE with RETURNS composite