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
)

[User] List pairs of games that share the same publisher but belong to different genres, showing both titles and genres.

[Assistant]
SELECT g1.game_id AS game1_id,
       g1.title AS title1,
       g1.genre AS genre1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.genre AS genre2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND g1.genre <> g2.genre;

[User] Exclude any pairs where the publisher_id is NULL.

[Assistant]
SELECT g1.game_id AS game1_id,
       g1.title AS title1,
       g1.genre AS genre1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.genre AS genre2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND g1.genre <> g2.genre
WHERE g1.publisher_id IS NOT NULL;

[User] Further restrict to game pairs released within one year of each other.

[Assistant]
SELECT g1.game_id AS game1_id,
       g1.title AS title1,
       g1.release_date AS release1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.release_date AS release2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND ABS(EXTRACT(YEAR FROM AGE(g1.release_date, g2.release_date))) <= 1
WHERE g1.publisher_id IS NOT NULL;

[User] Order the final result by publisher_id and then by the earliest release_date among each pair.

[Assistant]
SELECT g1.publisher_id,
       g1.game_id AS game1_id,
       g1.title AS title1,
       g1.release_date AS release1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.release_date AS release2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND ABS(EXTRACT(YEAR FROM AGE(g1.release_date, g2.release_date))) <= 1
WHERE g1.publisher_id IS NOT NULL
ORDER BY g1.publisher_id,
         LEAST(g1.release_date, g2.release_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 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] List all patients who have insurance plans with group numbers, showing their patient IDs and the count of such plans per patient.

[Assistant] SELECT patient_id, COUNT(*) AS plan_count FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id;

[User] Actually, I only need patients who have more than 2 such plans.

[Assistant] SELECT patient_id, COUNT(*) AS plan_count FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id HAVING COUNT(*) > 2;

[User] Can you also include the earliest effective date among these plans for each patient?

[Assistant] SELECT patient_id, COUNT(*) AS plan_count, MIN(effective_date) AS earliest_effective_date FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id HAVING COUNT(*) > 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 social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), 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.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
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, -- 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 text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
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 text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )

[User] Find posts that have been liked by users the author of the post is following. List the post_id and the user_id of the post author.

[Assistant] SELECT p.post_id, p.user_id AS post_author_user_id FROM social_media.posts AS p JOIN social_media.likes AS l ON p.post_id = l.post_id JOIN social_media.follows AS f ON f.follower_user_id = p.user_id AND f.following_user_id = l.user_id;

[User] Can you refine this to only include posts where the author started following the user *before* the post was created?

[Assistant] SELECT p.post_id, p.user_id AS post_author_user_id FROM social_media.posts AS p JOIN social_media.likes AS l ON p.post_id = l.post_id JOIN social_media.follows AS f ON f.follower_user_id = p.user_id AND f.following_user_id = l.user_id WHERE f.created_at < p.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 financial_services.accounts ( account_id.text, customer_id.text, account_number.text, account_type.text, balance.numeric, currency.text, opened_date.date, status.text, interest_rate.numeric, last_updated_at.timestamp )

[User] Summarize the total balance and average interest rate for each account type.

[Assistant] SELECT account_type, SUM(balance) AS total_balance, AVG(interest_rate) AS average_interest_rate FROM financial_services.accounts GROUP BY account_type

[User] Only include account types where the total balance is greater than 1000000.

[Assistant] SELECT account_type, SUM(balance) AS total_balance, AVG(interest_rate) AS average_interest_rate FROM financial_services.accounts GROUP BY account_type HAVING SUM(balance) > 1000000

[User] Also, include the total count of accounts for each type in the result.

[Assistant] SELECT account_type, COUNT(*) AS total_accounts, SUM(balance) AS total_balance, AVG(interest_rate) AS average_interest_rate FROM financial_services.accounts GROUP BY account_type HAVING SUM(balance) > 1000000

[User] Finally, sort the results by the total balance in descending order.

[Assistant] SELECT account_type, COUNT(*) AS total_accounts, SUM(balance) AS total_balance, AVG(interest_rate) AS average_interest_rate FROM financial_services.accounts GROUP BY account_type HAVING SUM(balance) > 1000000 ORDER BY total_balance 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 web3.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )

[User] How many users registered in each month?

[Assistant]
SELECT date_trunc('month', created_at) AS month,
       COUNT(*) AS registrations
FROM web3.users
GROUP BY month
ORDER BY month;

[User] Actually, show only those months where registrations exceed 10.

[Assistant]
SELECT date_trunc('month', created_at) AS month,
       COUNT(*) AS registrations
FROM web3.users
GROUP BY month
HAVING COUNT(*) > 10
ORDER BY month;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text PRIMARY KEY, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.transactions ( transaction_id text PRIMARY KEY, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
CREATE TABLE financial_services.trades ( trade_id text PRIMARY KEY, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id bigserial PRIMARY KEY, security_id text, data_timestamp timestamp, open_price numeric, high_price numeric, low_price numeric, close_price numeric, adjusted_close_price numeric, volume bigint, source text )
CREATE TABLE financial_services.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )

[User] Can you provide a list of all trades in the past 90 days, including the security_id, account_id, trade_type, quantity, total_amount, and the current balance of the involved account?

[Assistant]
SELECT t.trade_id, t.security_id, t.account_id, t.trade_type, t.quantity, t.total_amount, a.balance
FROM financial_services.trades t
JOIN financial_services.accounts a ON t.account_id = a.account_id
WHERE t.trade_timestamp >= NOW() - INTERVAL '90 days';

[User] Please also include the execution venue for each trade in the result.

[Assistant]
SELECT t.trade_id, t.security_id, t.account_id, t.trade_type, t.quantity, t.total_amount, t.execution_venue, a.balance
FROM financial_services.trades t
JOIN financial_services.accounts a ON t.account_id = a.account_id
WHERE t.trade_timestamp >= NOW() - INTERVAL '90 days';

[User] Now, only show trades where the total_amount is above 10000.

[Assistant]
SELECT t.trade_id, t.security_id, t.account_id, t.trade_type, t.quantity, t.total_amount, t.execution_venue, a.balance
FROM financial_services.trades t
JOIN financial_services.accounts a ON t.account_id = a.account_id
WHERE t.trade_timestamp >= NOW() - INTERVAL '90 days'
  AND t.total_amount > 10000;

[User] Finally, order the output by trade_timestamp descending.

[Assistant]
SELECT t.trade_id, t.security_id, t.account_id, t.trade_type, t.quantity, t.total_amount, t.execution_venue, a.balance
FROM financial_services.trades t
JOIN financial_services.accounts a ON t.account_id = a.account_id
WHERE t.trade_timestamp >= NOW() - INTERVAL '90 days'
  AND t.total_amount > 10000
ORDER BY t.trade_timestamp 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 government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)

[User] List the first name, last name, and job title of each employee, along with the job title of their manager.

[Assistant] SELECT e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.job_title AS employee_job_title, m.job_title AS manager_job_title FROM government_services.employees AS e LEFT JOIN government_services.employees AS m ON e.manager_employee_id = m.employee_id;


System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. 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 train_station_management.trains ( train_id.text, train_number.text, model.text, manufacturer.text, year_manufactured.integer, capacity.integer, status.text, last_maintenance_date.date, next_maintenance_date.date )

[User] What is the average speed of train number T9876 during its last journey?

[Assistant] I'm sorry, but I can't provide information on the average speed of train number T9876 during its last journey. The data in the trains table does not include details about travel speed or journey-specific performance metrics.


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.trips ( trip_id text, 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 integer, cargo_manifest_id text )

[User] List all trips with their trip_id, vehicle_id, and the corresponding origin_location_id and destination_location_id, but only where the origin and destination are not the same.

[Assistant] SELECT trip_id, vehicle_id, origin_location_id, destination_location_id FROM transportation.trips WHERE origin_location_id <> destination_location_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 government_services.applications ( application_id text PRIMARY KEY, 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 )

[User] List the application ID, submitted date, and assigned employee ID for all applications that are currently in 'Processing' status and were submitted before January 1st, 2024.

[Assistant] SELECT application_id, submitted_at, assigned_employee_id FROM government_services.applications WHERE status = 'Processing' AND submitted_at < '2024-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 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)
)

[User] Show the content of comments and the content of the posts they belong to, for comments made by users whose location is 'New York'. Also include the username of the commenter.

[Assistant] SELECT c.content AS comment_content, p.content AS post_content, u.username FROM comments c JOIN posts p ON c.post_id = p.post_id JOIN social_media.users u ON c.user_id = u.user_id WHERE u.location = 'New York';

[User] Additionally, only include comments made by users who are verified.

[Assistant] SELECT c.content AS comment_content, p.content AS post_content, u.username FROM comments c JOIN posts p ON c.post_id = p.post_id JOIN social_media.users u ON c.user_id = u.user_id WHERE u.location = 'New York' AND u.is_verified = true;


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.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )

[User] For each route, show its route number, distance in kilometers, and the total number of trips that have used that route.

[Assistant]
SELECT r.route_number, r.distance_km, COUNT(t.trip_id) AS trip_count
FROM transportation.routes r
LEFT JOIN transportation.trips t ON r.route_id = t.route_id
GROUP BY r.route_number, r.distance_km;


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.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.accounts ( account_id.text, customer_id.text, account_number.text, account_type.text, balance.numeric, currency.text, opened_date.date, status.text, interest_rate.numeric, last_updated_at.timestamp )
CREATE TABLE financial_services.transactions ( transaction_id text, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
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 )
CREATE TABLE financial_services.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )

[User] Show me the total number of customers and their average age grouped by city.

[Assistant] SELECT city, COUNT(customer_id) AS total_customers, AVG(EXTRACT(YEAR FROM NOW()) - EXTRACT(YEAR FROM date_of_birth)) AS average_age FROM financial_services.customers WHERE city IS NOT NULL GROUP BY city

[User] Only include customers with status 'Active'.

[Assistant] SELECT city, COUNT(customer_id) AS total_customers, AVG(EXTRACT(YEAR FROM NOW()) - EXTRACT(YEAR FROM date_of_birth)) AS average_age FROM financial_services.customers WHERE city IS NOT NULL AND status = 'Active' GROUP BY city


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 PRIMARY KEY, 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 )

[User] Find all pairs of citizens who share the same last name but have different dates of birth. Display both full names, the shared last name, and each date of birth.

[Assistant]
SELECT
  c1.first_name || ' ' || c1.last_name AS citizen1_name,
  c2.first_name || ' ' || c2.last_name AS citizen2_name,
  c1.last_name AS shared_last_name,
  c1.date_of_birth AS dob1,
  c2.date_of_birth AS dob2
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.last_name = c2.last_name
     AND c1.citizen_id < c2.citizen_id
     AND c1.date_of_birth <> c2.date_of_birth;


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.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)

[User] List the first name, last name, email, and the name of the law firm for all lawyers.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T1.email ,  T2.firm_name FROM legal_services.lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id  =  T2.firm_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 insurance.customers ( customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, ssn_hash character varying(128), address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state character varying(50) NOT NULL, zip_code character varying(20) NOT NULL, country character varying(50) NOT NULL DEFAULT 'USA', phone_number character varying(30), email character varying(128) UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, status character varying(20) NOT NULL DEFAULT 'Active', PRIMARY KEY (customer_id) )
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )
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] Show me all customers who have purchased policies for insurance products of type 'health', including their full name, policy number, and the insurance product's name.

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name, p.policy_number, ip.product_name
FROM insurance.customers c
JOIN insurance.policies p ON p.customer_id = c.customer_id
JOIN insurance.insurance_products ip ON ip.product_id = p.product_id
WHERE ip.product_type = 'health';

[User] Add the premium amount of the policy and the product's base premium to the result.

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name, p.policy_number, ip.product_name, p.premium_amount, ip.base_premium
FROM insurance.customers c
JOIN insurance.policies p ON p.customer_id = c.customer_id
JOIN insurance.insurance_products ip ON ip.product_id = p.product_id
WHERE ip.product_type = 'health';

[User] Actually, only include policies that are currently active and have a premium amount greater than the base premium of the product.

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name, p.policy_number, ip.product_name, p.premium_amount, ip.base_premium
FROM insurance.customers c
JOIN insurance.policies p ON p.customer_id = c.customer_id
JOIN insurance.insurance_products ip ON ip.product_id = p.product_id
WHERE ip.product_type = 'health'
  AND p.status = 'active'
  AND p.premium_amount > ip.base_premium;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )

[User] Show me all rooms on floor 4 or above together with their room number, features, and current status.

[Assistant]
SELECT room_id, room_number, features, status
FROM hospitality_technology.rooms
WHERE floor >= 4;

[User] Only include rooms that are marked as non-smoking and sort the results by floor descending.

[Assistant]
SELECT room_id, room_number, features, status, floor
FROM hospitality_technology.rooms
WHERE floor >= 4 AND is_smoking = FALSE
ORDER BY floor 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
Use Hashes. Key pattern: 'inv:<inventory_record_id>'. Example: HSET inv:INVREC500 component_id "component:WINGBOLT" quantity 5000 location_warehouse "WH3" batch_number "BCH778899" ... Consider Sorted Set by expiry date: ZADD component_expiry:<component_id> <expiry_timestamp> <inventory_record_id>.

[User] Can you help me retrieve the inventory details for a specific component ID, including the quantity and warehouse location?

[Assistant] HGETALL inv:<inventory_record_id>

[User] Can you also include the batch number for that inventory record?

[Assistant] HGETALL inv:<inventory_record_id>

[User] If I want to check the expiry date for this component, how can I retrieve that information?

[Assistant] ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] Can you filter the results to show only inventory records with an expiry date after a specific timestamp?

[Assistant] ZRANGEBYSCORE component_expiry:<component_id> <specific_timestamp> +inf WITHSCORES


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id.text, username.text, email.text, password_hash.text, full_name.text, profile_picture_url.text, bio.text, location.text, created_at.timestamp, updated_at.timestamp, is_verified.boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
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.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
CREATE TABLE social_media.messages ( message_id.text, conversation_id.text, sender_user_id.text, content.text, media_url.text, media_type.text, sent_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )

[User] Get the five most recent public posts that have media_type = 'video', showing post_id, created_at, and the author's username.

[Assistant]
SELECT
  p.post_id,
  p.created_at,
  u.username
FROM social_media.posts p
JOIN social_media.users u
  ON p.user_id = u.user_id
WHERE p.visibility = 'public'
  AND p.media_type = 'video'
ORDER BY p.created_at DESC
LIMIT 5;

[User] Actually, filter to only include posts made by verified users.

[Assistant]
SELECT
  p.post_id,
  p.created_at,
  u.username
FROM social_media.posts p
JOIN social_media.users u
  ON p.user_id = u.user_id
WHERE p.visibility = 'public'
  AND p.media_type = 'video'
  AND u.is_verified = TRUE
ORDER BY p.created_at DESC
LIMIT 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 hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] Find all review comments that have a staff response, showing the comment and the staff response date.

[Assistant] SELECT comment, response_date FROM reviews WHERE response_date IS NOT NULL;

[User] Now, also include the name of the staff member who responded.

[Assistant] SELECT T1.comment, T1.response_date, T2.first_name, T2.last_name FROM reviews AS T1 JOIN staff AS T2 ON T1.response_staff_id = T2.staff_id WHERE T1.response_date IS NOT NULL;

[User] Further filter this list to only show responses made more than 24 hours after the review was submitted, and include the review date and the reservation ID.

[Assistant] SELECT T1.comment, T1.response_date, T2.first_name, T2.last_name, T1.review_date, T1.reservation_id FROM reviews AS T1 JOIN staff AS T2 ON T1.response_staff_id = T2.staff_id WHERE T1.response_date IS NOT NULL AND T1.response_date > T1.review_date + INTERVAL '24 hours';


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.transactions ( transaction_id.text, account_id.text, related_account_id.text, transaction_type.text, amount.numeric, currency.text, transaction_date.timestamp, effective_date.date, description.text, status.text, reference_number.text )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )

[User] Show me the number of market data points and average adjusted close price per source.

[Assistant]
SELECT source, COUNT(*) AS data_point_count, AVG(adjusted_close_price) AS avg_adjusted_close_price
FROM financial_services.market_data
GROUP BY source
ORDER BY source ASC;

[User] Filter the result to only include sources where the average adjusted close price is above 50.

[Assistant]
SELECT source, COUNT(*) AS data_point_count, AVG(adjusted_close_price) AS avg_adjusted_close_price
FROM financial_services.market_data
GROUP BY source
HAVING AVG(adjusted_close_price) > 50
ORDER BY source ASC;

[User] Also, only consider market data from the past 90 days.

[Assistant]
SELECT source, COUNT(*) AS data_point_count, AVG(adjusted_close_price) AS avg_adjusted_close_price
FROM financial_services.market_data
WHERE data_timestamp >= CURRENT_DATE - INTERVAL '90 days'
GROUP BY source
HAVING AVG(adjusted_close_price) > 50
ORDER BY source 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 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] List reservations, including the reservation ID, check-in date, check-out date, property name, room type name, and room type base rate, for reservations with 3 or more adults.

[Assistant] SELECT T1.reservation_id, T1.check_in_date, T1.check_out_date, T2.property_name, T3.type_name, T3.base_rate FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.num_adults >= 3;

[User] Now, only include reservations made at properties with a star rating of 4 or higher and sort the results by check-in date.

[Assistant] SELECT T1.reservation_id, T1.check_in_date, T1.check_out_date, T2.property_name, T3.type_name, T3.base_rate FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.num_adults >= 3 AND T2.star_rating >= 4 ORDER BY T1.check_in_date;

[User] Further refine this list to include only reservations where the total amount is over 700, and limit the results to the top 15.

[Assistant] SELECT T1.reservation_id, T1.check_in_date, T1.check_out_date, T2.property_name, T3.type_name, T3.base_rate FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.num_adults >= 3 AND T2.star_rating >= 4 AND T1.total_amount > 700 ORDER BY T1.check_in_date LIMIT 15;


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 PRIMARY KEY, 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.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, 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.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)

[User] List the names of services available at service locations that are accessible and located in the state of 'California'.

[Assistant] SELECT T1.service_name, T2.location_name FROM government_services.services AS T1 JOIN government_services.service_locations AS T2 ON T1.agency_id = T2.agency_id WHERE T2.is_accessible = TRUE AND T2.state = 'California';

[User] Modify to only include services that are active.

[Assistant] SELECT T1.service_name, T2.location_name FROM government_services.services AS T1 JOIN government_services.service_locations AS T2 ON T1.agency_id = T2.agency_id WHERE T2.is_accessible = TRUE AND T2.state = 'California' AND T1.is_active = TRUE;


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 character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.doctors ( doctor_id text, 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 PRIMARY KEY, 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 text, created_at timestamp )
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 text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] List the license number and specialty for all doctors who have a phone number on record.

[Assistant] SELECT license_number, specialty FROM healthcare.doctors WHERE phone_number 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 government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )

[User] List all pairs of active services in the same category where one service’s standard fee is higher than the other’s. Display the category, the higher-fee service name with its fee, and the lower-fee service name with its fee.

[Assistant]
SELECT
  s1.category,
  s1.service_name AS higher_service,
  s1.standard_fee AS higher_fee,
  s2.service_name AS lower_service,
  s2.standard_fee AS lower_fee
FROM government_services.services s1
JOIN government_services.services s2
  ON s1.category = s2.category
  AND s1.standard_fee > s2.standard_fee
WHERE s1.is_active = TRUE
  AND s2.is_active = TRUE;


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 timestamp with time zone, last_login timestamp with time zone, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )

[User] Retrieve the top 5 players by the number of distinct achievements unlocked. Show player_id and distinct_unlocks.

[Assistant]
SELECT p.player_id, COUNT(DISTINCT pa.achievement_id) AS distinct_unlocks
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
GROUP BY p.player_id
ORDER BY distinct_unlocks DESC
LIMIT 5;

[User] Now limit the results to players whose status is 'active'.

[Assistant]
SELECT p.player_id, COUNT(DISTINCT pa.achievement_id) AS distinct_unlocks
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
WHERE p.status = 'active'
GROUP BY p.player_id
ORDER BY distinct_unlocks DESC
LIMIT 5;

[User] Sort the list by distinct_unlocks descending and then by player_id ascending.

[Assistant]
SELECT p.player_id, COUNT(DISTINCT pa.achievement_id) AS distinct_unlocks
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
WHERE p.status = 'active'
GROUP BY p.player_id
ORDER BY distinct_unlocks DESC, p.player_id ASC
LIMIT 5;

[User] Finally, limit the output to the top 3 entries.

[Assistant]
SELECT p.player_id, COUNT(DISTINCT pa.achievement_id) AS distinct_unlocks
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
WHERE p.status = 'active'
GROUP BY p.player_id
ORDER BY distinct_unlocks DESC, p.player_id ASC
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 trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )

[User] Show the number of users registered each month for 2024.

[Assistant]
SELECT
  date_trunc('month', created_at) AS month,
  COUNT(*) AS user_count
FROM trading_platform.users
WHERE created_at >= '2024-01-01'
  AND created_at < '2025-01-01'
GROUP BY month
ORDER BY month;


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 )
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )

[User] Show all policy numbers with their corresponding payment_id and amount_paid for payments made on or after January 1st, 2024.

[Assistant]
SELECT p.policy_number, pp.payment_id, pp.amount_paid
FROM insurance.premium_payments pp
JOIN insurance.policies p ON pp.policy_id = p.policy_id
WHERE pp.payment_date >= '2024-01-01';

[User] Include the payment_method and the due_date in the output as well.

[Assistant]
SELECT p.policy_number, pp.payment_id, pp.amount_paid, pp.payment_method, pp.due_date
FROM insurance.premium_payments pp
JOIN insurance.policies p ON pp.policy_id = p.policy_id
WHERE pp.payment_date >= '2024-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 social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )

[User] Show me the content of all comments that have received at least one like.

[Assistant] SELECT DISTINCT T1.content FROM social_media.comments AS T1 JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id;

[User] Also include the creation time of these comments and the user_id of the commenter?

[Assistant] SELECT DISTINCT T1.comment_id, T1.content, T1.created_at, T1.user_id FROM social_media.comments AS T1 JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id;

[User] Only show comments created before '2024-05-01'.

[Assistant] SELECT DISTINCT T1.comment_id, T1.content, T1.created_at, T1.user_id FROM social_media.comments AS T1 JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id WHERE T1.created_at < '2024-05-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.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.appointments ( appointment_id.text, 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] Show me the subjects and start times of all appointments along with the document names of any documents uploaded for the associated case.

[Assistant]
SELECT a.subject, a.start_time, d.document_name
FROM legal_services.appointments a
JOIN legal_services.documents d ON a.case_id = d.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.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )

[User] Can you show me the total number of sessions and the average score for each server and each game combination?

[Assistant] SELECT server_id, game_id, COUNT(*) AS total_sessions, AVG(score) AS average_score FROM gaming_technology.game_sessions GROUP BY server_id, game_id;

[User] Could you filter this to only include combinations where the average score is above 200?

[Assistant] SELECT server_id, game_id, COUNT(*) AS total_sessions, AVG(score) AS average_score FROM gaming_technology.game_sessions GROUP BY server_id, game_id HAVING AVG(score) > 200;

[User] Can you add the total duration in seconds for each combination as well?

[Assistant] SELECT server_id, game_id, COUNT(*) AS total_sessions, AVG(score) AS average_score, SUM(duration_seconds) AS total_duration FROM gaming_technology.game_sessions GROUP BY server_id, game_id HAVING AVG(score) > 200;

[User] Now, only show combinations where the total duration exceeds 10,000 seconds.

[Assistant] SELECT server_id, game_id, COUNT(*) AS total_sessions, AVG(score) AS average_score, SUM(duration_seconds) AS total_duration FROM gaming_technology.game_sessions GROUP BY server_id, game_id HAVING AVG(score) > 200 AND SUM(duration_seconds) > 10000;


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 cex_token_balance ( snapshot_time character varying(32) NOT NULL, chain character varying(128) NOT NULL, address character varying(128) NOT NULL, exchange character varying(512) NOT NULL, token_address character varying(128) NOT NULL, token_symbol character varying(512), balance numeric(38,10), usd_value numeric(38,14), price double precision )

[User] Show me the top 5 tokens by USD value held on the Binance Smart Chain, along with their average price and total balance.

[Assistant] SELECT token_symbol, AVG(price) as average_price, SUM(balance) as total_balance, SUM(usd_value) as total_usd_value FROM cex_token_balance WHERE chain = 'Binance Smart Chain' GROUP BY token_symbol ORDER BY total_usd_value DESC LIMIT 5;

[User] Actually, I want to see this for the Polygon chain instead, and only include tokens with a total balance over 1000.

[Assistant] SELECT token_symbol, AVG(price) as average_price, SUM(balance) as total_balance, SUM(usd_value) as total_usd_value FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol HAVING SUM(balance) > 1000 ORDER BY total_usd_value DESC LIMIT 5;

[User] Can you add the exchange name to these results and filter to only show Binance holdings?

[Assistant] SELECT exchange, token_symbol, AVG(price) as average_price, SUM(balance) as total_balance, SUM(usd_value) as total_usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND exchange = 'Binance' GROUP BY exchange, token_symbol HAVING SUM(balance) > 1000 ORDER BY total_usd_value DESC LIMIT 5;

[User] Now order these results by total balance instead of USD value.

[Assistant] SELECT exchange, token_symbol, AVG(price) as average_price, SUM(balance) as total_balance, SUM(usd_value) as total_usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND exchange = 'Binance' GROUP BY exchange, token_symbol HAVING SUM(balance) > 1000 ORDER BY total_balance DESC LIMIT 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 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 )

[User] Compute the total invoiced amount and average payment delay (in days) by status for invoices issued between 2024-01-01 and 2024-06-30.

[Assistant]
SELECT status,
       SUM(total_amount) AS total_invoiced,
       AVG(EXTRACT(day FROM (payment_date::date - issue_date))) AS avg_payment_delay_days
  FROM legal_services.invoices
 WHERE issue_date BETWEEN '2024-01-01' AND '2024-06-30'
 GROUP BY status;

[User] Also show the count of invoices per status.

[Assistant]
SELECT status,
       SUM(total_amount) AS total_invoiced,
       AVG(EXTRACT(day FROM (payment_date::date - issue_date))) AS avg_payment_delay_days,
       COUNT(*) AS invoice_count
  FROM legal_services.invoices
 WHERE issue_date BETWEEN '2024-01-01' AND '2024-06-30'
 GROUP BY status;

[User] Exclude statuses where total_invoiced is less than 10000.

[Assistant]
SELECT status,
       SUM(total_amount) AS total_invoiced,
       AVG(EXTRACT(day FROM (payment_date::date - issue_date))) AS avg_payment_delay_days,
       COUNT(*) AS invoice_count
  FROM legal_services.invoices
 WHERE issue_date BETWEEN '2024-01-01' AND '2024-06-30'
 GROUP BY status
HAVING SUM(total_amount) >= 10000;

[User] Finally, order the results by avg_payment_delay_days ascending.

[Assistant]
SELECT status,
       SUM(total_amount) AS total_invoiced,
       AVG(EXTRACT(day FROM (payment_date::date - issue_date))) AS avg_payment_delay_days,
       COUNT(*) AS invoice_count
  FROM legal_services.invoices
 WHERE issue_date BETWEEN '2024-01-01' AND '2024-06-30'
 GROUP BY status
HAVING SUM(total_amount) >= 10000
 ORDER BY avg_payment_delay_days 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
// Use Hashes for ticket details. Key format: ticket:<ticket_id>
// HSET ticket:tkt_1a2b ticket_id "tkt_1a2b" booking_id "book_zyx" car_id "car_abc" seat_number "12A" ... is_checked_in 0 ...

// To link tickets to bookings (optional):
// SADD booking:book_zyx:tickets ticket:tkt_1a2b
// Use Hashes for maintenance record details. Key format: maintenance_record:<record_id>
// HSET maintenance_record:maint_rec_001 record_id "maint_rec_001" asset_id "train_789" asset_type "Train" ... status "Completed"

// To link records to assets (optional):
// SADD train:train_789:maintenance maintenance_record:maint_rec_001
// SADD platform:plat_123:maintenance maintenance_record:maint_rec_002

[User] 特定のプラットフォームID 'plat_123' に関連するメンテナンス記録を取得するのを手伝っていただけますか？また、記録のステータスも含めてください。

[Assistant]
SMEMBERS platform:plat_123:maintenance
HGETALL maintenance_record:<record_id>

[User] ステータスが 'Completed' の記録だけを表示するようにフィルタリングしていただけますか？

[Assistant]
SMEMBERS platform:plat_123:maintenance
HGET maintenance_record:<record_id> status
HGETALL maintenance_record:<record_id> (only if status = 'Completed')

[User] 関連する資産タイプも結果に含めていただけますか？

[Assistant]
SMEMBERS platform:plat_123:maintenance
HGET maintenance_record:<record_id> status
HGETALL maintenance_record:<record_id> (only if status = 'Completed')


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 PRIMARY KEY, 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.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 PRIMARY KEY, 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 text, created_at timestamp )
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.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 text PRIMARY KEY, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed int, prescription_date timestamp )

[User] Show me all patients who have received at least two different medications prescribed by doctors working at the same hospital. Include the patient full name, the medication names, and the shared hospital_affiliation_id.

[Assistant]
SELECT DISTINCT p.patient_id, p.first_name, p.last_name, m1.medication_name AS medication1, m2.medication_name AS medication2, d.hospital_affiliation_id
FROM healthcare.prescriptions pr1
JOIN healthcare.prescriptions pr2 ON pr1.patient_id = pr2.patient_id AND pr1.medication_id <> pr2.medication_id
JOIN healthcare.doctors d ON pr1.doctor_id = d.doctor_id AND pr2.doctor_id = d.doctor_id
JOIN healthcare.patients p ON pr1.patient_id = p.patient_id
JOIN healthcare.medications m1 ON pr1.medication_id = m1.medication_id
JOIN healthcare.medications m2 ON pr2.medication_id = m2.medication_id
WHERE d.hospital_affiliation_id IS NOT NULL;

[User] Can you only include records where both medications share the same generic name?

[Assistant]
SELECT DISTINCT p.patient_id, p.first_name, p.last_name, m1.medication_name AS medication1, m2.medication_name AS medication2, m1.generic_name, d.hospital_affiliation_id
FROM healthcare.prescriptions pr1
JOIN healthcare.prescriptions pr2 ON pr1.patient_id = pr2.patient_id AND pr1.medication_id <> pr2.medication_id
JOIN healthcare.doctors d ON pr1.doctor_id = d.doctor_id AND pr2.doctor_id = d.doctor_id
JOIN healthcare.patients p ON pr1.patient_id = p.patient_id
JOIN healthcare.medications m1 ON pr1.medication_id = m1.medication_id
JOIN healthcare.medications m2 ON pr2.medication_id = m2.medication_id
WHERE d.hospital_affiliation_id IS NOT NULL AND m1.generic_name = m2.generic_name;

[User] Actually, only show those cases where the doctor specialty is 'Internal Medicine'.

[Assistant]
SELECT DISTINCT p.patient_id, p.first_name, p.last_name, m1.medication_name AS medication1, m2.medication_name AS medication2, m1.generic_name, d.hospital_affiliation_id
FROM healthcare.prescriptions pr1
JOIN healthcare.prescriptions pr2 ON pr1.patient_id = pr2.patient_id AND pr1.medication_id <> pr2.medication_id
JOIN healthcare.doctors d ON pr1.doctor_id = d.doctor_id AND pr2.doctor_id = d.doctor_id
JOIN healthcare.patients p ON pr1.patient_id = p.patient_id
JOIN healthcare.medications m1 ON pr1.medication_id = m1.medication_id
JOIN healthcare.medications m2 ON pr2.medication_id = m2.medication_id
WHERE d.hospital_affiliation_id IS NOT NULL AND m1.generic_name = m2.generic_name AND d.specialty = 'Internal Medicine';


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.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
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 )
CREATE TABLE legal_services.appointments ( appointment_id.text, 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] Show the subject and start time for all appointments that are related to a case that also has an invoice. Include the case number and the invoice number.

[Assistant] SELECT T1.subject, T1.start_time, T2.case_number, T3.invoice_number FROM appointments AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id JOIN invoices AS T3 ON T2.case_id = T3.case_id;

[User] Only include appointments scheduled in the year 2024.

[Assistant] SELECT T1.subject, T1.start_time, T2.case_number, T3.invoice_number FROM appointments AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id JOIN invoices AS T3 ON T2.case_id = T3.case_id WHERE T1.start_time >= '2024-01-01' AND T1.start_time < '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 social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )

[User] Show the total number of likes made by each user, including the user_id and their like count.

[Assistant] SELECT user_id, COUNT(*) AS like_count FROM social_media.likes GROUP BY user_id;

[User] Only show users who have made more than 50 likes.

[Assistant] SELECT user_id, COUNT(*) AS like_count FROM social_media.likes GROUP BY user_id HAVING 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 social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments ( comment_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, parent_comment_id character varying(64), content text NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (comment_id) )
CREATE TABLE social_media.likes ( like_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, post_id character varying(64), comment_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (like_id), CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) )
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.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
CREATE TABLE social_media.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )
CREATE TABLE social_media.user_settings ( setting_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )

[User] List all comment IDs and their content for comments made by users who have 'dark' as their theme.

[Assistant]
SELECT c.comment_id, c.content
FROM social_media.comments c
JOIN social_media.user_settings s ON c.user_id = s.user_id
WHERE s.theme = 'dark';

[User] Also include the usernames of these users.

[Assistant]
SELECT c.comment_id, c.content, u.username
FROM social_media.comments c
JOIN social_media.user_settings s ON c.user_id = s.user_id
JOIN social_media.users u ON c.user_id = u.user_id
WHERE s.theme = 'dark';


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.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)

[User] Find all medical records associated with an appointment, and show the record_id, appointment_id, and the record_date.

[Assistant]
SELECT record_id, appointment_id, record_date
FROM healthcare.medical_records
WHERE appointment_id 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 hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
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.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 )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews (
    review_id 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] Show the full names and emails of staff members who have delivered at least one service order.

[Assistant]
SELECT DISTINCT s.first_name, s.last_name, s.work_email
FROM hospitality_technology.staff s
JOIN hospitality_technology.service_orders so
  ON s.staff_id = so.staff_id_delivered;

[User] Only include staff members who have delivered more than 10 service orders.

[Assistant]
SELECT s.first_name, s.last_name, s.work_email, COUNT(*) AS orders_delivered
FROM hospitality_technology.staff s
JOIN hospitality_technology.service_orders so
  ON s.staff_id = so.staff_id_delivered
GROUP BY s.staff_id, s.first_name, s.last_name, s.work_email
HAVING COUNT(*) > 10
ORDER BY orders_delivered 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, 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.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_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 text, created_at timestamp )
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 along with their provider, plan type, and the contact phone number. Also, for each plan, show how many doctors have their hospital affiliation ID matching the plan ID.

[Assistant] SELECT ip.plan_id, ip.plan_name, ip.insurance_provider, ip.plan_type, ip.contact_phone, COUNT(d.doctor_id) FROM healthcare.insurance_plans ip LEFT JOIN healthcare.doctors d ON ip.plan_id = d.hospital_affiliation_id GROUP BY ip.plan_id, ip.plan_name, ip.insurance_provider, ip.plan_type, ip.contact_phone


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
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.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id 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) )
CREATE TABLE hospitality_technology.payments ( payment_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, bill_id character varying(64), amount numeric(12,2) NOT NULL, currency_code character varying(3) NOT NULL, payment_method character varying(50) NOT NULL, card_type character varying(50), card_last_four character varying(4), transaction_ref character varying(128), payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, status character varying(50) NOT NULL, staff_id_processed character varying(64), notes text, PRIMARY KEY (payment_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, 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] List all staff members showing their full name and position.

[Assistant] SELECT first_name || ' ' || last_name AS staff_full_name, position FROM hospitality_technology.staff;

[User] Now only include staff who are not currently active and were hired before 2020.

[Assistant] SELECT first_name || ' ' || last_name AS staff_full_name, position FROM hospitality_technology.staff WHERE is_active = false AND hire_date < '2020-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 legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
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.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)

[User] I need to get the count of appointments grouped by their status.

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

[User] Only show counts for statuses 'Scheduled' and 'Completed'.

[Assistant]
SELECT a.status,
       COUNT(*) AS appointment_count
FROM legal_services.appointments a
WHERE a.status IN ('Scheduled', 'Completed')
GROUP BY a.status;

[User] Also restrict to appointments created after 2023-01-01.

[Assistant]
SELECT a.status,
       COUNT(*) AS appointment_count
FROM legal_services.appointments a
WHERE a.status IN ('Scheduled', 'Completed')
  AND a.created_at >= '2023-01-01'
GROUP BY a.status;

[User] Finally, order the groups by appointment_count in descending order.

[Assistant]
SELECT a.status,
       COUNT(*) AS appointment_count
FROM legal_services.appointments a
WHERE a.status IN ('Scheduled', 'Completed')
  AND a.created_at >= '2023-01-01'
GROUP BY a.status
ORDER BY appointment_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 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] What is the count of unique items acquired on each day?

[Assistant] SELECT DATE(acquired_at) AS acquisition_date, COUNT(DISTINCT item_id) AS unique_item_count FROM gaming_technology.player_inventory GROUP BY DATE(acquired_at);

[User] Only show days where more than 10 unique items were acquired.

[Assistant] SELECT DATE(acquired_at) AS acquisition_date, COUNT(DISTINCT item_id) AS unique_item_count FROM gaming_technology.player_inventory GROUP BY DATE(acquired_at) HAVING COUNT(DISTINCT item_id) > 10;

[User] Also include the total quantity of items acquired on those days.

[Assistant] SELECT DATE(acquired_at) AS acquisition_date, COUNT(DISTINCT item_id) AS unique_item_count, SUM(quantity) AS total_quantity FROM gaming_technology.player_inventory GROUP BY DATE(acquired_at) HAVING COUNT(DISTINCT item_id) > 10;

[User] Order the results by the total quantity in descending order.

[Assistant] SELECT DATE(acquired_at) AS acquisition_date, COUNT(DISTINCT item_id) AS unique_item_count, SUM(quantity) AS total_quantity FROM gaming_technology.player_inventory GROUP BY DATE(acquired_at) HAVING COUNT(DISTINCT item_id) > 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 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.doctors ( doctor_id text, 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 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.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, 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] Retrieve the first and last names of all doctors who specialize in Cardiology.

[Assistant]
SELECT first_name, last_name
FROM healthcare.doctors
WHERE specialty = 'Cardiology';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )
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] Show me the case number, client ID, and total amount for each case that has at least one invoice.

[Assistant]
SELECT c.case_number, c.client_id, SUM(i.total_amount) AS total_invoice_amount
FROM legal_services.cases c
JOIN legal_services.invoices i ON c.case_id = i.case_id
GROUP BY c.case_number, c.client_id;

[User] Only include cases where the total invoice amount exceeds 10,000.

[Assistant]
SELECT c.case_number, c.client_id, SUM(i.total_amount) AS total_invoice_amount
FROM legal_services.cases c
JOIN legal_services.invoices i ON c.case_id = i.case_id
GROUP BY c.case_number, c.client_id
HAVING SUM(i.total_amount) > 10000;