System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar )
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk integer )
CREATE TABLE sui_coins ( object_id varchar, status varchar, coin_type varchar, balance varchar, owner varchar )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain varchar, contract_address varchar, name varchar, symbol varchar, deploy_block_number bigint, deploy_block_time bigint, erc_type varchar, owner varchar, traits varchar, description varchar, slug varchar, media_info varchar, image_url varchar, banner_image_url varchar, updated_at bigint, banner varchar, token_count bigint, floor_price varchar, floor_price_symbol varchar, floor_price_contract varchar, pk integer )
CREATE TABLE token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )

[User] List all ERC20 tokens from token_metas that are marked as a proxy (is_proxy = 1). Show their contract address, symbol, and name.

[Assistant] SELECT contract_address, symbol, name FROM token_metas WHERE is_erc20 = 1 AND is_proxy = 1

[User] Also include their total_supply.

[Assistant] SELECT contract_address, symbol, name, total_supply FROM token_metas WHERE is_erc20 = 1 AND is_proxy = 1

[User] Add the latest USD price for each of these tokens by joining with token_prices_latest.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.total_supply, tpl.price AS latest_usd_price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tm.is_proxy = 1

[User] Now, filter the results to only include tokens where the latest USD price is above 5.0.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.total_supply, tpl.price AS latest_usd_price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tm.is_proxy = 1 AND tpl.price > 5.0

[User] List NFTs minted on Ethereum after block 18000000, showing contract address, token ID, name, and mint_block_number.

[Assistant] SELECT contract_address, token_id, name, mint_block_number FROM nft_metadata WHERE blockchain = 'Ethereum' AND mint_block_number > 18000000

[User] Also include the mint_transaction_hash and mint_time for these NFTs.

[Assistant] SELECT contract_address, token_id, name, mint_block_number, mint_transaction_hash, mint_time FROM nft_metadata WHERE blockchain = 'Ethereum' AND mint_block_number > 18000000

[User] For each NFT, show the collection name it belongs to by joining nft_collections.

[Assistant] SELECT nm.contract_address, nm.token_id, nm.name, nm.mint_block_number, nm.mint_transaction_hash, nm.mint_time, nc.name AS collection_name FROM nft_metadata nm JOIN nft_collections nc ON nm.contract_address = nc.contract_address AND nm.blockchain = nc.blockchain WHERE nm.blockchain = 'Ethereum' AND nm.mint_block_number > 18000000

[User] Refine the list to only include NFTs from collections where the floor price is above 0.05 ETH.

[Assistant] SELECT nm.contract_address, nm.token_id, nm.name, nm.mint_block_number, nm.mint_transaction_hash, nm.mint_time, nc.name AS collection_name, nc.floor_price, nc.floor_price_symbol FROM nft_metadata nm JOIN nft_collections nc ON nm.contract_address = nc.contract_address AND nm.blockchain = nc.blockchain WHERE nm.blockchain = 'Ethereum' AND nm.mint_block_number > 18000000 AND nc.floor_price_symbol = 'ETH' AND CAST(nc.floor_price AS REAL) > 0.05

[User] Give me the max supply, creator, and current supply for all Avalanche tokens by their tick.

[Assistant]
SELECT tia.tick, tia.max_supply, tia.creator, tb.total_supply
FROM token_info_avalanche tia
LEFT JOIN token_balances tb ON tia.tick = tb.tick;

[User] Only show tokens where current supply is less than max supply.

[Assistant]
SELECT tia.tick, tia.max_supply, tia.creator, tb.total_supply
FROM token_info_avalanche tia
LEFT JOIN token_balances tb ON tia.tick = tb.tick
WHERE tb.total_supply < tia.max_supply;

[User] Also, add the last updated timestamp from token_info_avalanche.

[Assistant]
SELECT tia.tick, tia.max_supply, tia.creator, tb.total_supply, tia.updated_timestamp
FROM token_info_avalanche tia
LEFT JOIN token_balances tb ON tia.tick = tb.tick
WHERE tb.total_supply < tia.max_supply;

[User] List all SUI coins with status 'exists', showing their object_id, coin_type, and owner.

[Assistant] SELECT object_id, coin_type, owner FROM sui_coins WHERE status = 'exists'

[User] Join with sui_coins_metadata to include the symbol, name, and description for these coins. Filter to only include coins where the description contains the word 'DeFi'.

[Assistant] SELECT sc.object_id, sc.coin_type, sc.owner, sm.symbol, sm.name, sm.description FROM sui_coins sc JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type WHERE sc.status = 'exists' AND sm.description LIKE '%DeFi%'

[User] Group the results by owner and show the total balance (converted to numeric) for all 'DeFi' coins owned by each address. Order by total balance descending.

[Assistant] SELECT sc.owner, SUM(CAST(sc.balance AS REAL)) AS total_balance FROM sui_coins sc JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type WHERE sc.status = 'exists' AND sm.description LIKE '%DeFi%' GROUP BY sc.owner ORDER BY total_balance DESC

[User] List all NFTs on the blockchain with contract type 'ERC1155' and show their contract address, token id, and total number held by all wallets.

[Assistant]
SELECT contract_address, token_id, SUM(CAST(amount AS INTEGER)) AS total_held
FROM nft_holders
WHERE contract_type = 'ERC1155'
GROUP BY contract_address, token_id;

[User] Include also the number of unique holders for each NFT.

[Assistant]
SELECT contract_address, token_id, SUM(CAST(amount AS INTEGER)) AS total_held, COUNT(DISTINCT wallet_address) AS unique_holders
FROM nft_holders
WHERE contract_type = 'ERC1155'
GROUP BY contract_address, token_id;

[User] Now, show only NFTs with more than 10 unique holders.

[Assistant]
SELECT contract_address, token_id, SUM(CAST(amount AS INTEGER)) AS total_held, COUNT(DISTINCT wallet_address) AS unique_holders
FROM nft_holders
WHERE contract_type = 'ERC1155'
GROUP BY contract_address, token_id
HAVING COUNT(DISTINCT wallet_address) > 10;

[User] Show me the current amount held and wallet address for all wallets holding more than 100,000 units of the ERC20 token with contract address '0xeeee...'.

[Assistant] SELECT wallet_address, amount FROM erc20_balances WHERE contract_address = '0xeeee...' AND CAST(amount AS DECIMAL) > 100000;

[User] Could you also include the symbol and name for this token by joining with the token_metas table?

[Assistant] SELECT eb.wallet_address, eb.amount, tm.symbol, tm.name FROM erc20_balances eb JOIN token_metas tm ON eb.contract_address = tm.contract_address WHERE eb.contract_address = '0xeeee...' AND CAST(eb.amount AS DECIMAL) > 100000;

[User] List the top 5 ERC20 tokens by total supply, showing their symbol, contract_address, name, and total_supply.

[Assistant]
SELECT symbol, contract_address, name, total_supply
FROM token_metas
WHERE is_erc20 = 1
ORDER BY CAST(total_supply AS numeric) DESC
LIMIT 5;

[User] Now, also include the latest USD price for each token by joining with token_prices_latest.

[Assistant]
SELECT tm.symbol,
       tm.contract_address,
       tm.name,
       tm.total_supply,
       tpl.price AS usd_price
FROM token_metas tm
LEFT JOIN token_prices_latest tpl
  ON tm.contract_address = tpl.address
  AND tm.symbol = tpl.symbol
WHERE tm.is_erc20 = 1
ORDER BY CAST(tm.total_supply AS numeric) DESC
LIMIT 5;

[User] Actually, only include tokens where tm.is_proxy = 0 and usd_price > 10.

[Assistant]
SELECT tm.symbol,
       tm.contract_address,
       tm.name,
       tm.total_supply,
       tpl.price AS usd_price
FROM token_metas tm
JOIN token_prices_latest tpl
  ON tm.contract_address = tpl.address
  AND tm.symbol = tpl.symbol
WHERE tm.is_erc20 = 1
  AND tm.is_proxy = 0
  AND tpl.price > 10
ORDER BY CAST(tm.total_supply AS numeric) DESC
LIMIT 5;

[User] Finally, sort the results by usd_price descending and limit to top 3.

[Assistant]
SELECT tm.symbol,
       tm.contract_address,
       tm.name,
       tm.total_supply,
       tpl.price AS usd_price
FROM token_metas tm
JOIN token_prices_latest tpl
  ON tm.contract_address = tpl.address
  AND tm.symbol = tpl.symbol
WHERE tm.is_erc20 = 1
  AND tm.is_proxy = 0
  AND tpl.price > 10
ORDER BY tpl.price DESC
LIMIT 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )

[User] I want to know the total number of appointments per location along with the location name for appointments scheduled in March 2024.

[Assistant]
SELECT
  sl.location_name,
  COUNT(a.appointment_id) AS appointment_count
FROM appointments a
JOIN service_locations sl
  ON a.location_id = sl.location_id
WHERE a.scheduled_start_time >= '2024-03-01'
  AND a.scheduled_start_time < '2024-04-01'
GROUP BY sl.location_name;

[User] Actually, only include appointments with status 'Completed' and locations that are accessible.

[Assistant]
SELECT
  sl.location_name,
  COUNT(a.appointment_id) AS completed_appointment_count
FROM appointments a
JOIN service_locations sl
  ON a.location_id = sl.location_id
WHERE a.scheduled_start_time >= '2024-03-01'
  AND a.scheduled_start_time < '2024-04-01'
  AND a.status = 'Completed'
  AND sl.is_accessible = TRUE
GROUP BY sl.location_name;

[User] Provide a list of all future appointments showing appointment_id, scheduled_start_time, location_name, city, and state.

[Assistant]
SELECT
  a.appointment_id,
  a.scheduled_start_time,
  sl.location_name,
  sl.city,
  sl.state
FROM appointments a
JOIN service_locations sl
  ON a.location_id = sl.location_id
WHERE a.scheduled_start_time > CURRENT_TIMESTAMP;

[User] List the number of appointments for each booking method.

[Assistant]
SELECT
  a.booking_method,
  COUNT(*) AS appointment_count
FROM appointments a
GROUP BY a.booking_method;

[User] Filter this to only include booking methods that have more than 50 appointments.

[Assistant]
SELECT
  a.booking_method,
  COUNT(*) AS appointment_count
FROM appointments a
GROUP BY a.booking_method
HAVING COUNT(*) > 50;

[User] Also only consider appointments that are scheduled in the state of 'Texas'.

[Assistant]
SELECT
  a.booking_method,
  COUNT(*) AS appointment_count
FROM appointments a
JOIN service_locations sl
  ON a.location_id = sl.location_id
WHERE sl.state = 'Texas'
GROUP BY a.booking_method
HAVING COUNT(*) > 50;

[User] Now show the results ordered by appointment_count descending and limit to top 3 methods.

[Assistant]
SELECT
  a.booking_method,
  COUNT(*) AS appointment_count
FROM appointments a
JOIN service_locations sl
  ON a.location_id = sl.location_id
WHERE sl.state = 'Texas'
GROUP BY a.booking_method
HAVING COUNT(*) > 50
ORDER BY appointment_count DESC
LIMIT 3;

[User] List the name of each agency and the number of appointments associated with services from that agency.

[Assistant] SELECT T1.agency_name, COUNT(T2.appointment_id) FROM agencies AS T1 JOIN appointments AS T2 ON T1.agency_id = T2.agency_id GROUP BY T1.agency_name;

[User] How many appointments are recorded in the system?

[Assistant] SELECT COUNT(*) FROM appointments;

[User] Show the count of appointments for each status.

[Assistant] SELECT status, COUNT(*) FROM appointments GROUP BY status;

[User] Order the results by the count descending.

[Assistant] SELECT status, COUNT(*) FROM appointments GROUP BY status ORDER BY COUNT(*) DESC;

[User] Also, only include statuses with more than 10 appointments.

[Assistant] SELECT status, COUNT(*) FROM appointments GROUP BY status HAVING COUNT(*) > 10 ORDER BY COUNT(*) DESC;

[User] Show me all documents and the appointments scheduled by the same citizen. List the document ID, upload timestamp, document type, the corresponding appointment ID, and its scheduled start time.

[Assistant] SELECT T1.document_id, T1.upload_timestamp, T1.document_type, T2.appointment_id, T2.scheduled_start_time FROM government_services.documents AS T1 JOIN government_services.appointments AS T2 ON T1.citizen_id = T2.citizen_id


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players (
    player_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the player
    username character varying(100) NOT NULL UNIQUE, -- player's chosen display name
    email character varying(255) NOT NULL UNIQUE, -- player's email address for login/recovery
    password_hash text NOT NULL, -- securely hashed password
    registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the player account was created
    last_login timestamp with time zone, -- timestamp of the last successful login
    country_code character(2), -- player's country (ISO 3166-1 alpha-2)
    status character varying(20) NOT NULL DEFAULT 'active', -- account status (e.g., active, banned, suspended)
    profile_data jsonb, -- flexible field for avatar url, bio, preferences etc.
    PRIMARY KEY (player_id)
)
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)
CREATE TABLE gaming_technology.developers (
    developer_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the developer studio
    name character varying(150) NOT NULL UNIQUE, -- name of the development studio
    country character varying(100), -- country where the studio is based
    founded_year integer, -- year the studio was founded
    website character varying(255), -- developer's official website
    created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (developer_id)
)
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)

[User] I'd like a list of all games, displaying game title, developer name, and total number of achievements for each game.

[Assistant]
SELECT g.title, d.name AS developer_name, COUNT(a.achievement_id) AS total_achievements
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
LEFT JOIN gaming_technology.achievements a ON g.game_id = a.game_id
GROUP BY g.title, d.name;

[User] Can you also provide separate counts for hidden and visible achievements per game?

[Assistant]
SELECT g.title, d.name AS developer_name,
       COUNT(a.achievement_id) AS total_achievements,
       SUM(CASE WHEN a.hidden THEN 1 ELSE 0 END) AS hidden_achievements,
       SUM(CASE WHEN NOT a.hidden THEN 1 ELSE 0 END) AS visible_achievements
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
LEFT JOIN gaming_technology.achievements a ON g.game_id = a.game_id
GROUP BY g.title, d.name;

[User] Now, restrict the list to games released from 2020 onwards.

[Assistant]
SELECT g.title, d.name AS developer_name,
       COUNT(a.achievement_id) AS total_achievements,
       SUM(CASE WHEN a.hidden THEN 1 ELSE 0 END) AS hidden_achievements,
       SUM(CASE WHEN NOT a.hidden THEN 1 ELSE 0 END) AS visible_achievements
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
LEFT JOIN gaming_technology.achievements a ON g.game_id = a.game_id
WHERE g.release_date >= '2020-01-01'
GROUP BY g.title, d.name;

[User] Finally, only include games with more than 5 visible achievements and order by visible_achievements desc.

[Assistant]
SELECT g.title, d.name AS developer_name,
       COUNT(a.achievement_id) AS total_achievements,
       SUM(CASE WHEN a.hidden THEN 1 ELSE 0 END) AS hidden_achievements,
       SUM(CASE WHEN NOT a.hidden THEN 1 ELSE 0 END) AS visible_achievements
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
LEFT JOIN gaming_technology.achievements a ON g.game_id = a.game_id
WHERE g.release_date >= '2020-01-01'
GROUP BY g.title, d.name
HAVING SUM(CASE WHEN NOT a.hidden THEN 1 ELSE 0 END) > 5
ORDER BY visible_achievements DESC;

[User] Show usernames of players who own items of 'Legendary' rarity.

[Assistant] SELECT DISTINCT T1.username FROM players AS T1 JOIN player_inventory AS T2 ON T1.player_id = T2.player_id JOIN in_game_items AS T3 ON T2.item_id = T3.item_id WHERE T3.rarity = 'Legendary';

[User] Modify the query to also include the item name and the quantity the player owns for each such item.

[Assistant] SELECT T1.username, T3.item_name, T2.quantity FROM players AS T1 JOIN player_inventory AS T2 ON T1.player_id = T2.player_id JOIN in_game_items AS T3 ON T2.item_id = T3.item_id WHERE T3.rarity = 'Legendary';

[User] Change the request to find the total number of 'Legendary' items across all player inventories.

[Assistant] SELECT SUM(T1.quantity) FROM player_inventory AS T1 JOIN in_game_items AS T2 ON T1.item_id = T2.item_id WHERE T2.rarity = 'Legendary';

[User] Show the total number of 'Legendary' items per game, including the game title.

[Assistant] SELECT T3.title, SUM(T1.quantity) FROM player_inventory AS T1 JOIN in_game_items AS T2 ON T1.item_id = T2.item_id JOIN games AS T3 ON T2.game_id = T3.game_id WHERE T2.rarity = 'Legendary' GROUP BY T3.title;

[User] List all in-game items' names, types, and rarity along with their total cost in USD, for items that belong to games released on or after 2021-01-01.

[Assistant]
SELECT i.item_name, i.item_type, i.rarity, i.cost_amount
FROM gaming_technology.in_game_items i
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE g.release_date >= '2021-01-01' AND i.cost_currency = 'USD'
ORDER BY i.item_name;

[User] Please add the game's title to the results.

[Assistant]
SELECT i.item_name, i.item_type, i.rarity, i.cost_amount, g.title AS game_title
FROM gaming_technology.in_game_items i
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE g.release_date >= '2021-01-01' AND i.cost_currency = 'USD'
ORDER BY i.item_name;

[User] Now, show only items of rarity 'Epic' or 'Legendary'.

[Assistant]
SELECT i.item_name, i.item_type, i.rarity, i.cost_amount, g.title AS game_title
FROM gaming_technology.in_game_items i
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE g.release_date >= '2021-01-01' AND i.cost_currency = 'USD' AND i.rarity IN ('Epic', 'Legendary')
ORDER BY i.item_name;

[User] I got an error because some items have null cost_amount. Can you exclude those from the results?

[Assistant]
SELECT i.item_name, i.item_type, i.rarity, i.cost_amount, g.title AS game_title
FROM gaming_technology.in_game_items i
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE g.release_date >= '2021-01-01' AND i.cost_currency = 'USD' AND i.rarity IN ('Epic', 'Legendary') AND i.cost_amount IS NOT NULL
ORDER BY i.item_name;

[User] Retrieve the player_id, username, and game title for all players who have at least one item in their inventory.

[Assistant]
SELECT DISTINCT p.player_id, p.username, g.title
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id;

[User] Now include the total quantity of items each player holds per game.

[Assistant]
SELECT p.player_id, p.username, g.title, SUM(pi.quantity) AS total_quantity
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
GROUP BY p.player_id, p.username, g.title;

[User] Filter out entries where the total_quantity is less than 5.

[Assistant]
SELECT p.player_id, p.username, g.title, SUM(pi.quantity) AS total_quantity
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
GROUP BY p.player_id, p.username, g.title
HAVING SUM(pi.quantity) >= 5;

[User] Sort the results by total_quantity in descending order and limit to the top 10.

[Assistant]
SELECT p.player_id, p.username, g.title, SUM(pi.quantity) AS total_quantity
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
GROUP BY p.player_id, p.username, g.title
HAVING SUM(pi.quantity) >= 5
ORDER BY total_quantity DESC
LIMIT 10;

[User] Can you write a SQL statement that returns each server’s name, its region, and the average duration in seconds of all game sessions that took place on that server? Only include servers that have handled at least 5 sessions.

[Assistant]
SELECT s.server_name,
       s.region,
       AVG(gs.duration_seconds) AS avg_duration_seconds
FROM gaming_technology.servers s
JOIN gaming_technology.game_sessions gs
  ON s.server_id = gs.server_id
GROUP BY s.server_name, s.region
HAVING COUNT(gs.session_id) >= 5;

[User] Actually, I want to see only servers whose average session duration exceeds 1800 seconds.

[Assistant]
SELECT s.server_name,
       s.region,
       AVG(gs.duration_seconds) AS avg_duration_seconds
FROM gaming_technology.servers s
JOIN gaming_technology.game_sessions gs
  ON s.server_id = gs.server_id
GROUP BY s.server_name, s.region
HAVING COUNT(gs.session_id) >= 5
   AND AVG(gs.duration_seconds) > 1800;

[User] List game titles released on the 'PC' platform along with the count of servers currently hosting each game.

[Assistant] SELECT T1.title, count(T2.server_id) FROM games AS T1 JOIN servers AS T2 ON T1.game_id = T2.game_id WHERE T1.platform = 'PC' GROUP BY T1.title;

[User] Now, only show games with more than 3 servers and sort the results by the server count in descending order.

[Assistant] SELECT T1.title, count(T2.server_id) AS server_count FROM games AS T1 JOIN servers AS T2 ON T1.game_id = T2.game_id WHERE T1.platform = 'PC' GROUP BY T1.title HAVING count(T2.server_id) > 3 ORDER BY server_count DESC;

[User] How many players are there in each country?

[Assistant]
SELECT country_code, COUNT(*) AS player_count
FROM gaming_technology.players
GROUP BY country_code;

[User] Only include countries with more than 10 players.

[Assistant]
SELECT country_code, COUNT(*) AS player_count
FROM gaming_technology.players
GROUP BY country_code
HAVING COUNT(*) > 10;

[User] Also calculate what percentage of the total players each country represents.

[Assistant]
SELECT country_code,
       player_count,
       ROUND(player_count * 100.0 / total.total_players, 2) AS percentage_of_all
FROM (
  SELECT country_code, COUNT(*) AS player_count
  FROM gaming_technology.players
  GROUP BY country_code
  HAVING COUNT(*) > 10
) AS country_data
CROSS JOIN (
  SELECT COUNT(*) AS total_players
  FROM gaming_technology.players
) AS total;

[User] Order the results by this percentage in ascending order.

[Assistant]
SELECT country_code,
       player_count,
       ROUND(player_count * 100.0 / total.total_players, 2) AS percentage_of_all
FROM (
  SELECT country_code, COUNT(*) AS player_count
  FROM gaming_technology.players
  GROUP BY country_code
  HAVING COUNT(*) > 10
) AS country_data
CROSS JOIN (
  SELECT COUNT(*) AS total_players
  FROM gaming_technology.players
) AS total
ORDER BY percentage_of_all ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )

[User] Show me all cases that are associated with the court jurisdiction 'Federal Court'.

[Assistant] SELECT * FROM legal_services.cases WHERE court_jurisdiction = 'Federal Court';

[User] From these cases, only list those that have a status of 'Pending'.

[Assistant] SELECT * FROM legal_services.cases WHERE court_jurisdiction = 'Federal Court' AND status = 'Pending';

[User] For these pending cases in Federal Court, just show the case name, status, and lead lawyer ID.

[Assistant] SELECT case_name, status, lead_lawyer_id FROM legal_services.cases WHERE court_jurisdiction = 'Federal Court' AND status = 'Pending';

[User] List the names and numbers of cases that were opened in June 2024.

[Assistant] SELECT case_name, case_number FROM legal_services.cases WHERE date_opened >= '2024-06-01' AND date_opened < '2024-07-01';

[User] Find all cases that were closed in the year 2022, showing their case name, case number, and date closed.

[Assistant] SELECT case_name, case_number, date_closed FROM legal_services.cases WHERE date_closed >= '2022-01-01' AND date_closed < '2023-01-01';

[User] List the number of cases for each case type that are currently marked as 'Open'.

[Assistant] SELECT case_type, COUNT(*) FROM legal_services.cases WHERE status = 'Open' GROUP BY case_type;

[User] For each case type, calculate the average time to close cases in days, only including cases that have been closed.

[Assistant]
SELECT case_type,
       AVG(EXTRACT(EPOCH FROM (date_closed - date_opened)) / 86400) AS avg_close_days
FROM legal_services.cases
WHERE status = 'Closed'
  AND date_closed IS NOT NULL
GROUP BY case_type;

[User] Show me all pairs of cases led by the same lawyer, including both case names and the lead lawyer ID.

[Assistant]
SELECT c1.lead_lawyer_id,
       c1.case_name AS case_name_1,
       c2.case_name AS case_name_2
FROM legal_services.cases c1
JOIN legal_services.cases c2
  ON c1.lead_lawyer_id = c2.lead_lawyer_id
  AND c1.case_id < c2.case_id;

[User] Actually, only include pairs where the case types are also the same.

[Assistant]
SELECT c1.lead_lawyer_id,
       c1.case_name AS case_name_1,
       c2.case_name AS case_name_2
FROM legal_services.cases c1
JOIN legal_services.cases c2
  ON c1.lead_lawyer_id = c2.lead_lawyer_id
  AND c1.case_type = c2.case_type
  AND c1.case_id < c2.case_id;

[User] Also, show me the earliest opening date between the two cases for each pair.

[Assistant]
SELECT c1.lead_lawyer_id,
       c1.case_name AS case_name_1,
       c2.case_name AS case_name_2,
       LEAST(c1.date_opened, c2.date_opened) AS earliest_open_date
FROM legal_services.cases c1
JOIN legal_services.cases c2
  ON c1.lead_lawyer_id = c2.lead_lawyer_id
  AND c1.case_type = c2.case_type
  AND c1.case_id < c2.case_id;

[User] Show me all cases with a status of 'Pending', displaying their case name and court jurisdiction.

[Assistant] SELECT case_name, court_jurisdiction FROM legal_services.cases WHERE status = 'Pending';

[User] Actually, I only want the pending cases in the 'State Court' jurisdiction.

[Assistant] SELECT case_name, court_jurisdiction FROM legal_services.cases WHERE status = 'Pending' AND court_jurisdiction = 'State Court';

[User] Show the case number as well, and sort the results by case_name.

[Assistant] SELECT case_name, case_number, court_jurisdiction FROM legal_services.cases WHERE status = 'Pending' AND court_jurisdiction = 'State Court' ORDER BY case_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )

[User] List all conversation participants along with post_hashtag details where the participant's user_id matches the hashtag_id.

[Assistant]
SELECT cp.conversation_id, cp.user_id, ph.post_id, ph.hashtag_id
FROM social_media.conversation_participants cp
INNER JOIN social_media.post_hashtags ph
  ON cp.user_id = ph.hashtag_id;

[User] Only include participants who joined after '2024-01-01'.

[Assistant]
SELECT cp.conversation_id, cp.user_id, ph.post_id, ph.hashtag_id
FROM social_media.conversation_participants cp
INNER JOIN social_media.post_hashtags ph
  ON cp.user_id = ph.hashtag_id
WHERE cp.joined_at > '2024-01-01';

[User] Also, order the results by joined_at descending.

[Assistant]
SELECT cp.conversation_id, cp.user_id, ph.post_id, ph.hashtag_id
FROM social_media.conversation_participants cp
INNER JOIN social_media.post_hashtags ph
  ON cp.user_id = ph.hashtag_id
WHERE cp.joined_at > '2024-01-01'
ORDER BY cp.joined_at DESC;

[User] Finally, limit the output to the first 10 rows.

[Assistant]
SELECT cp.conversation_id, cp.user_id, ph.post_id, ph.hashtag_id
FROM social_media.conversation_participants cp
INNER JOIN social_media.post_hashtags ph
  ON cp.user_id = ph.hashtag_id
WHERE cp.joined_at > '2024-01-01'
ORDER BY cp.joined_at DESC
LIMIT 10;

[User] How many unique hashtags has each post been associated with? Please return post_id and unique_hashtag_count.

[Assistant]
SELECT post_id, COUNT(DISTINCT hashtag_id) AS unique_hashtag_count
FROM social_media.post_hashtags
GROUP BY post_id;

[User] Show me the user_id and number of conversations they have joined. Only include users who joined more than one conversation.

[Assistant]
SELECT user_id, COUNT(DISTINCT conversation_id) AS conversations_joined
FROM social_media.conversation_participants
GROUP BY user_id
HAVING COUNT(DISTINCT conversation_id) > 1;

[User] Add the time they joined their most recent conversation as latest_joined_at.

[Assistant]
SELECT user_id, COUNT(DISTINCT conversation_id) AS conversations_joined, MAX(joined_at) AS latest_joined_at
FROM social_media.conversation_participants
GROUP BY user_id
HAVING COUNT(DISTINCT conversation_id) > 1;

[User] Also, show the IDs of the conversations for each user as a comma-separated list.

[Assistant]
SELECT user_id,
  COUNT(DISTINCT conversation_id) AS conversations_joined,
  MAX(joined_at) AS latest_joined_at,
  STRING_AGG(DISTINCT conversation_id, ',') AS conversation_ids
FROM social_media.conversation_participants
GROUP BY user_id
HAVING COUNT(DISTINCT conversation_id) > 1;

[User] Which posts have been mentioned with at least one hashtag and also have users who joined the conversation corresponding to the post? Please show the post_id and the user_id of participants.

[Assistant]
SELECT ph.post_id, cp.user_id
FROM social_media.post_hashtags ph
INNER JOIN social_media.conversation_participants cp
  ON ph.post_id = cp.conversation_id;

[User] Can you also include the joined_at time for each user in the result?

[Assistant]
SELECT ph.post_id, cp.user_id, cp.joined_at
FROM social_media.post_hashtags ph
INNER JOIN social_media.conversation_participants cp
  ON ph.post_id = cp.conversation_id;

[User] Show me all replies to comments on post 'P500', including the reply content and the content of the parent comment.

[Assistant] SELECT T1.content AS reply_content, T2.content AS parent_comment_content FROM social_media.comments AS T1 JOIN social_media.comments AS T2 ON T1.parent_comment_id = T2.comment_id WHERE T1.post_id = 'P500'

[User] Only include replies created after '2024-06-15'.

[Assistant] SELECT T1.content AS reply_content, T2.content AS parent_comment_content FROM social_media.comments AS T1 JOIN social_media.comments AS T2 ON T1.parent_comment_id = T2.comment_id WHERE T1.post_id = 'P500' AND T1.created_at > '2024-06-15'

[User] Also, only show replies where the parent comment content contains the word 'question'.

[Assistant] SELECT T1.content AS reply_content, T2.content AS parent_comment_content FROM social_media.comments AS T1 JOIN social_media.comments AS T2 ON T1.parent_comment_id = T2.comment_id WHERE T1.post_id = 'P500' AND T1.created_at > '2024-06-15' AND T2.content LIKE '%question%'

[User] Order the results by reply creation time descending and limit to 10.

[Assistant] SELECT T1.content AS reply_content, T2.content AS parent_comment_content FROM social_media.comments AS T1 JOIN social_media.comments AS T2 ON T1.parent_comment_id = T2.comment_id WHERE T1.post_id = 'P500' AND T1.created_at > '2024-06-15' AND T2.content LIKE '%question%' ORDER BY T1.created_at DESC LIMIT 10

[User] List pairs of group conversations that were created on the same calendar day, showing their IDs and creation times.

[Assistant] SELECT T1.conversation_id AS convo1_id, T1.created_at AS convo1_created_at, T2.conversation_id AS convo2_id, T2.created_at AS convo2_created_at FROM social_media.conversations AS T1 JOIN social_media.conversations AS T2 ON DATE(T1.created_at) = DATE(T2.created_at) AND T1.conversation_id < T2.conversation_id WHERE T1.is_group_chat = true AND T2.is_group_chat = true

[User] Only include pairs where the conversation IDs both start with 'G' and order by the creation time descending.

[Assistant] SELECT T1.conversation_id AS convo1_id, T1.created_at AS convo1_created_at, T2.conversation_id AS convo2_id, T2.created_at AS convo2_created_at FROM social_media.conversations AS T1 JOIN social_media.conversations AS T2 ON DATE(T1.created_at) = DATE(T2.created_at) AND T1.conversation_id < T2.conversation_id WHERE T1.is_group_chat = true AND T2.is_group_chat = true AND T1.conversation_id LIKE 'G%' AND T2.conversation_id LIKE 'G%' ORDER BY T1.created_at DESC

[User] Count the number of group conversations created after '2024-05-01'.

[Assistant] SELECT COUNT(*) FROM social_media.conversations WHERE is_group_chat = true AND created_at > '2024-05-01'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] Please list the contact phone number and website for each insurance plan.

[Assistant] SELECT plan_id, plan_name, contact_phone, website FROM healthcare.insurance_plans;

[User] Show only the plans where the website contains '.gov'.

[Assistant] SELECT plan_id, plan_name, contact_phone, website FROM healthcare.insurance_plans WHERE website LIKE '%.gov%';

[User] Find all insurance plans that have both a contact phone number and a website listed, showing their provider and plan type.

[Assistant] SELECT insurance_provider, plan_type FROM healthcare.insurance_plans WHERE contact_phone IS NOT NULL AND website IS NOT NULL;

[User] Count the total number of unique insurance providers in the system.

[Assistant] SELECT COUNT(DISTINCT insurance_provider) FROM healthcare.insurance_plans;

[User] Count how many insurance plans exist for each plan type.

[Assistant]
SELECT plan_type, COUNT(*) AS plan_count
FROM healthcare.insurance_plans
GROUP BY plan_type;

[User] Now filter to only show plan types with more than 2 plans.

[Assistant]
SELECT plan_type, COUNT(*) AS plan_count
FROM healthcare.insurance_plans
GROUP BY plan_type
HAVING COUNT(*) > 2;

[User] List the plan ID, name, provider, and type for all insurance plans from 'Healthcare Partners' with a plan type of 'PPO'.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO';

[User] Now, only show those plans that also have a website listed.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO' AND website IS NOT NULL;

[User] Further refine the results to only include plans where the plan name contains the word 'Plus'.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO' AND website IS NOT NULL AND plan_name ILIKE '%Plus%';

[User] Finally, count how many such plans exist.

[Assistant] SELECT COUNT(*) FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO' AND website IS NOT NULL AND plan_name ILIKE '%Plus%';

[User] List all insurance providers along with the total number of plans they offer.

[Assistant]
SELECT insurance_provider, COUNT(*) AS plan_count
FROM healthcare.insurance_plans
GROUP BY insurance_provider;

[User] Only show providers with more than 2 plans.

[Assistant]
SELECT insurance_provider, COUNT(*) AS plan_count
FROM healthcare.insurance_plans
GROUP BY insurance_provider
HAVING COUNT(*) > 2;

[User] I want to find all pairs of insurance plans that share the same contact phone number, showing plan IDs, names, and the shared phone.

[Assistant]
SELECT p1.plan_id, p1.plan_name, p2.plan_id AS plan_id_2, p2.plan_name AS plan_name_2, p1.contact_phone
FROM healthcare.insurance_plans p1
JOIN healthcare.insurance_plans p2
  ON p1.contact_phone = p2.contact_phone
  AND p1.plan_id < p2.plan_id;

[User] Actually, exclude any plans where the contact phone is null or empty.

[Assistant]
SELECT p1.plan_id, p1.plan_name, p2.plan_id AS plan_id_2, p2.plan_name AS plan_name_2, p1.contact_phone
FROM healthcare.insurance_plans p1
JOIN healthcare.insurance_plans p2
  ON p1.contact_phone = p2.contact_phone
  AND p1.plan_id < p2.plan_id
WHERE p1.contact_phone IS NOT NULL
  AND p1.contact_phone <> '';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text PRIMARY KEY, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults int, num_children int, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.payments ( payment_id text PRIMARY KEY, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] List the room_id, room_number, and current_condition for all rooms that have 'Jacuzzi' in their features.

[Assistant]
SELECT room_id, room_number, current_condition
FROM hospitality_technology.rooms
WHERE features LIKE '%Jacuzzi%';

[User] Now, only include rooms that haven't been cleaned in the last 30 days.

[Assistant]
SELECT room_id, room_number, current_condition
FROM hospitality_technology.rooms
WHERE features LIKE '%Jacuzzi%'
  AND last_cleaned_at < NOW() - INTERVAL '30 days';

[User] Get me a list of all public reviews along with the guest's full name and the staff member who responded, including the overall rating and review date.

[Assistant]
SELECT rev.review_id,
       g.first_name || ' ' || g.last_name AS guest_name,
       rev.rating_overall,
       rev.review_date,
       s.first_name || ' ' || s.last_name AS responder_name
FROM hospitality_technology.reviews rev
LEFT JOIN hospitality_technology.guests g ON rev.guest_id = g.guest_id
LEFT JOIN hospitality_technology.staff s ON rev.response_staff_id = s.staff_id
WHERE rev.is_public = TRUE;

[User] Filter those to only include reviews with an overall rating above 4.

[Assistant]
SELECT rev.review_id,
       g.first_name || ' ' || g.last_name AS guest_name,
       rev.rating_overall,
       rev.review_date,
       s.first_name || ' ' || s.last_name AS responder_name
FROM hospitality_technology.reviews rev
LEFT JOIN hospitality_technology.guests g ON rev.guest_id = g.guest_id
LEFT JOIN hospitality_technology.staff s ON rev.response_staff_id = s.staff_id
WHERE rev.is_public = TRUE
  AND rev.rating_overall > 4;

[User] Also sort the results by review_date in ascending order.

[Assistant]
SELECT rev.review_id,
       g.first_name || ' ' || g.last_name AS guest_name,
       rev.rating_overall,
       rev.review_date,
       s.first_name || ' ' || s.last_name AS responder_name
FROM hospitality_technology.reviews rev
LEFT JOIN hospitality_technology.guests g ON rev.guest_id = g.guest_id
LEFT JOIN hospitality_technology.staff s ON rev.response_staff_id = s.staff_id
WHERE rev.is_public = TRUE
  AND rev.rating_overall > 4
ORDER BY rev.review_date ASC;

[User] List all available services in the 'Housekeeping' department that cost less than 20.

[Assistant]
SELECT service_id, service_name, price
FROM hospitality_technology.services
WHERE department = 'Housekeeping' AND is_available = true AND price < 20;

[User] Sort the results by service_name in ascending order.

[Assistant]
SELECT service_id, service_name, price
FROM hospitality_technology.services
WHERE department = 'Housekeeping' AND is_available = true AND price < 20
ORDER BY service_name ASC;

[User] Show me all rooms with their type names and base rates for property 'P001'.

[Assistant]
SELECT r.room_id, r.room_number, rt.type_name, rt.base_rate
FROM hospitality_technology.rooms r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id AND r.property_id = rt.property_id
WHERE r.property_id = 'P001';

[User] Actually, only include rooms on floor 2 and above, and sort by base_rate descending.

[Assistant]
SELECT r.room_id, r.room_number, rt.type_name, rt.base_rate, r.floor
FROM hospitality_technology.rooms r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id AND r.property_id = rt.property_id
WHERE r.property_id = 'P001' AND r.floor >= 2
ORDER BY rt.base_rate DESC;

[User] Show me the count of rooms by status.

[Assistant]
SELECT status,
       COUNT(*) AS room_count
FROM hospitality_technology.rooms
GROUP BY status;

[User] Actually, I need that breakdown by property as well.

[Assistant]
SELECT property_id,
       status,
       COUNT(*) AS room_count
FROM hospitality_technology.rooms
GROUP BY property_id, status
ORDER BY property_id, status;

[User] List all guests who have reservations for rooms that are currently marked as 'Maintenance'. Include the guest's full name, room number, and the reservation check-in and check-out dates.

[Assistant]
SELECT g.first_name || ' ' || g.last_name AS guest_name,
       r.room_number,
       res.check_in_date,
       res.check_out_date
FROM hospitality_technology.reservations res
JOIN hospitality_technology.guests g ON res.guest_id = g.guest_id
JOIN hospitality_technology.rooms r ON res.room_id = r.room_id
WHERE r.current_condition = 'Maintenance';

[User] Show me all spa service orders (service_id LIKE 'SPA%') in the last month with their guest names and total prices, ordered by total price in descending order.

[Assistant] SELECT so.order_id, g.first_name, g.last_name, so.total_price FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id WHERE so.service_id LIKE 'SPA%' AND so.order_timestamp >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) ORDER BY so.total_price DESC;

[User] Now, include only orders with a total price over $100 and show the property ID where the service was delivered.

[Assistant] SELECT so.order_id, g.first_name, g.last_name, so.total_price, r.property_id FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.reservations r ON so.reservation_id = r.reservation_id WHERE so.service_id LIKE 'SPA%' AND so.order_timestamp >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND so.total_price > 100 ORDER BY so.total_price DESC;

[User] The query is missing the service description. Can you include that as well?

[Assistant] SELECT so.order_id, g.first_name, g.last_name, so.total_price, r.property_id, s.description FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.reservations r ON so.reservation_id = r.reservation_id JOIN hospitality_technology.services s ON so.service_id = s.service_id WHERE so.service_id LIKE 'SPA%' AND so.order_timestamp >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND so.total_price > 100 ORDER BY so.total_price DESC;

[User] Actually, I need to see only orders delivered by staff with ID starting with 'STAFF1', and include the delivery timestamp.

[Assistant] SELECT so.order_id, g.first_name, g.last_name, so.total_price, r.property_id, s.description, so.delivery_timestamp FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.reservations r ON so.reservation_id = r.reservation_id JOIN hospitality_technology.services s ON so.service_id = s.service_id WHERE so.service_id LIKE 'SPA%' AND so.order_timestamp >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND so.total_price > 100 AND so.staff_id_delivered LIKE 'STAFF1%' ORDER BY so.total_price DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text PRIMARY KEY, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] Show me each completed order with order_id, the username of the user who placed it, asset_id, quantity, and price.

[Assistant]
SELECT
  o.order_id,
  u.username,
  o.asset_id,
  o.quantity,
  o.price
FROM trading_platform.orders o
JOIN trading_platform.users u ON o.user_id = u.user_id
WHERE o.status = 'completed';

[User] Also include the total executed quantity from trades for each order.

[Assistant]
SELECT
  o.order_id,
  u.username,
  o.asset_id,
  o.quantity,
  o.price,
  COALESCE(t.total_executed, 0) AS executed_quantity
FROM trading_platform.orders o
JOIN trading_platform.users u ON o.user_id = u.user_id
LEFT JOIN (
  SELECT order_id, SUM(quantity) AS total_executed
  FROM trading_platform.trades
  GROUP BY order_id
) t ON o.order_id = t.order_id
WHERE o.status = 'completed';

[User] Only include orders where some trades have occurred and calculate remaining_unfilled as order.quantity minus executed_quantity.

[Assistant]
SELECT
  o.order_id,
  u.username,
  o.asset_id,
  o.quantity,
  t.total_executed AS executed_quantity,
  (o.quantity - t.total_executed) AS remaining_unfilled
FROM trading_platform.orders o
JOIN trading_platform.users u ON o.user_id = u.user_id
JOIN (
  SELECT order_id, SUM(quantity) AS total_executed
  FROM trading_platform.trades
  GROUP BY order_id
) t ON o.order_id = t.order_id
WHERE o.status = 'completed'
  AND t.total_executed > 0;

[User] Limit to the top 5 orders by highest remaining_unfilled quantity.

[Assistant]
SELECT
  o.order_id,
  u.username,
  o.asset_id,
  o.quantity,
  t.total_executed AS executed_quantity,
  (o.quantity - t.total_executed) AS remaining_unfilled
FROM trading_platform.orders o
JOIN trading_platform.users u ON o.user_id = u.user_id
JOIN (
  SELECT order_id, SUM(quantity) AS total_executed
  FROM trading_platform.trades
  GROUP BY order_id
) t ON o.order_id = t.order_id
WHERE o.status = 'completed'
ORDER BY (o.quantity - t.total_executed) DESC
LIMIT 5;

[User] List each wallet with its wallet_id, user_id, and the total amount of unspent UTXOs associated with that wallet.

[Assistant]
SELECT
  w.wallet_id,
  w.user_id,
  COALESCE(SUM(u.amount), 0) AS unspent_total
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u
  ON w.address = u.address
  AND u.spent = false
GROUP BY w.wallet_id, w.user_id;

[User] Provide a summary for each transaction ID, showing the total amount of all its unspent UTXOs.

[Assistant] SELECT transaction_id, SUM(amount) FROM utxos WHERE spent = false GROUP BY transaction_id

[User] For each user, show their user_id, username, and the total number of trades they have participated in, counting both as buyer and as seller.

[Assistant]
SELECT
  u.user_id,
  u.username,
  COALESCE(b.buy_count, 0) + COALESCE(s.sell_count, 0) AS total_trades
FROM trading_platform.users u
LEFT JOIN (
  SELECT buyer_id AS user_id, COUNT(*) AS buy_count
  FROM trading_platform.trades
  GROUP BY buyer_id
) b ON u.user_id = b.user_id
LEFT JOIN (
  SELECT seller_id AS user_id, COUNT(*) AS sell_count
  FROM trading_platform.trades
  GROUP BY seller_id
) s ON u.user_id = s.user_id;

[User] Exclude users with zero trades and only include those whose total_trades is at least 5.

[Assistant]
SELECT
  u.user_id,
  u.username,
  COALESCE(b.buy_count, 0) + COALESCE(s.sell_count, 0) AS total_trades
FROM trading_platform.users u
LEFT JOIN (
  SELECT buyer_id AS user_id, COUNT(*) AS buy_count
  FROM trading_platform.trades
  GROUP BY buyer_id
) b ON u.user_id = b.user_id
LEFT JOIN (
  SELECT seller_id AS user_id, COUNT(*) AS sell_count
  FROM trading_platform.trades
  GROUP BY seller_id
) s ON u.user_id = s.user_id
WHERE (COALESCE(b.buy_count, 0) + COALESCE(s.sell_count, 0)) >= 5;

[User] List all orders, showing order ID, type, quantity, and the asset name.

[Assistant] SELECT o.order_id, o.order_type, o.quantity, a.name FROM trading_platform.orders o JOIN trading_platform.assets a ON o.asset_id = a.asset_id;

[User] Now, only include orders with 'completed' status and a quantity greater than 10.

[Assistant] SELECT o.order_id, o.order_type, o.quantity, a.name FROM trading_platform.orders o JOIN trading_platform.assets a ON o.asset_id = a.asset_id WHERE o.status = 'completed' AND o.quantity > 10;

[User] Actually, I also want to see the user ID of the user who placed the order.

[Assistant] SELECT o.order_id, o.order_type, o.quantity, a.name, w.user_id FROM trading_platform.orders o JOIN trading_platform.assets a ON o.asset_id = a.asset_id JOIN trading_platform.wallets w ON o.wallet_id = w.wallet_id WHERE o.status = 'completed' AND o.quantity > 10;

[User] The previous query didn't work because some completed orders might not be linked to a wallet? Can you show the order ID, type, quantity, asset name, but also include the user ID if available through the wallet linkage, and still filter by 'completed' status and quantity > 10?

[Assistant] SELECT o.order_id, o.order_type, o.quantity, a.name, w.user_id FROM trading_platform.orders o JOIN trading_platform.assets a ON o.asset_id = a.asset_id LEFT JOIN trading_platform.wallets w ON o.wallet_id = w.wallet_id WHERE o.status = 'completed' AND o.quantity > 10;

[User] For each user, show the total amount of unspent UTXOs across all their wallets.

[Assistant] SELECT w.user_id, SUM(u.amount) AS total_unspent_amount FROM trading_platform.wallets w JOIN trading_platform.utxos u ON w.address = u.address WHERE u.spent = FALSE GROUP BY w.user_id;

[User] Now, filter this list to only include users where the total unspent amount is greater than 500.

[Assistant] SELECT w.user_id, SUM(u.amount) AS total_unspent_amount FROM trading_platform.wallets w JOIN trading_platform.utxos u ON w.address = u.address WHERE u.spent = FALSE GROUP BY w.user_id HAVING SUM(u.amount) > 500;

[User] List all assets with their name, symbol, and type where the asset type is 'token'.

[Assistant] SELECT name, symbol, type FROM trading_platform.assets WHERE type = 'token';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )

[User] Find all pairs of different routes where the estimated duration in minutes is identical. For each pair, show both route IDs, their route numbers, and the shared duration.

[Assistant] SELECT r1.route_id AS route1_id, r1.route_number AS route1_number, r2.route_id AS route2_id, r2.route_number AS route2_number, r1.estimated_duration_minutes FROM transportation.routes r1 JOIN transportation.routes r2 ON r1.estimated_duration_minutes = r2.estimated_duration_minutes AND r1.route_id < r2.route_id;

[User] Retrieve route_number, description, and distance_km for routes that have a distance greater than the average distance of all routes.

[Assistant]
SELECT route_number, description, distance_km
FROM transportation.routes
WHERE distance_km > (
  SELECT AVG(distance_km)
  FROM transportation.routes
);

[User] Actually, I only want those routes where estimated_duration_minutes is less than 120, and sort by distance_km in descending order.

[Assistant]
SELECT route_number, description, distance_km
FROM transportation.routes
WHERE distance_km > (
  SELECT AVG(distance_km)
  FROM transportation.routes
)
  AND estimated_duration_minutes < 120
ORDER BY distance_km DESC;

[User] Which route numbers connect locations with a distance less than 80 km and more than 5 words in their description? Include the route type in the results.

[Assistant] SELECT route_number, type FROM transportation.routes WHERE distance_km < 80 AND array_length(regexp_split_to_array(description, '\s+'), 1) > 5;

[User] List pairs of distinct routes that originate from the same location but go to different destinations. Show the route ID and route number for both routes and the common origin location ID.

[Assistant]
SELECT
  r1.route_id AS route1_id,
  r1.route_number AS route1_number,
  r2.route_id AS route2_id,
  r2.route_number AS route2_number,
  r1.origin_location_id AS shared_origin_location_id
FROM transportation.routes AS r1
JOIN transportation.routes AS r2
  ON r1.origin_location_id = r2.origin_location_id
  AND r1.route_id < r2.route_id
WHERE
  r1.destination_location_id != r2.destination_location_id;

[User] Can you show me all routes where the origin_location_id is the same as the destination_location_id? List their route_id, route_number, and type.

[Assistant]
SELECT route_id, route_number, type
FROM transportation.routes
WHERE origin_location_id = destination_location_id;

[User] I'd also like to know the distance_km and estimated_duration_minutes for these routes.

[Assistant]
SELECT route_id, route_number, type, distance_km, estimated_duration_minutes
FROM transportation.routes
WHERE origin_location_id = destination_location_id;

[User] Finally, only include those routes where estimated_duration_minutes is less than 30 and sort by distance_km descending.

[Assistant]
SELECT route_id, route_number, type, distance_km, estimated_duration_minutes
FROM transportation.routes
WHERE origin_location_id = destination_location_id
  AND estimated_duration_minutes < 30
ORDER BY distance_km DESC;

[User] Show a list of all routes including their route number, type, distance in km, and estimated duration in minutes.

[Assistant]
SELECT
  route_number,
  type,
  distance_km,
  estimated_duration_minutes
FROM transportation.routes;

[User] Filter this list to only show routes of type 'Express'.

[Assistant]
SELECT
  route_number,
  type,
  distance_km,
  estimated_duration_minutes
FROM transportation.routes
WHERE
  type = 'Express';

[User] Sort the results by distance in descending order and limit to the top 5.

[Assistant]
SELECT
  route_number,
  type,
  distance_km,
  estimated_duration_minutes
FROM transportation.routes
WHERE
  type = 'Express'
ORDER BY
  distance_km DESC
LIMIT 5;

[User] Add the description and a column 'duration_per_km' showing the duration per kilometer.

[Assistant]
SELECT
  route_number,
  type,
  description,
  distance_km,
  estimated_duration_minutes,
  CAST(estimated_duration_minutes AS NUMERIC) / NULLIF(distance_km, 0) AS duration_per_km
FROM transportation.routes
WHERE
  type = 'Express'
ORDER BY
  distance_km DESC
LIMIT 5;

[User] Show me all pairs of routes where both routes have the same origin_location_id but different destination_location_id values. For each pair, display the first route's route_number, the second route's route_number, and their origin_location_id.

[Assistant]
SELECT r1.route_number AS first_route_number, r2.route_number AS second_route_number, r1.origin_location_id
FROM transportation.routes r1
JOIN transportation.routes r2
  ON r1.origin_location_id = r2.origin_location_id
  AND r1.route_id <> r2.route_id
  AND r1.destination_location_id <> r2.destination_location_id;

[User] Now, restrict this to only include pairs where the route type of both routes is 'Express', and order the result by first_route_number ascending.

[Assistant]
SELECT r1.route_number AS first_route_number, r2.route_number AS second_route_number, r1.origin_location_id
FROM transportation.routes r1
JOIN transportation.routes r2
  ON r1.origin_location_id = r2.origin_location_id
  AND r1.route_id <> r2.route_id
  AND r1.destination_location_id <> r2.destination_location_id
WHERE r1.type = 'Express' AND r2.type = 'Express'
ORDER BY first_route_number ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )

[User] Retrieve the route number and description for routes whose estimated duration exceeds 120 minutes.

[Assistant]
SELECT route_number, description
FROM transportation.routes
WHERE estimated_duration_minutes > 120;

[User] Also, filter to include only routes with distance greater than 200 km and order by distance_km descending.

[Assistant]
SELECT route_number, description
FROM transportation.routes
WHERE estimated_duration_minutes > 120
  AND distance_km > 200
ORDER BY distance_km DESC;

[User] List the first and last names of all drivers with status 'Active' along with the route number and type of all Express routes.

[Assistant]
SELECT d.first_name, d.last_name, r.route_number, r.type
FROM transportation.drivers d
CROSS JOIN transportation.routes r
WHERE d.status = 'Active' AND r.type = 'Express';

[User] Now, only include drivers hired after '2023-01-01'.

[Assistant]
SELECT d.first_name, d.last_name, r.route_number, r.type
FROM transportation.drivers d
CROSS JOIN transportation.routes r
WHERE d.status = 'Active'
  AND r.type = 'Express'
  AND d.hire_date > '2023-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.accounts ( account_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, account_number character varying(128) NOT NULL UNIQUE, account_type character varying(50) NOT NULL, balance numeric(19, 4) NOT NULL DEFAULT 0.00, currency character varying(3) NOT NULL, opened_date date NOT NULL, status character varying(32) NOT NULL, interest_rate numeric(5, 4), last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (account_id), FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id) )
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.employees ( employee_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(100) NOT NULL, department character varying(100), branch_id character varying(64), email character varying(128) NOT NULL UNIQUE, phone_extension character varying(20), hire_date date NOT NULL, termination_date date, manager_id character varying(64), status character varying(32) NOT NULL, PRIMARY KEY (employee_id), FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id) )
CREATE TABLE financial_services.loans ( loan_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL UNIQUE, loan_type character varying(50) NOT NULL, principal_amount numeric(19, 4) NOT NULL, current_principal_balance numeric(19, 4) NOT NULL, interest_rate numeric(6, 4) NOT NULL, term_months integer NOT NULL, origination_date date NOT NULL, maturity_date date NOT NULL, monthly_payment numeric(12, 4), collateral_description text, status character varying(32) NOT NULL, PRIMARY KEY (loan_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id) )

[User] Show me each account along with any loans linked to it. Include the account type, account balance, loan type, and loan principal amount.

[Assistant] SELECT a.account_type, a.balance, l.loan_type, l.principal_amount FROM financial_services.accounts a JOIN financial_services.loans l ON a.account_id = l.account_id

[User] Only include loans that are currently 'Active'.

[Assistant] SELECT a.account_type, a.balance, l.loan_type, l.principal_amount FROM financial_services.accounts a JOIN financial_services.loans l ON a.account_id = l.account_id WHERE l.status = 'Active'

[User] Now, summarize this data by account type, showing the total balance of accounts with active loans and the total principal amount of those active loans.

[Assistant] SELECT a.account_type, SUM(a.balance) AS total_account_balance, SUM(l.principal_amount) AS total_active_loan_principal FROM financial_services.accounts a JOIN financial_services.loans l ON a.account_id = l.account_id WHERE l.status = 'Active' GROUP BY a.account_type

[User] List all customers (customer_id) who have both an active checking account (account_type = 'Checking' and status = 'Open') and a home loan (loan_type = 'Home' and status = 'Active'), along with their total account balance and total loan principal amount.

[Assistant] SELECT a.customer_id, SUM(a.balance) AS total_account_balance, SUM(l.principal_amount) AS total_loan_principal FROM financial_services.accounts a JOIN financial_services.loans l ON a.account_id = l.account_id WHERE a.account_type = 'Checking' AND a.status = 'Open' AND l.loan_type = 'Home' AND l.status = 'Active' GROUP BY a.customer_id;

[User] Show me all securities (security_id, ticker_symbol, security_name) that are traded on the NASDAQ exchange and have a daily trading volume exceeding 1 million shares, along with the account details (account_id, account_number, balance) of customers who hold these securities in their accounts.

[Assistant] SELECT s.security_id, s.ticker_symbol, s.security_name, a.account_id, a.account_number, a.balance FROM financial_services.securities s JOIN financial_services.market_data md ON s.security_id = md.security_id JOIN financial_services.accounts a ON s.currency = a.currency WHERE s.exchange = 'NASDAQ' AND md.volume > 1000000 AND a.status = 'Open' GROUP BY s.security_id, s.ticker_symbol, s.security_name, a.account_id, a.account_number, a.balance;

[User] Now modify the query to only include accounts with a balance greater than $50,000 and sort them by balance in descending order.

[Assistant] SELECT s.security_id, s.ticker_symbol, s.security_name, a.account_id, a.account_number, a.balance FROM financial_services.securities s JOIN financial_services.market_data md ON s.security_id = md.security_id JOIN financial_services.accounts a ON s.currency = a.currency WHERE s.exchange = 'NASDAQ' AND md.volume > 1000000 AND a.status = 'Open' AND a.balance > 50000 GROUP BY s.security_id, s.ticker_symbol, s.security_name, a.account_id, a.account_number, a.balance ORDER BY a.balance DESC;

[User] For each loan, show the loan ID, principal amount, interest rate, and the balance and currency of the associated account.

[Assistant] SELECT l.loan_id, l.principal_amount, l.interest_rate, a.balance, a.currency FROM financial_services.loans l JOIN financial_services.accounts a ON l.account_id = a.account_id

[User] Restrict the list to loans originated in the last 12 months.

[Assistant] SELECT l.loan_id, l.principal_amount, l.interest_rate, a.balance, a.currency FROM financial_services.loans l JOIN financial_services.accounts a ON l.account_id = a.account_id WHERE l.origination_date >= CURRENT_DATE - INTERVAL '1 year'

[User] Also, only include accounts where the balance is greater than 10000.

[Assistant] SELECT l.loan_id, l.principal_amount, l.interest_rate, a.balance, a.currency FROM financial_services.loans l JOIN financial_services.accounts a ON l.account_id = a.account_id WHERE l.origination_date >= CURRENT_DATE - INTERVAL '1 year' AND a.balance > 10000

[User] Finally, sort the results by the loan interest rate in descending order.

[Assistant] SELECT l.loan_id, l.principal_amount, l.interest_rate, a.balance, a.currency FROM financial_services.loans l JOIN financial_services.accounts a ON l.account_id = a.account_id WHERE l.origination_date >= CURRENT_DATE - INTERVAL '1 year' AND a.balance > 10000 ORDER BY l.interest_rate DESC


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )

[User] List all policies that have a coverage limit greater than 750000 and a premium amount greater than 1000. Show the policy number, product ID, coverage limit, and premium amount.

[Assistant]
SELECT
  policy_number,
  product_id,
  coverage_limit,
  premium_amount
FROM insurance.policies
WHERE
  coverage_limit > 750000
  AND premium_amount > 1000;

[User] Okay, now only include policies that are currently 'Active' and have been active for at least 90 days.

[Assistant]
SELECT
  policy_number,
  product_id,
  coverage_limit,
  premium_amount
FROM insurance.policies
WHERE
  coverage_limit > 750000
  AND premium_amount > 1000
  AND status = 'Active'
  AND start_date <= CURRENT_DATE - INTERVAL '90 days';

[User] Instead of listing policies, count how many such active policies exist for each product ID. Show the product ID and the count, but only for products that have more than 5 such policies.

[Assistant]
SELECT
  product_id,
  COUNT(policy_id) AS active_policy_count
FROM insurance.policies
WHERE
  coverage_limit > 750000
  AND premium_amount > 1000
  AND status = 'Active'
  AND start_date <= CURRENT_DATE - INTERVAL '90 days'
GROUP BY
  product_id
HAVING
  COUNT(policy_id) > 5
ORDER BY
  active_policy_count DESC;

[User] Great. For those product IDs, also include the total premium amount across all policies included in the count. Order by the total premium amount descending.

[Assistant]
SELECT
  product_id,
  COUNT(policy_id) AS active_policy_count,
  SUM(premium_amount) AS total_premium
FROM insurance.policies
WHERE
  coverage_limit > 750000
  AND premium_amount > 1000
  AND status = 'Active'
  AND start_date <= CURRENT_DATE - INTERVAL '90 days'
GROUP BY
  product_id
HAVING
  COUNT(policy_id) > 5
ORDER BY
  total_premium DESC;

[User] Show all policies that started in 2024, including the policy_id, customer_id, and start_date. Order the results by start_date ascending.

[Assistant]
SELECT policy_id, customer_id, start_date
FROM insurance.policies
WHERE start_date >= '2024-01-01' AND start_date < '2025-01-01'
ORDER BY start_date ASC;

[User] Also, include the status of each policy and only show those with premium_amount over 3000.

[Assistant]
SELECT policy_id, customer_id, start_date, status
FROM insurance.policies
WHERE start_date >= '2024-01-01' AND start_date < '2025-01-01'
  AND premium_amount > 3000
ORDER BY start_date ASC;

[User] List all replacement policies where a customer received a new policy starting the day after their previous policy was cancelled. Return customer_id, original_policy_id, original_cancellation_date, new_policy_id, new_start_date.

[Assistant]
SELECT orig.customer_id,
       orig.policy_id      AS original_policy_id,
       orig.cancellation_date AS original_cancellation_date,
       nw.policy_id        AS new_policy_id,
       nw.start_date       AS new_start_date
FROM insurance.policies orig
JOIN insurance.policies nw
  ON orig.customer_id = nw.customer_id
 AND orig.cancellation_date IS NOT NULL
 AND nw.start_date = orig.cancellation_date + INTERVAL '1 day';

[User] Now include the premium_amount difference as premium_diff and only show cases where the new policy's premium is higher.

[Assistant]
SELECT orig.customer_id,
       orig.policy_id      AS original_policy_id,
       orig.cancellation_date AS original_cancellation_date,
       nw.policy_id        AS new_policy_id,
       nw.start_date       AS new_start_date,
       (nw.premium_amount - orig.premium_amount) AS premium_diff
FROM insurance.policies orig
JOIN insurance.policies nw
  ON orig.customer_id = nw.customer_id
 AND orig.cancellation_date IS NOT NULL
 AND nw.start_date = orig.cancellation_date + INTERVAL '1 day'
WHERE nw.premium_amount > orig.premium_amount;

[User] Show me all pairs of active policies for the same customer where their coverage periods overlap. Return customer_id, policy1_id, policy2_id, overlap_start, overlap_end.

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date)   AS overlap_end
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.policy_id < p2.policy_id
 AND p1.status = 'active'
 AND p2.status = 'active'
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date;

[User] I only want overlaps longer than 30 days and display the overlap days as overlap_days.

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date)   AS overlap_end,
       (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) AS overlap_days
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.policy_id < p2.policy_id
 AND p1.status = 'active'
 AND p2.status = 'active'
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date
HAVING (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) > 30;

[User] Order the results by overlap_days descending and limit to top 10.

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date)   AS overlap_end,
       (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) AS overlap_days
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.policy_id < p2.policy_id
 AND p1.status = 'active'
 AND p2.status = 'active'
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date
GROUP BY p1.customer_id, p1.policy_id, p2.policy_id
HAVING (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) > 30
ORDER BY overlap_days DESC
LIMIT 10;

[User] Find all customers who have at least two active policies with overlapping coverage periods. List the customer ID and the policy numbers of any two such overlapping active policies.

[Assistant]
SELECT
  p1.customer_id,
  p1.policy_number AS policy_number_1,
  p2.policy_number AS policy_number_2
FROM insurance.policies AS p1
JOIN insurance.policies AS p2
  ON p1.customer_id = p2.customer_id
  AND p1.policy_id < p2.policy_id
WHERE
  p1.status = 'Active'
  AND p2.status = 'Active'
  AND p1.start_date <= p2.end_date
  AND p1.end_date >= p2.start_date;

[User] Which customers have a canceled policy along with another active policy? Give customer_id, canceled_policy_id, active_policy_id.

[Assistant]
SELECT p_cancel.customer_id,
       p_cancel.policy_id AS canceled_policy_id,
       p_active.policy_id AS active_policy_id
FROM insurance.policies p_cancel
JOIN insurance.policies p_active
  ON p_cancel.customer_id = p_active.customer_id
WHERE p_cancel.status = 'canceled'
  AND p_active.status = 'active';

[User] Filter only cases where the cancellation_reason contains 'non-payment'.

[Assistant]
SELECT p_cancel.customer_id,
       p_cancel.policy_id AS canceled_policy_id,
       p_active.policy_id AS active_policy_id
FROM insurance.policies p_cancel
JOIN insurance.policies p_active
  ON p_cancel.customer_id = p_active.customer_id
WHERE p_cancel.status = 'canceled'
  AND p_active.status = 'active'
  AND p_cancel.cancellation_reason ILIKE '%non-payment%';

[User] I need to find all pairs of policies for each customer whose coverage periods overlap. Show customer_id, the two policy_ids for each overlapping pair.

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
  AND p1.policy_id < p2.policy_id
  AND p1.start_date <= p2.end_date
  AND p2.start_date <= p1.end_date;

[User] Can you also include the number of days of overlap between the two policies as overlap_days?

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id,
       (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) AS overlap_days
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
  AND p1.policy_id < p2.policy_id
  AND p1.start_date <= p2.end_date
  AND p2.start_date <= p1.end_date;

[User] Actually, restrict the results to only include pairs where both policies are currently active.

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id,
       (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) AS overlap_days
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
  AND p1.policy_id < p2.policy_id
  AND p1.start_date <= p2.end_date
  AND p2.start_date <= p1.end_date
WHERE p1.status = 'active'
  AND p2.status = 'active';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id character varying(64) NOT NULL, follower_user_id character varying(64) NOT NULL, following_user_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (follow_id), CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )

[User] List the usernames and email addresses of users who have participated in group chats, along with the names of those group chats.

[Assistant]
SELECT u.username, u.email, c.group_name
FROM social_media.users u
JOIN social_media.conversation_participants cp ON u.user_id = cp.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = TRUE;

[User] I only want to see users who joined the group chat in 2024. Show the join date as well.

[Assistant]
SELECT u.username, u.email, c.group_name, cp.joined_at
FROM social_media.users u
JOIN social_media.conversation_participants cp ON u.user_id = cp.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = TRUE
  AND cp.joined_at >= '2024-01-01';

[User] Which users have participated in conversations that are not group chats? Please show their usernames and the conversation IDs.

[Assistant]
SELECT u.username, cp.conversation_id
FROM social_media.conversation_participants cp
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = FALSE;

[User] Actually, can you show the time when they joined each conversation as well?

[Assistant]
SELECT u.username, cp.conversation_id, cp.joined_at
FROM social_media.conversation_participants cp
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = FALSE;

[User] Only include users who joined after March 1, 2024.

[Assistant]
SELECT u.username, cp.conversation_id, cp.joined_at
FROM social_media.conversation_participants cp
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = FALSE
  AND cp.joined_at > '2024-03-01';

[User] Show me all comments that are replies (i.e., have a parent_comment_id) on posts that include media, along with the comment content and creation time.

[Assistant]
SELECT c.comment_id, c.parent_comment_id, c.content, c.created_at
FROM social_media.comments c
JOIN social_media.posts p ON c.post_id = p.post_id
WHERE c.parent_comment_id IS NOT NULL
  AND p.media_url IS NOT NULL AND p.media_url <> '';

[User] Show me the full names of users and the total number of likes they have given to comments.

[Assistant]
SELECT u.full_name, COUNT(l.like_id) AS likes_given_to_comments
FROM social_media.users u
JOIN social_media.likes l ON u.user_id = l.user_id
WHERE l.comment_id IS NOT NULL
GROUP BY u.full_name;

[User] Can you also show the number of likes they have given to posts in the same result?

[Assistant]
SELECT u.full_name,
       COUNT(DISTINCT CASE WHEN l.comment_id IS NOT NULL THEN l.like_id END) AS likes_given_to_comments,
       COUNT(DISTINCT CASE WHEN l.post_id IS NOT NULL AND l.comment_id IS NULL THEN l.like_id END) AS likes_given_to_posts
FROM social_media.users u
LEFT JOIN social_media.likes l ON u.user_id = l.user_id
GROUP BY u.full_name;

[User] For each user, show their username and how many unique conversations they have sent at least one message in where the conversation is a group chat.

[Assistant]
SELECT u.username, COUNT(DISTINCT m.conversation_id) AS group_chats_messaged_in
FROM social_media.users u
JOIN social_media.messages m ON u.user_id = m.sender_user_id
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY u.username;

[User] Instead, show only users who have sent messages in more than one group chat, and include their email addresses.

[Assistant]
SELECT u.username, u.email, COUNT(DISTINCT m.conversation_id) AS group_chats_messaged_in
FROM social_media.users u
JOIN social_media.messages m ON u.user_id = m.sender_user_id
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY u.username, u.email
HAVING COUNT(DISTINCT m.conversation_id) > 1;

[User] Also add the most recent message time sent by each user in these group chats.

[Assistant]
SELECT u.username, u.email, COUNT(DISTINCT m.conversation_id) AS group_chats_messaged_in, MAX(m.sent_at) AS last_message_time
FROM social_media.users u
JOIN social_media.messages m ON u.user_id = m.sender_user_id
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY u.username, u.email
HAVING COUNT(DISTINCT m.conversation_id) > 1;

[User] List all posts along with the number of comments each post has received.

[Assistant]
SELECT p.post_id, COUNT(c.comment_id) AS comment_count
FROM social_media.posts p
LEFT JOIN social_media.comments c ON p.post_id = c.post_id
GROUP BY p.post_id;

[User] List the message_id, content, sender's username, and group_name for all messages in group chats.

[Assistant]
SELECT m.message_id, m.content, u.username, c.group_name
FROM social_media.messages m
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
JOIN social_media.users u ON m.sender_user_id = u.user_id
WHERE c.is_group_chat = TRUE;

[User] Exclude group chats that have fewer than 3 participants.

[Assistant]
SELECT m.message_id, m.content, u.username, c.group_name
FROM social_media.messages m
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
JOIN social_media.users u ON m.sender_user_id = u.user_id
JOIN (
  SELECT conversation_id
  FROM social_media.conversation_participants
  GROUP BY conversation_id
  HAVING COUNT(*) >= 3
) cp ON c.conversation_id = cp.conversation_id
WHERE c.is_group_chat = TRUE;

[User] And only show messages sent after '2024-06-01', ordering by sent_at ascending.

[Assistant]
SELECT m.message_id, m.content, u.username, c.group_name
FROM social_media.messages m
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
JOIN social_media.users u ON m.sender_user_id = u.user_id
JOIN (
  SELECT conversation_id
  FROM social_media.conversation_participants
  GROUP BY conversation_id
  HAVING COUNT(*) >= 3
) cp ON c.conversation_id = cp.conversation_id
WHERE c.is_group_chat = TRUE
  AND m.sent_at > '2024-06-01'
ORDER BY m.sent_at ASC;