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.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )
CREATE TABLE hospitality_technology.reservations (
    reservation_id character varying(64) NOT NULL,  -- unique identifier for the booking
    property_id character varying(64) NOT NULL, -- FK to properties table
    guest_id character varying(64) NOT NULL, -- FK to guests table (primary guest)
    room_id character varying(64), -- FK to rooms table (assigned room, might be null initially)
    room_type_id character varying(64) NOT NULL, -- FK to room_types table (booked room type)
    check_in_date date NOT NULL, -- scheduled check-in date
    check_out_date date NOT NULL, -- scheduled check-out date
    actual_check_in_ts timestamp with time zone, -- actual check-in time
    actual_check_out_ts timestamp with time zone, -- actual check-out time
    num_adults integer NOT NULL, -- number of adults
    num_children integer DEFAULT 0, -- number of children
    status character varying(50) NOT NULL, -- e.g., Pending, Confirmed, CheckedIn, CheckedOut, Cancelled, NoShow
    booking_source character varying(100), -- e.g., Website, OTA (Expedia, Booking.com), Phone, WalkIn
    rate_plan_id character varying(64), -- FK to rate_plans table (optional)
    total_amount numeric(12, 2), -- estimated or final total cost
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    special_requests text, -- specific guest requests for this booking
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (reservation_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.services ( service_id.text, 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 character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )

[User] For each guest, show their full name and the total quantity of services they have ordered in the last 30 days.

[Assistant]
SELECT g.guest_id,
       g.first_name || ' ' || g.last_name AS full_name,
       SUM(so.quantity) AS total_quantity
FROM hospitality_technology.guests g
JOIN hospitality_technology.service_orders so
  ON g.guest_id = so.guest_id
WHERE so.order_timestamp >= NOW() - INTERVAL '30 days'
GROUP BY g.guest_id, g.first_name, g.last_name;

[User] Now only include guests whose total_quantity is greater than 10, and order by total_quantity descending.

[Assistant]
SELECT g.guest_id,
       g.first_name || ' ' || g.last_name AS full_name,
       SUM(so.quantity) AS total_quantity
FROM hospitality_technology.guests g
JOIN hospitality_technology.service_orders so
  ON g.guest_id = so.guest_id
WHERE so.order_timestamp >= NOW() - INTERVAL '30 days'
GROUP BY g.guest_id, g.first_name, g.last_name
HAVING SUM(so.quantity) > 10
ORDER BY total_quantity DESC;

[User] Also include the total spending for each of these guests in that period.

[Assistant]
SELECT g.guest_id,
       g.first_name || ' ' || g.last_name AS full_name,
       SUM(so.quantity) AS total_quantity,
       ROUND(SUM(so.total_price), 2) AS total_spending
FROM hospitality_technology.guests g
JOIN hospitality_technology.service_orders so
  ON g.guest_id = so.guest_id
WHERE so.order_timestamp >= NOW() - INTERVAL '30 days'
GROUP BY g.guest_id, g.first_name, g.last_name
HAVING SUM(so.quantity) > 10
ORDER BY total_quantity 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 gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )

[User] For each player who has unlocked at least two achievements, find the time difference in minutes between their first and last achievement unlock. Show player_id and the difference labeled last_minus_first_minutes.

[Assistant] SELECT player_id, EXTRACT(EPOCH FROM (MAX(unlocked_at) - MIN(unlocked_at))) / 60 AS last_minus_first_minutes FROM gaming_technology.player_achievements GROUP BY player_id HAVING COUNT(player_achievement_id) >= 2;

[User] Only include players where the difference is greater than 60 minutes.

[Assistant] SELECT player_id, EXTRACT(EPOCH FROM (MAX(unlocked_at) - MIN(unlocked_at))) / 60 AS last_minus_first_minutes FROM gaming_technology.player_achievements GROUP BY player_id HAVING COUNT(player_achievement_id) >= 2 AND EXTRACT(EPOCH FROM (MAX(unlocked_at) - MIN(unlocked_at))) / 60 > 60;

[User] Now, instead of the total difference, I want to find players who unlocked at least two *different* achievements within the *same hour* on the same day. Show their player_id and the date.

[Assistant] SELECT DISTINCT p1.player_id, DATE(p1.unlocked_at) AS unlock_date FROM gaming_technology.player_achievements p1 JOIN gaming_technology.player_achievements p2 ON p1.player_id = p2.player_id AND p1.achievement_id <> p2.achievement_id WHERE DATE(p1.unlocked_at) = DATE(p2.unlocked_at) AND EXTRACT(HOUR FROM p1.unlocked_at) = EXTRACT(HOUR FROM p2.unlocked_at);

[User] Filter this list to only show players who achieved this on a date after '2024-01-01' and order by the date descending.

[Assistant] SELECT DISTINCT p1.player_id, DATE(p1.unlocked_at) AS unlock_date FROM gaming_technology.player_achievements p1 JOIN gaming_technology.player_achievements p2 ON p1.player_id = p2.player_id AND p1.achievement_id <> p2.achievement_id WHERE DATE(p1.unlocked_at) = DATE(p2.unlocked_at) AND EXTRACT(HOUR FROM p1.unlocked_at) = EXTRACT(HOUR FROM p2.unlocked_at) AND DATE(p1.unlocked_at) > '2024-01-01' ORDER BY unlock_date 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 healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text PRIMARY KEY, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )

[User] Count how many prescriptions exist for each medication_id and order the results by the highest count first.

[Assistant]
SELECT medication_id, COUNT(*) AS prescription_count
FROM healthcare.prescriptions
GROUP BY medication_id
ORDER BY prescription_count 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 healthcare.doctors ( doctor_id text PRIMARY KEY, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id.text, patient_id.text, appointment_id.text, doctor_id.text, record_date.timestamp, chief_complaint.text, present_illness_history.text, past_medical_history.text, physical_examination_notes.text, assessment.text, treatment_plan.text, vitals.json, created_at.timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )

[User] List all insurance plans and the doctors whose hospital affiliation ID matches the plan ID. Include plan_name, insurance_provider, doctor first_name, and last_name.

[Assistant]
SELECT ip.plan_name, ip.insurance_provider, d.first_name, d.last_name
FROM healthcare.insurance_plans ip
JOIN healthcare.doctors d ON ip.plan_id = d.hospital_affiliation_id;

[User] Please add the doctor's specialty to the output and only include plans where the plan_type is 'POS'.

[Assistant]
SELECT ip.plan_name, ip.insurance_provider, d.first_name, d.last_name, d.specialty
FROM healthcare.insurance_plans ip
JOIN healthcare.doctors d ON ip.plan_id = d.hospital_affiliation_id
WHERE ip.plan_type = 'POS';


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 project_fundraising_record ( id character varying(32) NOT NULL, project_id character varying(32) NOT NULL, project_name character varying(128) NOT NULL, rounds_name character varying(32), investment_value numeric(38,14), investment_date character varying(128), introduction character varying(128), valuation numeric(38,14) )
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
 "CREATE TABLE narrative_info (",
    "narrative character varying(512) NOT NULL, -- the id of narrative",
    "top_3_coins text, -- the top 3 tokens in the narrative",
    "price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative",
    "price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative",
    "price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative",
    "market_cap double precision, -- the market cap of the narrative",
    "volume_24h double precision, -- the trade volume of the narrative",
    "trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative",
    "token_num bigint, -- total token number in the narrative",
    ",PRIMARY KEY (narrative));"

CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )
CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )

[User] Show all tokens on the 'Arbitrum' chain from DEX pools that have a 24-hour trading volume between $100,000 and $500,000. Display token symbol, price, and volume_24h.

[Assistant]
SELECT
  token_symbol,
  price,
  volume_24h
FROM token_dexpool_info
WHERE
  chain = 'Arbitrum' AND volume_24h BETWEEN 100000 AND 500000;

[User] Include their liquidity and 6-hour price change percentage in the results.

[Assistant]
SELECT
  token_symbol,
  price,
  volume_24h,
  liquidity,
  price_change_percentage_6h
FROM token_dexpool_info
WHERE
  chain = 'Arbitrum' AND volume_24h BETWEEN 100000 AND 500000;


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, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, 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.assets ( asset_id text, name text, symbol text, type text )
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, name text, description text, url text )
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, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] Show each wallet address, the user who owns it, and the number of UTXOs associated with that address.

[Assistant]
SELECT w.address, w.user_id, COUNT(u.utxo_id) AS utxo_count
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u ON w.address = u.address
GROUP BY w.address, w.user_id;

[User] I only want to see wallets that have at least 3 UTXOs.

[Assistant]
SELECT w.address, w.user_id, COUNT(u.utxo_id) AS utxo_count
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u ON w.address = u.address
GROUP BY w.address, w.user_id
HAVING COUNT(u.utxo_id) >= 3;

[User] Also, for each, show the total amount contained in those UTXOs.

[Assistant]
SELECT w.address, w.user_id, COUNT(u.utxo_id) AS utxo_count, COALESCE(SUM(u.amount), 0) AS total_amount
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u ON w.address = u.address
GROUP BY w.address, w.user_id
HAVING COUNT(u.utxo_id) >= 3;

[User] Restrict to only wallets created after '2024-01-01'.

[Assistant]
SELECT w.address, w.user_id, COUNT(u.utxo_id) AS utxo_count, COALESCE(SUM(u.amount), 0) AS total_amount
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u ON w.address = u.address
WHERE w.created_at > '2024-01-01'
GROUP BY w.address, w.user_id
HAVING COUNT(u.utxo_id) >= 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 social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )

[User] List all group conversations that were created after January 1st, 2023, and for each, show the names of hashtags that were created within the same month as the conversation.

[Assistant]
SELECT c.conversation_id, c.group_name, c.created_at AS conversation_created_at, h.tag_name, h.created_at AS hashtag_created_at
FROM social_media.conversations c
JOIN social_media.hashtags h
  ON DATE_TRUNC('month', c.created_at) = DATE_TRUNC('month', h.created_at)
WHERE c.is_group_chat = TRUE
  AND c.created_at > '2023-01-01';

[User] Instead of hashtag names, can you show their hashtag IDs?

[Assistant]
SELECT c.conversation_id, c.group_name, c.created_at AS conversation_created_at, h.hashtag_id, h.created_at AS hashtag_created_at
FROM social_media.conversations c
JOIN social_media.hashtags h
  ON DATE_TRUNC('month', c.created_at) = DATE_TRUNC('month', h.created_at)
WHERE c.is_group_chat = TRUE
  AND c.created_at > '2023-01-01';

[User] Also, filter only group chats where the group name contains the word 'Project'.

[Assistant]
SELECT c.conversation_id, c.group_name, c.created_at AS conversation_created_at, h.hashtag_id, h.created_at AS hashtag_created_at
FROM social_media.conversations c
JOIN social_media.hashtags h
  ON DATE_TRUNC('month', c.created_at) = DATE_TRUNC('month', h.created_at)
WHERE c.is_group_chat = TRUE
  AND c.created_at > '2023-01-01'
  AND c.group_name ILIKE '%Project%';


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.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )

[User] For each employee, find their first and last name along with the number of applications they've been assigned. Only include employees with at least 5 assigned applications.

[Assistant]
SELECT e.first_name,
       e.last_name,
       COUNT(a.application_id) AS assigned_count
FROM government_services.employees e
JOIN government_services.applications a ON e.employee_id = a.assigned_employee_id
GROUP BY e.first_name, e.last_name
HAVING COUNT(a.application_id) >= 5;


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.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )

[User] List pairs of documents uploaded by the same user for the same claim. Return uploaded_by, claim_id, document_id AS doc1_id, and the paired document_id AS doc2_id.

[Assistant]
SELECT cd1.uploaded_by,
       cd1.claim_id,
       cd1.document_id AS doc1_id,
       cd2.document_id AS doc2_id
FROM insurance.claim_documents cd1
JOIN insurance.claim_documents cd2
  ON cd1.claim_id = cd2.claim_id
 AND cd1.uploaded_by = cd2.uploaded_by
 AND cd1.document_id < cd2.document_id;

[User] Filter to only include pairs where the two documents have different mime_types.

[Assistant]
SELECT cd1.uploaded_by,
       cd1.claim_id,
       cd1.document_id AS doc1_id,
       cd2.document_id AS doc2_id
FROM insurance.claim_documents cd1
JOIN insurance.claim_documents cd2
  ON cd1.claim_id = cd2.claim_id
 AND cd1.uploaded_by = cd2.uploaded_by
 AND cd1.document_id < cd2.document_id
WHERE cd1.mime_type <> cd2.mime_type;


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.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.guests ( guest_id.text, 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.payments ( payment_id text, 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 )

[User] List all guests who have a loyalty_member_id, showing their guest_id, first_name, last_name, and loyalty_member_id.

[Assistant]
SELECT guest_id,
       first_name,
       last_name,
       loyalty_member_id
FROM hospitality_technology.guests
WHERE loyalty_member_id IS NOT NULL;

[User] Now filter to only include those guests who are from Canada and order by last_name.

[Assistant]
SELECT guest_id,
       first_name,
       last_name,
       loyalty_member_id
FROM hospitality_technology.guests
WHERE loyalty_member_id IS NOT NULL
  AND country_code = 'CA'
ORDER BY last_name 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 character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )

[User] Show me all cases along with the names and types of documents associated with them.

[Assistant]
SELECT c.case_id, c.case_number, c.case_name, d.document_name, d.document_type
FROM legal_services.cases c
LEFT JOIN legal_services.documents d ON c.case_id = d.case_id;

[User] Only include cases where at least one document has been uploaded after January 1st, 2024.

[Assistant]
SELECT c.case_id, c.case_number, c.case_name, d.document_name, d.document_type
FROM legal_services.cases c
JOIN legal_services.documents d ON c.case_id = d.case_id
WHERE d.upload_timestamp > '2024-01-01';

[User] Show only the most recently uploaded document for each case.

[Assistant]
SELECT sub.case_id, sub.case_number, sub.case_name, sub.document_name, sub.document_type, sub.upload_timestamp
FROM (
    SELECT c.case_id, c.case_number, c.case_name, d.document_name, d.document_type, d.upload_timestamp,
           ROW_NUMBER() OVER (PARTITION BY c.case_id ORDER BY d.upload_timestamp DESC) as rn
    FROM legal_services.cases c
    JOIN legal_services.documents d ON c.case_id = d.case_id
    WHERE d.upload_timestamp > '2024-01-01'
) sub
WHERE sub.rn = 1;


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 narrative_info ( narrative character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) )

[User] Show me the top 3 narratives by 24-hour trading volume, along with their 1-hour and 24-hour price change percentages.

[Assistant] SELECT narrative, volume_24h, price_change_percentage_1h, price_change_percentage_24h FROM narrative_info ORDER BY volume_24h DESC LIMIT 3;

[User] Actually, I only want narratives with a positive 7-day price change percentage.

[Assistant] SELECT narrative, volume_24h, price_change_percentage_1h, price_change_percentage_24h FROM narrative_info WHERE price_change_percentage_7d > 0 ORDER BY volume_24h DESC LIMIT 3;

[User] Can you also include the market cap for these narratives?

[Assistant] SELECT narrative, volume_24h, price_change_percentage_1h, price_change_percentage_24h, market_cap FROM narrative_info WHERE price_change_percentage_7d > 0 ORDER BY volume_24h DESC LIMIT 3;

[User] Now order the results by market cap instead of trading volume.

[Assistant] SELECT narrative, volume_24h, price_change_percentage_1h, price_change_percentage_24h, market_cap FROM narrative_info WHERE price_change_percentage_7d > 0 ORDER BY market_cap 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 transportation.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)

[User] Show me all maintenance logs for 'Oil Change' services performed in the last 6 months, including the vehicle ID, service date, and cost.

[Assistant] SELECT vehicle_id, service_date, cost FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '6 months';

[User] Can you also include the mechanic name and filter to only show services that cost more than $100?

[Assistant] SELECT vehicle_id, service_date, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '6 months' AND cost > 100;

[User] Now order these results by service date with the most recent first and limit to 10 records.

[Assistant] SELECT vehicle_id, service_date, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '6 months' AND cost > 100 ORDER BY service_date DESC LIMIT 10;


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.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )

[User] Show me all servers where current_players is 0, and include their server_id, server_name, and region.

[Assistant] SELECT server_id, server_name, region FROM gaming_technology.servers WHERE current_players = 0;

[User] Add the max_players and status columns.

[Assistant] SELECT server_id, server_name, region, max_players, status FROM gaming_technology.servers WHERE current_players = 0;

[User] Only show servers where status is not 'offline'.

[Assistant] SELECT server_id, server_name, region, max_players, status FROM gaming_technology.servers WHERE current_players = 0 AND status <> 'offline';

[User] Now sort the results by region ascending and max_players descending.

[Assistant] SELECT server_id, server_name, region, max_players, status FROM gaming_technology.servers WHERE current_players = 0 AND status <> 'offline' ORDER BY region ASC, max_players 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 transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
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 )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )

[User] List the number of trips and the average passenger count per vehicle.

[Assistant]
SELECT v.vehicle_id, COUNT(t.trip_id) AS trip_count, AVG(t.passenger_count) AS avg_passenger_count
FROM transportation.vehicles v
LEFT JOIN transportation.trips t ON v.vehicle_id = t.vehicle_id
GROUP BY v.vehicle_id;

[User] Only include vehicles that have transported more than 50 passengers in total.

[Assistant]
SELECT v.vehicle_id, COUNT(t.trip_id) AS trip_count, AVG(t.passenger_count) AS avg_passenger_count, SUM(t.passenger_count) AS total_passengers
FROM transportation.vehicles v
LEFT JOIN transportation.trips t ON v.vehicle_id = t.vehicle_id
GROUP BY v.vehicle_id
HAVING SUM(t.passenger_count) > 50;

[User] Can you add the vehicle make and model to the result?

[Assistant]
SELECT v.vehicle_id, v.make, v.model, COUNT(t.trip_id) AS trip_count, AVG(t.passenger_count) AS avg_passenger_count, SUM(t.passenger_count) AS total_passengers
FROM transportation.vehicles v
LEFT JOIN transportation.trips t ON v.vehicle_id = t.vehicle_id
GROUP BY v.vehicle_id, v.make, v.model
HAVING SUM(t.passenger_count) > 50;

[User] I am getting null for total_passengers for some vehicles, can you exclude vehicles with no trips?

[Assistant]
SELECT v.vehicle_id, v.make, v.model, COUNT(t.trip_id) AS trip_count, AVG(t.passenger_count) AS avg_passenger_count, SUM(t.passenger_count) AS total_passengers
FROM transportation.vehicles v
JOIN transportation.trips t ON v.vehicle_id = t.vehicle_id
GROUP BY v.vehicle_id, v.make, v.model
HAVING SUM(t.passenger_count) > 50;


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.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )

[User] List pairs of securities from the same issuer where one security was updated within the last 30 days, and the other was updated more than 90 days ago. Show issuer name, ticker symbols, and last_updated timestamps for both.

[Assistant] SELECT a.issuer_name, a.ticker_symbol AS ticker_symbol_a, a.last_updated AS last_updated_a, b.ticker_symbol AS ticker_symbol_b, b.last_updated AS last_updated_b FROM financial_services.securities AS a JOIN financial_services.securities AS b ON a.issuer_name = b.issuer_name WHERE a.security_id != b.security_id AND a.last_updated >= CURRENT_DATE - INTERVAL '30 days' AND b.last_updated < CURRENT_DATE - INTERVAL '90 days';

[User] Only include issuers who have more than 5 securities in total.

[Assistant] WITH IssuerCounts AS (SELECT issuer_name, COUNT(*) AS total_securities FROM financial_services.securities WHERE issuer_name IS NOT NULL GROUP BY issuer_name HAVING COUNT(*) > 5) SELECT a.issuer_name, a.ticker_symbol AS ticker_symbol_a, a.last_updated AS last_updated_a, b.ticker_symbol AS ticker_symbol_b, b.last_updated AS last_updated_b FROM financial_services.securities AS a JOIN financial_services.securities AS b ON a.issuer_name = b.issuer_name JOIN IssuerCounts ic ON a.issuer_name = ic.issuer_name WHERE a.security_id != b.security_id AND a.last_updated >= CURRENT_DATE - INTERVAL '30 days' AND b.last_updated < CURRENT_DATE - INTERVAL '90 days';

[User] Order the results by issuer name, then by the more recently updated security's ticker symbol.

[Assistant] WITH IssuerCounts AS (SELECT issuer_name, COUNT(*) AS total_securities FROM financial_services.securities WHERE issuer_name IS NOT NULL GROUP BY issuer_name HAVING COUNT(*) > 5) SELECT a.issuer_name, a.ticker_symbol AS ticker_symbol_a, a.last_updated AS last_updated_a, b.ticker_symbol AS ticker_symbol_b, b.last_updated AS last_updated_b FROM financial_services.securities AS a JOIN financial_services.securities AS b ON a.issuer_name = b.issuer_name JOIN IssuerCounts ic ON a.issuer_name = ic.issuer_name WHERE a.security_id != b.security_id AND a.last_updated >= CURRENT_DATE - INTERVAL '30 days' AND b.last_updated < CURRENT_DATE - INTERVAL '90 days' ORDER BY a.issuer_name ASC, a.ticker_symbol 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 healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] Show me all male patients who have received more than one prescription, including their full name, date of birth, and the total number of prescriptions.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
WHERE p.gender = 'Male'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] Could you also include the names of the medications they've been prescribed?

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions, STRING_AGG(pr.medication_id, ', ') AS medication_ids
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
WHERE p.gender = 'Male'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] Actually, I only want to see patients who also have at least one active diagnosis.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions, STRING_AGG(DISTINCT pr.medication_id, ', ') AS medication_ids
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
WHERE p.gender = 'Male' AND d.status = 'Active'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] One of the medication_ids columns seems off, could you instead also show the medication_id and dosage for each prescription individually, as well as the diagnosis_code for their active diagnosis?

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, pr.prescription_id, pr.medication_id, pr.dosage, d.diagnosis_code
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
WHERE p.gender = 'Male' AND d.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 character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.posts (
    post_id character varying(64) NOT NULL, -- unique identifier for the post
    user_id character varying(64) NOT NULL, -- identifier of the user who created the post (FK to users.user_id)
    content text, -- textual content of the post
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of post creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last post edit
    visibility character varying(20) NOT NULL DEFAULT 'public', -- visibility ('public', 'friends', 'private')
    location_lat numeric(9,6), -- latitude of post location
    location_lon numeric(9,6), -- longitude of post location
    PRIMARY KEY (post_id)
)
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 character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags (
    hashtag_id character varying(64) NOT NULL, -- unique identifier for the hashtag
    tag_name character varying(100) NOT NULL UNIQUE, -- the actual hashtag text (without '#')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when the hashtag was first used
    PRIMARY KEY (hashtag_id)
)
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
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 character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
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
)

[User] List all group chats created in 2024, showing the group_name, conversation_id, and creation time.

[Assistant]
SELECT conversation_id, group_name, created_at
FROM social_media.conversations
WHERE is_group_chat = true AND created_at >= '2024-01-01' AND created_at < '2025-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 transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)

[User] List vehicle make, model, maintenance service date, and cost for all maintenance logs.

[Assistant] SELECT v.make, v.model, ml.service_date, ml.cost FROM transportation.vehicles AS v JOIN transportation.maintenance_logs AS ml ON v.vehicle_id = ml.vehicle_id;

[User] Filter this list to only include maintenance logs with a cost greater than 500.

[Assistant] SELECT v.make, v.model, ml.service_date, ml.cost FROM transportation.vehicles AS v JOIN transportation.maintenance_logs AS ml ON v.vehicle_id = ml.vehicle_id WHERE ml.cost > 500;

[User] Now, show the average cost of maintenance for each vehicle make, only considering logs where the cost was greater than 500.

[Assistant] SELECT v.make, AVG(ml.cost) AS average_maintenance_cost FROM transportation.vehicles AS v JOIN transportation.maintenance_logs AS ml ON v.vehicle_id = ml.vehicle_id WHERE ml.cost > 500 GROUP BY v.make;


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.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )

[User] Show each policy number and the total amount paid for it across all premium payments received so far.

[Assistant] SELECT T1.policy_number, SUM(T2.amount_paid) FROM insurance.policies AS T1 JOIN insurance.premium_payments AS T2 ON T1.policy_id = T2.policy_id GROUP BY T1.policy_number;


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.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.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] I want to know the usernames of users who have followed more than three different people, along with the date they created their accounts.

[Assistant]
SELECT u.username, u.created_at, COUNT(DISTINCT f.following_user_id) AS following_count
FROM social_media.users u
JOIN social_media.follows f ON u.user_id = f.follower_user_id
GROUP BY u.user_id, u.username, u.created_at
HAVING COUNT(DISTINCT f.following_user_id) > 3;

[User] Also include the usernames of up to two users they are following for each user in the result.

[Assistant]
SELECT u.username AS follower_username, u.created_at, uf.username AS following_username
FROM social_media.users u
JOIN social_media.follows f ON u.user_id = f.follower_user_id
JOIN social_media.users uf ON f.following_user_id = uf.user_id
WHERE u.user_id IN (
  SELECT f1.follower_user_id
  FROM social_media.follows f1
  GROUP BY f1.follower_user_id
  HAVING COUNT(DISTINCT f1.following_user_id) > 3
)
ORDER BY u.username, f.created_at
LIMIT 2;

[User] Can you instead provide all usernames they follow, not just two, and include the follow creation date as well?

[Assistant]
SELECT u.username AS follower_username, u.created_at AS follower_created_at, uf.username AS following_username, f.created_at AS follow_created_at
FROM social_media.users u
JOIN social_media.follows f ON u.user_id = f.follower_user_id
JOIN social_media.users uf ON f.following_user_id = uf.user_id
WHERE u.user_id IN (
  SELECT f1.follower_user_id
  FROM social_media.follows f1
  GROUP BY f1.follower_user_id
  HAVING COUNT(DISTINCT f1.following_user_id) > 3
)
ORDER BY u.username, f.created_at;


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.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )

[User] List all claim documents along with the beneficiary first and last names and their relationship for policies where a document of type 'MEDICAL_REPORT' exists.

[Assistant]
SELECT cd.document_id, cd.claim_id, cd.file_name, cd.document_type, pb.first_name, pb.last_name, pb.relationship
FROM insurance.claim_documents cd
INNER JOIN insurance.policy_beneficiaries pb ON cd.claim_id = pb.policy_id
WHERE cd.document_type = 'MEDICAL_REPORT';

[User] Actually, please include only beneficiaries whose percentage_share is 30% or more.

[Assistant]
SELECT cd.document_id, cd.claim_id, cd.file_name, cd.document_type, pb.first_name, pb.last_name, pb.relationship, pb.percentage_share
FROM insurance.claim_documents cd
INNER JOIN insurance.policy_beneficiaries pb ON cd.claim_id = pb.policy_id
WHERE cd.document_type = 'MEDICAL_REPORT'
  AND pb.percentage_share >= 30;

[User] Also, add the uploaded_at timestamp from the document to the results and order by uploaded_at descending.

[Assistant]
SELECT cd.document_id, cd.claim_id, cd.file_name, cd.document_type, cd.uploaded_at, pb.first_name, pb.last_name, pb.relationship, pb.percentage_share
FROM insurance.claim_documents cd
INNER JOIN insurance.policy_beneficiaries pb ON cd.claim_id = pb.policy_id
WHERE cd.document_type = 'MEDICAL_REPORT'
  AND pb.percentage_share >= 30
ORDER BY cd.uploaded_at 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 legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )

[User] List the case number, case name, and the full name of the client for cases that have uploaded documents.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_id )

[User] Also include the full name of the lead lawyer for these cases.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name AS client_name ,  T4.full_name AS lawyer_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id JOIN legal_services.lawyers AS T4 ON T1.lead_lawyer_id  =  T4.lawyer_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_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, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )

[User] For each player, show their player_id and the number of unique games they have played sessions on.

[Assistant]
SELECT player_id, COUNT(DISTINCT game_id) AS unique_games
FROM gaming_technology.game_sessions
GROUP BY player_id;

[User] Also show the total number of sessions they have played.

[Assistant]
SELECT player_id, COUNT(DISTINCT game_id) AS unique_games, COUNT(*) AS total_sessions
FROM gaming_technology.game_sessions
GROUP BY player_id;

[User] Only include players who have played on more than 2 unique games.

[Assistant]
SELECT player_id, COUNT(DISTINCT game_id) AS unique_games, COUNT(*) AS total_sessions
FROM gaming_technology.game_sessions
GROUP BY player_id
HAVING COUNT(DISTINCT game_id) > 2;

[User] For each result, include the player's username as well.

[Assistant]
SELECT p.player_id, p.username, COUNT(DISTINCT gs.game_id) AS unique_games, COUNT(*) AS total_sessions
FROM gaming_technology.players p
JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
GROUP BY p.player_id, p.username
HAVING COUNT(DISTINCT gs.game_id) > 2;


[User] List the latest version of each document (identified by case_id and document_name), showing the version number and its upload_timestamp.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version   AS latest_version,
       d.upload_timestamp
FROM legal_services.documents d
JOIN (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m ON d.case_id = m.case_id
    AND d.document_name = m.document_name
    AND d.version = m.max_version;

[User] Actually, I also want to see the upload_timestamp of the previous version for each document.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version         AS latest_version,
       d_latest.upload_timestamp  AS latest_timestamp,
       d_prev.upload_timestamp    AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;

[User] Also, only include documents whose first version (version = 1) was uploaded in 2024.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version          AS latest_version,
       d_latest.upload_timestamp   AS latest_timestamp,
       d_prev.upload_timestamp     AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_first
  ON d_first.case_id = m.case_id
 AND d_first.document_name = m.document_name
 AND d_first.version = 1
 AND d_first.upload_timestamp >= '2024-01-01'
 AND d_first.upload_timestamp < '2025-01-01'
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;


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.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )

[User] Display all invoices along with the associated case name and the full name of the client.

[Assistant]
SELECT i.invoice_number, cs.case_name, c.first_name || ' ' || c.last_name AS client_full_name
FROM legal_services.invoices i
LEFT JOIN legal_services.cases cs ON i.case_id = cs.case_id
LEFT JOIN legal_services.clients c ON i.client_id = c.client_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 hospitality_technology.reservations ( reservation_id text, 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 integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )

[User] Find reservations where the same guest has overlapping stays in the same property.

[Assistant]
SELECT r1.reservation_id AS res1,
       r2.reservation_id AS res2,
       r1.guest_id,
       r1.property_id
FROM hospitality_technology.reservations r1
JOIN hospitality_technology.reservations r2
  ON r1.guest_id = r2.guest_id
 AND r1.property_id = r2.property_id
 AND r1.reservation_id < r2.reservation_id
 AND r1.check_in_date < r2.check_out_date
 AND r2.check_in_date < r1.check_out_date;

[User] Only include overlaps where the overlapping period is more than 2 days.

[Assistant]
SELECT r1.reservation_id AS res1,
       r2.reservation_id AS res2,
       r1.guest_id,
       r1.property_id
FROM hospitality_technology.reservations r1
JOIN hospitality_technology.reservations r2
  ON r1.guest_id = r2.guest_id
 AND r1.property_id = r2.property_id
 AND r1.reservation_id < r2.reservation_id
 AND r1.check_in_date < r2.check_out_date
 AND r2.check_in_date < r1.check_out_date
WHERE (LEAST(r1.check_out_date, r2.check_out_date) - GREATEST(r1.check_in_date, r2.check_in_date)) > 2;

[User] Also return the exact overlap duration in days as overlap_days.

[Assistant]
SELECT r1.reservation_id AS res1,
       r2.reservation_id AS res2,
       r1.guest_id,
       r1.property_id,
       (LEAST(r1.check_out_date, r2.check_out_date) - GREATEST(r1.check_in_date, r2.check_in_date)) AS overlap_days
FROM hospitality_technology.reservations r1
JOIN hospitality_technology.reservations r2
  ON r1.guest_id = r2.guest_id
 AND r1.property_id = r2.property_id
 AND r1.reservation_id < r2.reservation_id
 AND r1.check_in_date < r2.check_out_date
 AND r2.check_in_date < r1.check_out_date
WHERE (LEAST(r1.check_out_date, r2.check_out_date) - GREATEST(r1.check_in_date, r2.check_in_date)) > 2;


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.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.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] Show me all items and the total quantity held by players for each item.

[Assistant]
SELECT pi.item_id, SUM(pi.quantity) AS total_quantity
FROM gaming_technology.player_inventory pi
GROUP BY pi.item_id;

[User] Can you filter for items where players hold at least 10 in total?

[Assistant]
SELECT pi.item_id, SUM(pi.quantity) AS total_quantity
FROM gaming_technology.player_inventory pi
GROUP BY pi.item_id
HAVING SUM(pi.quantity) >= 10;

[User] I would also like to see the most recent acquired_at time for each item.

[Assistant]
SELECT pi.item_id, SUM(pi.quantity) AS total_quantity, MAX(pi.acquired_at) AS most_recent_acquired
FROM gaming_technology.player_inventory pi
GROUP BY pi.item_id
HAVING SUM(pi.quantity) >= 10;

[User] I see duplicates in item_id columns, can you join with the in_game_items table and also show the item name instead?

[Assistant]
SELECT ii.item_name, pi.item_id, SUM(pi.quantity) AS total_quantity, MAX(pi.acquired_at) AS most_recent_acquired
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items ii ON pi.item_id = ii.item_id
GROUP BY ii.item_name, pi.item_id
HAVING SUM(pi.quantity) >= 10;


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.reviews (
    review_id character varying(64) NOT NULL,  -- unique identifier for the review
    property_id character varying(64) NOT NULL, -- FK to properties table
    reservation_id character varying(64) UNIQUE, -- FK to reservations (link review to a specific stay, optional but good)
    guest_id character varying(64) NOT NULL, -- FK to guests table
    rating_overall integer, -- overall score (e.g., 1-5 or 1-10)
    rating_cleanliness integer,
    rating_service integer,
    rating_location integer,
    rating_value integer,
    comment text, -- guest's written feedback
    review_source character varying(100), -- e.g., DirectSurvey, TripAdvisor, Google, Booking.com
    review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the review was submitted
    is_public boolean DEFAULT true, -- whether the review is publicly visible
    staff_response text, -- official response from the property
    response_staff_id character varying(64), -- FK to staff (who responded)
    response_date timestamp with time zone, -- when the response was posted
    PRIMARY KEY (review_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id)
)

[User] For each review, show me the comment, the review date, and the full name of the staff member who responded to the review, if there is a response.

[Assistant]
SELECT r.review_id, r.comment, r.review_date, s.first_name || ' ' || s.last_name AS staff_full_name
FROM hospitality_technology.reviews r
LEFT JOIN hospitality_technology.staff s ON r.response_staff_id = s.staff_id;

[User] Only show reviews that have a staff response and also include the response date.

[Assistant]
SELECT r.review_id, r.comment, r.review_date, s.first_name || ' ' || s.last_name AS staff_full_name, r.response_date
FROM hospitality_technology.reviews r
JOIN hospitality_technology.staff s ON r.response_staff_id = s.staff_id
WHERE r.staff_response IS NOT NULL;


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 text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.insurance_products ( product_id text, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )

[User] List policy_number, customer_id, and product_name for policies that are currently active.

[Assistant]
SELECT p.policy_number, p.customer_id, ip.product_name
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'Active' AND ip.is_active = true;

[User] Actually, only show those policies that will expire within the next 30 days.

[Assistant]
SELECT p.policy_number, p.customer_id, ip.product_name
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'Active'
  AND ip.is_active = true
  AND p.end_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days';

[User] Also, include the product_type and only for products of type 'Life'.

[Assistant]
SELECT p.policy_number, p.customer_id, ip.product_name, ip.product_type
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'Active'
  AND ip.is_active = true
  AND p.end_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days'
  AND ip.product_type = 'Life';

[User] Sort the final results by end_date ascending, please.

[Assistant]
SELECT p.policy_number, p.customer_id, ip.product_name, ip.product_type, p.end_date
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'Active'
  AND ip.is_active = true
  AND p.end_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days'
  AND ip.product_type = 'Life'
ORDER BY p.end_date 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 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, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )

[User] Which games have at least one achievement worth exactly 75 points, and what are the names and descriptions of those achievements?

[Assistant]
SELECT g.title, a.name AS achievement_name, a.description
FROM gaming_technology.games g
JOIN gaming_technology.achievements a ON g.game_id = a.game_id
WHERE a.points = 75;

[User] Also include the release date of each game in the output.

[Assistant]
SELECT g.title, g.release_date, a.name AS achievement_name, a.description
FROM gaming_technology.games g
JOIN gaming_technology.achievements a ON g.game_id = a.game_id
WHERE a.points = 75;

[User] Now, only show results for games released after 2021-01-01.

[Assistant]
SELECT g.title, g.release_date, a.name AS achievement_name, a.description
FROM gaming_technology.games g
JOIN gaming_technology.achievements a ON g.game_id = a.game_id
WHERE a.points = 75 AND g.release_date > '2021-01-01';

[User] Order the list by game release date ascending, then achievement name ascending.

[Assistant]
SELECT g.title, g.release_date, a.name AS achievement_name, a.description
FROM gaming_technology.games g
JOIN gaming_technology.achievements a ON g.game_id = a.game_id
WHERE a.points = 75 AND g.release_date > '2021-01-01'
ORDER BY g.release_date ASC, a.name 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 healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )

[User] List all pairs of patients who have the same emergency contact name and phone number. Show the IDs and full names of both patients and the shared emergency contact details (name and phone).

[Assistant] SELECT p1.patient_id AS patient1_id, p1.first_name AS patient1_first_name, p1.last_name AS patient1_last_name, p2.patient_id AS patient2_id, p2.first_name AS patient2_first_name, p2.last_name AS patient2_last_name, p1.emergency_contact_name, p1.emergency_contact_phone FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.emergency_contact_name = p2.emergency_contact_name AND p1.emergency_contact_phone = p2.emergency_contact_phone WHERE p1.patient_id < p2.patient_id;

[User] Only include pairs where the shared emergency contact name is not null.

[Assistant] SELECT p1.patient_id AS patient1_id, p1.first_name AS patient1_first_name, p1.last_name AS patient1_last_name, p2.patient_id AS patient2_id, p2.first_name AS patient2_first_name, p2.last_name AS patient2_last_name, p1.emergency_contact_name, p1.emergency_contact_phone FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.emergency_contact_name = p2.emergency_contact_name AND p1.emergency_contact_phone = p2.emergency_contact_phone WHERE p1.patient_id < p2.patient_id AND p1.emergency_contact_name IS NOT NULL;


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.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )
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 )
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )

[User] List each client's first and last name along with the number of cases they have, alias the count as case_count.

[Assistant]
SELECT cl.first_name, cl.last_name, COUNT(c.case_id) AS case_count
FROM legal_services.clients cl
LEFT JOIN legal_services.cases c ON cl.client_id = c.client_id
GROUP BY cl.client_id, cl.first_name, cl.last_name;

[User] Actually, only include clients who have more than 2 cases.

[Assistant]
SELECT cl.first_name, cl.last_name, COUNT(c.case_id) AS case_count
FROM legal_services.clients cl
LEFT JOIN legal_services.cases c ON cl.client_id = c.client_id
GROUP BY cl.client_id, cl.first_name, cl.last_name
HAVING COUNT(c.case_id) > 2;

[User] Also sort the results by case_count descending and then by the client's last_name ascending.

[Assistant]
SELECT cl.first_name, cl.last_name, COUNT(c.case_id) AS case_count
FROM legal_services.clients cl
LEFT JOIN legal_services.cases c ON cl.client_id = c.client_id
GROUP BY cl.client_id, cl.first_name, cl.last_name
HAVING COUNT(c.case_id) > 2
ORDER BY case_count DESC, cl.last_name 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.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )

[User] List each document_name along with the count of its versions, but only include those document_names that have more than 3 versions.

[Assistant]
SELECT document_name,
       COUNT(version) AS version_count
FROM legal_services.documents
GROUP BY document_name
HAVING COUNT(version) > 3;