Introduction
Composite types let you group different pieces of data together as one unit. This helps organize related information clearly.
Jump into concepts and practice - no test required
Composite types let you group different pieces of data together as one unit. This helps organize related information clearly.
CREATE TYPE type_name AS ( field1 data_type1, field2 data_type2 );
full_name with two text fields.CREATE TYPE full_name AS ( first_name TEXT, last_name TEXT );
address type with street, city, and zip code fields.CREATE TYPE address AS ( street TEXT, city TEXT, zip_code TEXT );
full_name and address as column types.CREATE TABLE people ( id SERIAL PRIMARY KEY, name full_name, home address );
This example creates a composite type full_name, then a table employees using it. It inserts two employees and selects their names by accessing the composite fields.
CREATE TYPE full_name AS ( first_name TEXT, last_name TEXT ); CREATE TABLE employees ( id SERIAL PRIMARY KEY, name full_name ); INSERT INTO employees (name) VALUES (ROW('Alice', 'Smith')); INSERT INTO employees (name) VALUES (ROW('Bob', 'Jones')); SELECT id, (name).first_name AS first_name, (name).last_name AS last_name FROM employees ORDER BY id;
You access composite fields using parentheses and dot notation, like (column).field.
Composite types can be nested inside other composite types.
They help keep related data together and make queries easier to read.
Composite types group related fields into one custom type.
They can be used as column types or function return types.
Access fields with (column).field syntax.
person with fields name (text) and age (integer)?CREATE TYPE address AS (city text, zip integer);
CREATE TABLE users (id serial, home address);SELECT (home).city FROM users WHERE id = 1;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);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?