System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )
CREATE TABLE gaming_technology.games ( game_id uuid NOT NULL DEFAULT gen_random_uuid(), title character varying(200) NOT NULL, developer_id uuid NOT NULL, publisher_id uuid, genre character varying(100), release_date date, description text, platform character varying(50) NOT NULL, engine character varying(100), website character varying(255), PRIMARY KEY (game_id) )
CREATE TABLE gaming_technology.developers ( developer_id uuid NOT NULL DEFAULT gen_random_uuid(), name character varying(150) NOT NULL UNIQUE, country character varying(100), founded_year integer, website character varying(255), created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (developer_id) )
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, name character varying(150) NOT NULL, description text NOT NULL, icon_url character varying(255), points integer DEFAULT 0, hidden boolean DEFAULT false, PRIMARY KEY (achievement_id) )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )

[User] Count how many achievements were unlocked on each calendar day. Show the date and the count.

[Assistant] SELECT DATE(unlocked_at) AS unlock_date, COUNT(*) AS achievement_count FROM gaming_technology.player_achievements GROUP BY unlock_date;

[User] Only include dates where more than 50 achievements were unlocked.

[Assistant] SELECT DATE(unlocked_at) AS unlock_date, COUNT(*) AS achievement_count FROM gaming_technology.player_achievements GROUP BY unlock_date HAVING COUNT(*) > 50;

[User] Additionally, include the number of *distinct players* who unlocked achievements on each of those dates.

[Assistant] SELECT DATE(unlocked_at) AS unlock_date, COUNT(*) AS achievement_count, COUNT(DISTINCT player_id) AS distinct_players FROM gaming_technology.player_achievements GROUP BY unlock_date HAVING COUNT(*) > 50;

[User] Order the results by the distinct player count in descending order.

[Assistant] SELECT DATE(unlocked_at) AS unlock_date, COUNT(*) AS achievement_count, COUNT(DISTINCT player_id) AS distinct_players FROM gaming_technology.player_achievements GROUP BY unlock_date HAVING COUNT(*) > 50 ORDER BY distinct_players DESC;

[User] For each player, show the player_id and the count of inventory items they acquired with a quantity greater than 1.

[Assistant] SELECT player_id, COUNT(inventory_id) AS items_qty_gt_1_count FROM gaming_technology.player_inventory WHERE quantity > 1 GROUP BY player_id;

[User] I want the number of achievements unlocked per country_code by active players, showing only countries with at least 100 unlocks.

[Assistant]
SELECT p.country_code, COUNT(*) AS unlock_count
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.country_code
HAVING COUNT(*) >= 100;

[User] Please exclude entries where country_code is NULL and sort the output by unlock_count descending.

[Assistant]
SELECT p.country_code, COUNT(*) AS unlock_count
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa
  ON p.player_id = pa.player_id
WHERE p.status = 'active'
  AND p.country_code IS NOT NULL
GROUP BY p.country_code
HAVING COUNT(*) >= 100
ORDER BY unlock_count DESC;

[User] For each game, count the total number of achievements unlocked across all players. Show game title and count.

[Assistant] SELECT g.title, COUNT(pa.player_achievement_id) AS total_unlocked_achievements FROM gaming_technology.games AS g JOIN gaming_technology.achievements AS a ON g.game_id = a.game_id JOIN gaming_technology.player_achievements AS pa ON a.achievement_id = pa.achievement_id GROUP BY g.title;

[User] Only include games that have more than 100 achievements unlocked.

[Assistant] SELECT g.title, COUNT(pa.player_achievement_id) AS total_unlocked_achievements FROM gaming_technology.games AS g JOIN gaming_technology.achievements AS a ON g.game_id = a.game_id JOIN gaming_technology.player_achievements AS pa ON a.achievement_id = pa.achievement_id GROUP BY g.title HAVING COUNT(pa.player_achievement_id) > 100;

[User] For these games, also show the number of servers hosting that game.

[Assistant] SELECT g.title, COUNT(pa.player_achievement_id) AS total_unlocked_achievements, COUNT(s.server_id) AS server_count FROM gaming_technology.games AS g JOIN gaming_technology.achievements AS a ON g.game_id = a.game_id JOIN gaming_technology.player_achievements AS pa ON a.achievement_id = pa.achievement_id LEFT JOIN gaming_technology.servers AS s ON g.game_id = s.game_id GROUP BY g.title HAVING COUNT(pa.player_achievement_id) > 100;

[User] Count the number of servers for each possible status recorded in the servers table.

[Assistant] SELECT status, COUNT(server_id) AS server_count FROM gaming_technology.servers GROUP BY status;

[User] Only include statuses where the server count is greater than 5.

[Assistant] SELECT status, COUNT(server_id) AS server_count FROM gaming_technology.servers GROUP BY status HAVING COUNT(server_id) > 5;

[User] For those filtered statuses, calculate the total number of current players across the servers in each status group.

[Assistant] SELECT status, COUNT(server_id) AS server_count, SUM(current_players) AS total_current_players FROM gaming_technology.servers GROUP BY status HAVING COUNT(server_id) > 5;

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

[Assistant] SELECT status, COUNT(server_id) AS server_count, SUM(current_players) AS total_current_players FROM gaming_technology.servers GROUP BY status HAVING COUNT(server_id) > 5 ORDER BY total_current_players DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.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.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 text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
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 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] Retrieve each guest's full name and the date of their most recent review, including review_source.

[Assistant]
SELECT sub.guest_id, sub.full_name, sub.review_date AS last_review_date, sub.review_source
FROM (
  SELECT g.guest_id,
         g.first_name || ' ' || g.last_name AS full_name,
         r.review_date,
         r.review_source,
         ROW_NUMBER() OVER (PARTITION BY g.guest_id ORDER BY r.review_date DESC) AS rn
  FROM hospitality_technology.guests g
  JOIN hospitality_technology.reviews r ON g.guest_id = r.guest_id
) sub
WHERE sub.rn = 1;

[User] I only want guests who have opted in for communication and whose latest review is public.

[Assistant]
SELECT sub.guest_id, sub.full_name, sub.review_date AS last_review_date, sub.review_source
FROM (
  SELECT g.guest_id,
         g.first_name || ' ' || g.last_name AS full_name,
         r.review_date,
         r.review_source,
         r.is_public,
         ROW_NUMBER() OVER (PARTITION BY g.guest_id ORDER BY r.review_date DESC) AS rn
  FROM hospitality_technology.guests g
  JOIN hospitality_technology.reviews r ON g.guest_id = r.guest_id
  WHERE g.communication_consent = true
) sub
WHERE sub.rn = 1 AND sub.is_public = true;

[User] Also include the review comment and order the results by last_review_date descending, limiting to the top 10 entries.

[Assistant]
SELECT sub.guest_id, sub.full_name, sub.review_date AS last_review_date, sub.review_source, sub.comment
FROM (
  SELECT g.guest_id,
         g.first_name || ' ' || g.last_name AS full_name,
         r.review_date,
         r.review_source,
         r.comment,
         r.is_public,
         ROW_NUMBER() OVER (PARTITION BY g.guest_id ORDER BY r.review_date DESC) AS rn
  FROM hospitality_technology.guests g
  JOIN hospitality_technology.reviews r ON g.guest_id = r.guest_id
  WHERE g.communication_consent = true AND r.is_public = true
) sub
WHERE sub.rn = 1
ORDER BY sub.review_date DESC
LIMIT 10;

[User] For each department, list the total number of available services and the total combined price of those services.

[Assistant]
SELECT department, COUNT(*) AS service_count, SUM(price) AS total_price
FROM hospitality_technology.services
WHERE is_available = true
GROUP BY department;

[User] Actually, show only departments where the combined price exceeds 1000.

[Assistant]
SELECT department, COUNT(*) AS service_count, SUM(price) AS total_price
FROM hospitality_technology.services
WHERE is_available = true
GROUP BY department
HAVING SUM(price) > 1000;

[User] List all services in the 'Concierge' department along with their names, price, and whether they are currently available. Include the property name as well.

[Assistant]
SELECT s.service_name, s.price, s.is_available, p.property_name
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.department = 'Concierge';

[User] Could you filter only those services that are not currently available and sort by price ascending?

[Assistant]
SELECT s.service_name, s.price, s.is_available, p.property_name
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.department = 'Concierge'
  AND s.is_available = false
ORDER BY s.price ASC;

[User] Instead, show only properties in the city of 'Miami' and add the service category to the results.

[Assistant]
SELECT s.service_name, s.category, s.price, s.is_available, p.property_name
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.department = 'Concierge'
  AND s.is_available = false
  AND p.city = 'Miami'
ORDER BY s.price ASC;

[User] Show me the list of all guests who have reservations along with the room number, room type name, and property name for each reservation.

[Assistant]
SELECT g.first_name, g.last_name, r.room_number, rt.type_name AS room_type_name, p.property_name
FROM hospitality_technology.reservations res
JOIN hospitality_technology.guests g ON res.guest_id = g.guest_id
LEFT JOIN hospitality_technology.rooms r ON res.room_id = r.room_id
LEFT JOIN hospitality_technology.room_types rt ON res.room_type_id = rt.room_type_id
JOIN hospitality_technology.properties p ON res.property_id = p.property_id;

[User] Get a list of room types along with their property name and the count of rooms currently Available for each type.

[Assistant]
SELECT rt.type_name, p.property_name, COUNT(r.room_id) AS available_rooms_count
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.rooms r ON rt.room_type_id = r.room_type_id
  AND r.status = 'Available'
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
GROUP BY rt.type_name, p.property_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.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, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department 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 text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] List all payments for reservations made at properties with a star rating of 5.0. Include the payment amount, guest ID, reservation ID, and property name.

[Assistant] SELECT T1.amount, T1.guest_id, T1.reservation_id, T3.property_name FROM hospitality_technology.payments AS T1 JOIN hospitality_technology.reservations AS T2 ON T1.reservation_id = T2.reservation_id JOIN hospitality_technology.properties AS T3 ON T2.property_id = T3.property_id WHERE T3.star_rating = 5.0

[User] List all public reviews that have a staff response, showing the review ID, overall rating, and the full name of the staff member who responded.

[Assistant] SELECT T1.review_id, T1.rating_overall, T2.first_name, T2.last_name FROM hospitality_technology.reviews AS T1 JOIN hospitality_technology.staff AS T2 ON T1.response_staff_id = T2.staff_id WHERE T1.is_public = true AND T1.response_staff_id IS NOT NULL

[User] Also include the property name for each of these reviews.

[Assistant] SELECT T1.review_id, T1.rating_overall, T2.first_name, T2.last_name, T3.property_name FROM hospitality_technology.reviews AS T1 JOIN hospitality_technology.staff AS T2 ON T1.response_staff_id = T2.staff_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id WHERE T1.is_public = true AND T1.response_staff_id IS NOT NULL

[User] Filter the results to only show reviews with an overall rating of 5 and those responded to in the last 90 days.

[Assistant] SELECT T1.review_id, T1.rating_overall, T2.first_name, T2.last_name, T3.property_name FROM hospitality_technology.reviews AS T1 JOIN hospitality_technology.staff AS T2 ON T1.response_staff_id = T2.staff_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id WHERE T1.is_public = true AND T1.response_staff_id IS NOT NULL AND T1.rating_overall = 5 AND T1.response_date >= CURRENT_DATE - INTERVAL '90 days'

[User] Which properties offer services in the 'Business Center' department, and what are the names and prices of those services?

[Assistant]
SELECT p.property_id, p.property_name, s.service_name, s.price
FROM hospitality_technology.properties p
JOIN hospitality_technology.services s ON p.property_id = s.property_id
WHERE s.department = 'Business Center';

[User] Actually, only show those services that are currently available and sort the results by price ascending.

[Assistant]
SELECT p.property_id, p.property_name, s.service_name, s.price
FROM hospitality_technology.properties p
JOIN hospitality_technology.services s ON p.property_id = s.property_id
WHERE s.department = 'Business Center' AND s.is_available = TRUE
ORDER BY s.price ASC;

[User] List all future reservations (where check_in_date > current_date) including guest full name, room_id, property_id, and the number of days until check-in.

[Assistant]
SELECT r.reservation_id, r.property_id, r.room_id,
       g.first_name || ' ' || g.last_name AS guest_name,
       (r.check_in_date - CURRENT_DATE) AS days_until_check_in
FROM hospitality_technology.reservations r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
WHERE r.check_in_date > CURRENT_DATE;

[User] Show me the number of service orders placed for each service category.

[Assistant]
SELECT s.category, COUNT(so.order_id) AS order_count
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
GROUP BY s.category;

[User] Only include categories with more than 10 orders and order by order_count descending.

[Assistant]
SELECT s.category, COUNT(so.order_id) AS order_count
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
GROUP BY s.category
HAVING COUNT(so.order_id) > 10
ORDER BY order_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 web3.contracts (
    contract_id character varying(64) NOT NULL,  -- unique identifier for the contract
    address character varying(128) NOT NULL, -- address of the deployed contract
    abi text NOT NULL, -- application binary interface of the contract
    bytecode text NOT NULL, -- bytecode of the contract
    deployer_address character varying(128) NOT NULL, -- address of the deployer
    deployed_at timestamp NOT NULL, -- time when the contract was deployed
    network_id character varying(64) NOT NULL, -- identifier of the network where the contract is deployed
    status character varying(32) NOT NULL, -- status of the contract (e.g., active, deprecated)
    PRIMARY KEY (contract_id)
)
CREATE TABLE web3.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128), -- address of the receiver (can be null for contract deployment)
    value numeric(38,14) NOT NULL, -- value transferred
    gas_used integer NOT NULL, -- amount of gas used by the transaction
    gas_price numeric(38,14) NOT NULL, -- price of gas at the time of the transaction
    block_number integer NOT NULL, -- block number containing the transaction
    timestamp timestamp NOT NULL, -- time when the transaction was mined
    input_data text, -- input data of the transaction (can be null)
    status character varying(32) NOT NULL, -- status of the transaction (e.g., success, failed)
    nonce integer NOT NULL, -- nonce of the sender at the time of the transaction
    PRIMARY KEY (transaction_id)
)
CREATE TABLE web3.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)

[User] For each user with at least two wallets, calculate the average time difference in hours between consecutive wallet creations. Return user_id and avg_diff_hours.

[Assistant] SELECT user_id, AVG(EXTRACT(EPOCH FROM (created_at - prev_created)) / 3600) AS avg_diff_hours FROM (SELECT user_id, created_at, LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at) AS prev_created FROM web3.wallets) t WHERE prev_created IS NOT NULL GROUP BY user_id;

[User] Actually, restrict the results to users whose avg_diff_hours is less than 24 hours and sort by avg_diff_hours ascending.

[Assistant] WITH diffs AS (SELECT user_id, EXTRACT(EPOCH FROM (created_at - prev_created)) / 3600 AS diff_hours FROM (SELECT user_id, created_at, LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at) AS prev_created FROM web3.wallets) sub WHERE prev_created IS NOT NULL) SELECT user_id, AVG(diff_hours) AS avg_diff_hours FROM diffs GROUP BY user_id HAVING AVG(diff_hours) < 24 ORDER BY avg_diff_hours;

[User] Show each contract address and the count of successful transactions sent to that contract.

[Assistant] SELECT c.address, COUNT(t.transaction_id) AS success_tx_count FROM web3.contracts c JOIN web3.transactions t ON t.to_address = c.address AND t.status = 'success' GROUP BY c.address;

[User] List all transactions along with the user_id of the sender when the sender’s address matches a wallet. Return transaction_id, from_address, and user_id.

[Assistant] SELECT t.transaction_id, t.from_address, w.user_id FROM web3.transactions t JOIN web3.wallets w ON t.from_address = w.address;

[User] List each transaction ID that includes token transfers, along with the distinct symbols of the tokens transferred in that transaction.

[Assistant] SELECT T1.transaction_id, STRING_AGG(DISTINCT T3.token_symbol, ', ') FROM web3.transactions AS T1 JOIN web3.token_transfers AS T2 ON T1.transaction_id = T2.transaction_id JOIN web3.tokens AS T3 ON T2.token_id = T3.token_id GROUP BY T1.transaction_id

[User] For each transaction status, what is the average transaction value?

[Assistant] SELECT status, AVG(value) FROM web3.transactions GROUP BY status

[User] Could you filter this to only show statuses where the average value is greater than 100?

[Assistant] SELECT status, AVG(value) FROM web3.transactions GROUP BY status HAVING AVG(value) > 100


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.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )

[User] List all locations situated within the state of California.

[Assistant] SELECT location_id, name, city, state_province FROM transportation.locations WHERE state_province = 'CA';

[User] Now, refine this list to only include locations that are specifically in Los Angeles.

[Assistant] SELECT location_id, name, city, state_province FROM transportation.locations WHERE state_province = 'CA' AND city = 'Los Angeles';

[User] Could you also include the type of location and its postal code in the result?

[Assistant] SELECT location_id, name, city, state_province, type, postal_code FROM transportation.locations WHERE state_province = 'CA' AND city = 'Los Angeles';

[User] Finally, order these locations by their name in alphabetical order.

[Assistant] SELECT location_id, name, city, state_province, type, postal_code FROM transportation.locations WHERE state_province = 'CA' AND city = 'Los Angeles' ORDER BY name;

[User] Show me all locations in New York with latitude above 40.7, including their type and coordinates.

[Assistant] SELECT name, type, latitude, longitude FROM transportation.locations WHERE state_province = 'New York' AND latitude > 40.7;

[User] There's a typo in your SQL - it should be 'locations' not 'locatons'. Also, can you include the city and order by latitude in descending order?

[Assistant] SELECT name, type, city, latitude, longitude FROM transportation.locations WHERE state_province = 'New York' AND latitude > 40.7 ORDER BY latitude DESC;

[User] Now filter these results to only show locations of type 'gas station' or 'depot' and include their postal codes.

[Assistant] SELECT name, type, city, postal_code, latitude, longitude FROM transportation.locations WHERE state_province = 'New York' AND latitude > 40.7 AND type IN ('gas station', 'depot') ORDER BY latitude DESC;

[User] Can you show me the name, city, and type for all locations that are in the same city but have different types?

[Assistant] SELECT l1.name, l1.city, l1.type FROM transportation.locations l1 JOIN transportation.locations l2 ON l1.city = l2.city AND l1.location_id <> l2.location_id AND l1.type <> l2.type;

[User] Please only include locations where the city is 'Chicago'.

[Assistant] SELECT l1.name, l1.city, l1.type FROM transportation.locations l1 JOIN transportation.locations l2 ON l1.city = l2.city AND l1.location_id <> l2.location_id AND l1.type <> l2.type WHERE l1.city = 'Chicago';

[User] Find all cities that contain at least one location of type 'Depot' and at least one location of type 'Station'.

[Assistant] SELECT city FROM transportation.locations WHERE type IN ('Depot', 'Station') GROUP BY city HAVING COUNT(DISTINCT CASE WHEN type = 'Depot' THEN location_id END) > 0 AND COUNT(DISTINCT CASE WHEN type = 'Station' THEN location_id END) > 0;

[User] Can you give me all locations in Los Angeles?

[Assistant]
SELECT location_id, name, type, address_line1, city, state_province, postal_code, country, latitude, longitude, timezone
FROM transportation.locations
WHERE city = 'Los Angeles';

[User] I want to see only locations of type 'Depot' in Los Angeles.

[Assistant]
SELECT location_id, name, type, address_line1, city, state_province, postal_code, country, latitude, longitude, timezone
FROM transportation.locations
WHERE city = 'Los Angeles' AND type = 'Depot';

[User] Can you show me their postal codes and sort them by name in ascending order?

[Assistant]
SELECT location_id, name, postal_code
FROM transportation.locations
WHERE city = 'Los Angeles' AND type = 'Depot'
ORDER BY name ASC;

[User] Actually, I also want to see the state_province in the output.

[Assistant]
SELECT location_id, name, postal_code, state_province
FROM transportation.locations
WHERE city = 'Los Angeles' AND type = 'Depot'
ORDER BY name ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )

[User] I want to identify pairs of players who unlocked the same achievement within one hour of each other. List player1_id, player2_id, achievement_id, and the time difference in minutes.

[Assistant]
SELECT pa1.player_id AS player1_id,
       pa2.player_id AS player2_id,
       pa1.achievement_id,
       ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) AS time_diff_minutes
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.achievement_id = pa2.achievement_id
     AND pa1.player_id <> pa2.player_id
WHERE ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) <= 60;

[User] Actually, ensure we only list each pair once by showing only cases where player1_id < player2_id.

[Assistant]
SELECT pa1.player_id AS player1_id,
       pa2.player_id AS player2_id,
       pa1.achievement_id,
       ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) AS time_diff_minutes
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.achievement_id = pa2.achievement_id
     AND pa1.player_id < pa2.player_id
WHERE ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) <= 60;

[User] Also, only include cases where the time difference is less than 30 minutes.

[Assistant]
SELECT pa1.player_id AS player1_id,
       pa2.player_id AS player2_id,
       pa1.achievement_id,
       ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) AS time_diff_minutes
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.achievement_id = pa2.achievement_id
     AND pa1.player_id < pa2.player_id
WHERE ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) < 30;

[User] And only for achievements unlocked after '2023-01-01'.

[Assistant]
SELECT pa1.player_id AS player1_id,
       pa2.player_id AS player2_id,
       pa1.achievement_id,
       ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) AS time_diff_minutes
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.achievement_id = pa2.achievement_id
     AND pa1.player_id < pa2.player_id
WHERE pa1.unlocked_at >= '2023-01-01'
  AND pa2.unlocked_at >= '2023-01-01'
  AND ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) < 30;

[User] List all pairs of achievements unlocked by the same player, showing player_id, achievement1, and achievement2.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS achievement1,
       pa2.achievement_id AS achievement2
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa1.unlocked_at < pa2.unlocked_at;

[User] Now include only pairs where the second achievement was unlocked within 7 days of the first.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS achievement1,
       pa2.achievement_id AS achievement2
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa1.unlocked_at < pa2.unlocked_at
 AND pa2.unlocked_at <= pa1.unlocked_at + INTERVAL '7 days';

[User] List each achievement with the very next achievement unlocked by the same player using a self-join. Show player_id, current_ach, current_unlocked_at, next_ach, and next_unlocked_at.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS current_ach,
       pa1.unlocked_at AS current_unlocked_at,
       pa2.achievement_id AS next_ach,
       pa2.unlocked_at AS next_unlocked_at
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa2.unlocked_at = (
     SELECT MIN(pa3.unlocked_at)
     FROM gaming_technology.player_achievements pa3
     WHERE pa3.player_id = pa1.player_id
       AND pa3.unlocked_at > pa1.unlocked_at
 );

[User] Now restrict to pairs where the time difference between current_unlocked_at and next_unlocked_at is less than 48 hours.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS current_ach,
       pa1.unlocked_at AS current_unlocked_at,
       pa2.achievement_id AS next_ach,
       pa2.unlocked_at AS next_unlocked_at
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa2.unlocked_at = (
     SELECT MIN(pa3.unlocked_at)
     FROM gaming_technology.player_achievements pa3
     WHERE pa3.player_id = pa1.player_id
       AND pa3.unlocked_at > pa1.unlocked_at
 )
WHERE pa2.unlocked_at - pa1.unlocked_at < INTERVAL '48 hours';

[User] Order the results by player_id and current_unlocked_at ascending.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS current_ach,
       pa1.unlocked_at AS current_unlocked_at,
       pa2.achievement_id AS next_ach,
       pa2.unlocked_at AS next_unlocked_at
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa2.unlocked_at = (
     SELECT MIN(pa3.unlocked_at)
     FROM gaming_technology.player_achievements pa3
     WHERE pa3.player_id = pa1.player_id
       AND pa3.unlocked_at > pa1.unlocked_at
 )
WHERE pa2.unlocked_at - pa1.unlocked_at < INTERVAL '48 hours'
ORDER BY pa1.player_id ASC, pa1.unlocked_at ASC;

[User] Finally, limit to 20 rows.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS current_ach,
       pa1.unlocked_at AS current_unlocked_at,
       pa2.achievement_id AS next_ach,
       pa2.unlocked_at AS next_unlocked_at
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa2.unlocked_at = (
     SELECT MIN(pa3.unlocked_at)
     FROM gaming_technology.player_achievements pa3
     WHERE pa3.player_id = pa1.player_id
       AND pa3.unlocked_at > pa1.unlocked_at
 )
WHERE pa2.unlocked_at - pa1.unlocked_at < INTERVAL '48 hours'
ORDER BY pa1.player_id ASC, pa1.unlocked_at ASC
LIMIT 20;

[User] Can you show me all achievement unlock records where the same player unlocked two different achievements within the same day? Please show player_id, achievement_id_1, achievement_id_2, and the unlock dates for each.

[Assistant]
SELECT pa1.player_id, pa1.achievement_id as achievement_id_1, pa2.achievement_id as achievement_id_2, pa1.unlocked_at as unlock_date_1, pa2.unlocked_at as unlock_date_2
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
  AND pa1.achievement_id <> pa2.achievement_id
  AND DATE(pa1.unlocked_at) = DATE(pa2.unlocked_at)
  AND pa1.unlocked_at < pa2.unlocked_at;

[User] Add a condition to only include records where both achievements were unlocked on or after January 1st, 2024.

[Assistant]
SELECT pa1.player_id, pa1.achievement_id as achievement_id_1, pa2.achievement_id as achievement_id_2, pa1.unlocked_at as unlock_date_1, pa2.unlocked_at as unlock_date_2
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
  AND pa1.achievement_id <> pa2.achievement_id
  AND DATE(pa1.unlocked_at) = DATE(pa2.unlocked_at)
  AND pa1.unlocked_at < pa2.unlocked_at
WHERE pa1.unlocked_at >= '2024-01-01' AND pa2.unlocked_at >= '2024-01-01';

[User] How many achievements has each player unlocked and what's the earliest unlocked timestamp for each?

[Assistant]
SELECT player_id,
       COUNT(*) AS total_unlocked,
       MIN(unlocked_at) AS first_unlocked
FROM gaming_technology.player_achievements
GROUP BY player_id;

[User] Exclude players with fewer than 3 achievements.

[Assistant]
SELECT player_id,
       COUNT(*) AS total_unlocked,
       MIN(unlocked_at) AS first_unlocked
FROM gaming_technology.player_achievements
GROUP BY player_id
HAVING COUNT(*) >= 3;

[User] Order the results by first_unlocked ascending.

[Assistant]
SELECT player_id,
       COUNT(*) AS total_unlocked,
       MIN(unlocked_at) AS first_unlocked
FROM gaming_technology.player_achievements
GROUP BY player_id
HAVING COUNT(*) >= 3
ORDER BY first_unlocked ASC;

[User] Only show the top 10 players after ordering.

[Assistant]
SELECT player_id,
       COUNT(*) AS total_unlocked,
       MIN(unlocked_at) AS first_unlocked
FROM gaming_technology.player_achievements
GROUP BY player_id
HAVING COUNT(*) >= 3
ORDER BY first_unlocked ASC
LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] Get the count of unread 'message' notifications per group chat, showing conversation_id, group_name, and unread_message_notifications.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_message_notifications
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'message'
  AND n.read_at IS NULL
GROUP BY c.conversation_id, c.group_name;

[User] Actually, only include group chats where unread_message_notifications > 5.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_message_notifications
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'message'
  AND n.read_at IS NULL
GROUP BY c.conversation_id, c.group_name
HAVING COUNT(n.notification_id) > 5;

[User] List all users with private profiles who have disabled push notifications, including their user_id and email_notifications_enabled status.

[Assistant]
SELECT user_id,
       email_notifications_enabled
FROM social_media.user_settings
WHERE private_profile = true
  AND push_notifications_enabled = false;

[User] I want to see for each group chat the count of unread 'mention' notifications received by its recipients. Include conversation_id, group_name, and unread_mentions.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_mentions
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'mention'
  AND n.read_at IS NULL
GROUP BY c.conversation_id, c.group_name;

[User] Now only include group chats created within the past year.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_mentions
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'mention'
  AND n.read_at IS NULL
WHERE c.created_at >= NOW() - INTERVAL '1 year'
GROUP BY c.conversation_id, c.group_name;

[User] Order the results by unread_mentions descending.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_mentions
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'mention'
  AND n.read_at IS NULL
WHERE c.created_at >= NOW() - INTERVAL '1 year'
GROUP BY c.conversation_id, c.group_name
ORDER BY unread_mentions DESC;

[User] Limit to the top 5 group chats.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_mentions
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'mention'
  AND n.read_at IS NULL
WHERE c.created_at >= NOW() - INTERVAL '1 year'
GROUP BY c.conversation_id, c.group_name
ORDER BY unread_mentions DESC
LIMIT 5;

[User] How many unread messages does each sender have? Show sender_user_id and count of messages where read_at is null.

[Assistant]
SELECT sender_user_id, COUNT(*) AS unread_messages
FROM social_media.messages
WHERE read_at IS NULL
GROUP BY sender_user_id;

[User] List all messages that haven’t triggered any notification; show message_id, sender_user_id, and sent_at.

[Assistant]
SELECT m.message_id, m.sender_user_id, m.sent_at
FROM social_media.messages AS m
LEFT JOIN social_media.notifications AS n
  ON n.target_entity_type = 'message'
  AND n.target_entity_id = m.message_id
WHERE n.notification_id IS NULL;

[User] Actually, only include those sent before '2024-06-01'.

[Assistant]
SELECT m.message_id, m.sender_user_id, m.sent_at
FROM social_media.messages AS m
LEFT JOIN social_media.notifications AS n
  ON n.target_entity_type = 'message'
  AND n.target_entity_id = m.message_id
WHERE n.notification_id IS NULL
  AND m.sent_at < '2024-06-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 token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )

[User] List tokens on 'Arbitrum' with liquidity over 5000000.

[Assistant] SELECT * FROM token_dexpool_info WHERE chain = 'Arbitrum' AND liquidity > 5000000;

[User] Filter those tokens to only include ones with a positive price change in the last 24 hours.

[Assistant] SELECT * FROM token_dexpool_info WHERE chain = 'Arbitrum' AND liquidity > 5000000 AND price_change_percentage_24h > 0;

[User] Order the results by 24-hour trading volume descending and show the top 5 tokens.

[Assistant] SELECT * FROM token_dexpool_info WHERE chain = 'Arbitrum' AND liquidity > 5000000 AND price_change_percentage_24h > 0 ORDER BY volume_24h DESC LIMIT 5;

[User] Also show their market cap and trend rank.

[Assistant] SELECT token_symbol, token_name, chain, price, liquidity, price_change_percentage_24h, volume_24h, market_cap, trend_rank FROM token_dexpool_info WHERE chain = 'Arbitrum' AND liquidity > 5000000 AND price_change_percentage_24h > 0 ORDER BY volume_24h DESC LIMIT 5;

[User] Which three tokens on the Arbitrum chain have the lowest 6-hour price change percentage?

[Assistant] SELECT token_symbol, price_change_percentage_6h FROM token_dexpool_info WHERE chain = 'Arbitrum' ORDER BY price_change_percentage_6h ASC LIMIT 3;

[User] Please also show their current price and trading volume.

[Assistant] SELECT token_symbol, price_change_percentage_6h, price, volume_24h FROM token_dexpool_info WHERE chain = 'Arbitrum' ORDER BY price_change_percentage_6h ASC LIMIT 3;

[User] Now include their liquidity and market cap in the result.

[Assistant] SELECT token_symbol, price_change_percentage_6h, price, volume_24h, liquidity, market_cap FROM token_dexpool_info WHERE chain = 'Arbitrum' ORDER BY price_change_percentage_6h ASC LIMIT 3;

[User] Restrict to only those tokens where market cap is above 10 million.

[Assistant] SELECT token_symbol, price_change_percentage_6h, price, volume_24h, liquidity, market_cap FROM token_dexpool_info WHERE chain = 'Arbitrum' AND market_cap > 10000000 ORDER BY price_change_percentage_6h ASC LIMIT 3;

[User] List tokens with trend rank 5 or better and a price below $1. Show symbol, price, and trend rank.

[Assistant] SELECT token_symbol, price, trend_rank FROM token_dexpool_info WHERE trend_rank IS NOT NULL AND trend_rank <= 5 AND price < 1;

[User] Find tokens on the 'Ethereum' chain with a 6-hour price increase above 5%, and include their net_flow and roi from smart money performance.

[Assistant]
SELECT d.token_symbol, d.chain, d.price_change_percentage_6h, p.net_flow, p.roi
FROM token_dexpool_info d
JOIN smart_money_token_performance p ON d.token_symbol = p.token_symbol AND d.chain = p.chain
WHERE d.chain = 'Ethereum' AND d.price_change_percentage_6h > 5;

[User] Only include those with a 24h trading volume greater than 1000000.

[Assistant]
SELECT d.token_symbol, d.chain, d.price_change_percentage_6h, d.volume_24h, p.net_flow, p.roi
FROM token_dexpool_info d
JOIN smart_money_token_performance p ON d.token_symbol = p.token_symbol AND d.chain = p.chain
WHERE d.chain = 'Ethereum' AND d.price_change_percentage_6h > 5
  AND d.volume_24h > 1000000;

[User] Sort the results by net_flow descending and limit to the top 3 tokens.

[Assistant]
SELECT d.token_symbol, d.chain, d.price_change_percentage_6h, d.volume_24h, p.net_flow, p.roi
FROM token_dexpool_info d
JOIN smart_money_token_performance p ON d.token_symbol = p.token_symbol AND d.chain = p.chain
WHERE d.chain = 'Ethereum' AND d.price_change_percentage_6h > 5
  AND d.volume_24h > 1000000
ORDER BY p.net_flow DESC
LIMIT 3;

[User] Also include the number of makers in the last 24h for each of these tokens.

[Assistant]
SELECT d.token_symbol, d.chain, d.price_change_percentage_6h, d.volume_24h, d.makers_24h, p.net_flow, p.roi
FROM token_dexpool_info d
JOIN smart_money_token_performance p ON d.token_symbol = p.token_symbol AND d.chain = p.chain
WHERE d.chain = 'Ethereum' AND d.price_change_percentage_6h > 5
  AND d.volume_24h > 1000000
ORDER BY p.net_flow DESC
LIMIT 3;

[User] For each chain, find the token with the highest 24h trading volume and the token with the lowest 24h trading volume. Show chain, high_volume_token, high_volume_24h, low_volume_token, and low_volume_24h.

[Assistant]
WITH max_vol AS (
  SELECT chain,
         token_symbol AS high_volume_token,
         volume_24h AS high_volume_24h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MAX(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
), min_vol AS (
  SELECT chain,
         token_symbol AS low_volume_token,
         volume_24h AS low_volume_24h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MIN(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
)
SELECT m.chain,
       m.high_volume_token,
       m.high_volume_24h,
       n.low_volume_token,
       n.low_volume_24h
FROM max_vol m
JOIN min_vol n ON m.chain = n.chain;

[User] Exclude chains where the highest volume is below 100,000.

[Assistant]
WITH max_vol AS (
  SELECT chain,
         token_symbol AS high_volume_token,
         volume_24h AS high_volume_24h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MAX(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
), min_vol AS (
  SELECT chain,
         token_symbol AS low_volume_token,
         volume_24h AS low_volume_24h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MIN(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
)
SELECT m.chain,
       m.high_volume_token,
       m.high_volume_24h,
       n.low_volume_token,
       n.low_volume_24h
FROM max_vol m
JOIN min_vol n ON m.chain = n.chain
WHERE m.high_volume_24h >= 100000;

[User] Also include the 6h price change percentage for those high and low volume tokens in the output.

[Assistant]
WITH max_vol AS (
  SELECT chain,
         token_symbol AS high_volume_token,
         volume_24h AS high_volume_24h,
         price_change_percentage_6h AS high_change_6h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MAX(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
), min_vol AS (
  SELECT chain,
         token_symbol AS low_volume_token,
         volume_24h AS low_volume_24h,
         price_change_percentage_6h AS low_change_6h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MIN(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
)
SELECT m.chain,
       m.high_volume_token,
       m.high_volume_24h,
       m.high_change_6h,
       n.low_volume_token,
       n.low_volume_24h,
       n.low_change_6h
FROM max_vol m
JOIN min_vol n ON m.chain = n.chain;

[User] Finally, order the result by chain in ascending order.

[Assistant]
WITH max_vol AS (
  SELECT chain,
         token_symbol AS high_volume_token,
         volume_24h AS high_volume_24h,
         price_change_percentage_6h AS high_change_6h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MAX(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
), min_vol AS (
  SELECT chain,
         token_symbol AS low_volume_token,
         volume_24h AS low_volume_24h,
         price_change_percentage_6h AS low_change_6h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MIN(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
)
SELECT m.chain,
       m.high_volume_token,
       m.high_volume_24h,
       m.high_change_6h,
       n.low_volume_token,
       n.low_volume_24h,
       n.low_change_6h
FROM max_vol m
JOIN min_vol n ON m.chain = n.chain
ORDER BY m.chain ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
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 )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )

[User] I want to see, for each game, the total number of sessions and the average cost of its in-game items.

[Assistant] SELECT gs.game_id, COUNT(*) AS session_count, AVG(igi.cost_amount) AS avg_item_cost FROM gaming_technology.game_sessions gs JOIN gaming_technology.in_game_items igi ON gs.game_id = igi.game_id GROUP BY gs.game_id;

[User] Actually, only include games that have at least 100 sessions.

[Assistant] SELECT gs.game_id, COUNT(*) AS session_count, AVG(igi.cost_amount) AS avg_item_cost FROM gaming_technology.game_sessions gs JOIN gaming_technology.in_game_items igi ON gs.game_id = igi.game_id GROUP BY gs.game_id HAVING COUNT(*) >= 100;

[User] Also, include the number of distinct items available for each game.

[Assistant] SELECT gs.game_id, COUNT(*) AS session_count, AVG(igi.cost_amount) AS avg_item_cost, COUNT(DISTINCT igi.item_id) AS distinct_item_count FROM gaming_technology.game_sessions gs JOIN gaming_technology.in_game_items igi ON gs.game_id = igi.game_id GROUP BY gs.game_id HAVING COUNT(*) >= 100;

[User] Show all in-game items (name, rarity) that belong to games where the average session score across all sessions for that game is greater than 300.

[Assistant] SELECT ii.item_name, ii.rarity FROM gaming_technology.in_game_items AS ii WHERE ii.game_id IN (SELECT game_id FROM gaming_technology.game_sessions GROUP BY game_id HAVING AVG(score) > 300);

[User] Additionally, include the total number of sessions for each of these items' games.

[Assistant] SELECT ii.item_name, ii.rarity, gs.total_sessions FROM gaming_technology.in_game_items AS ii JOIN (SELECT game_id, COUNT(*) AS total_sessions, AVG(score) AS avg_score FROM gaming_technology.game_sessions GROUP BY game_id) AS gs ON ii.game_id = gs.game_id WHERE gs.avg_score > 300;

[User] List the names of servers and their regions, and the names of achievements available in the games hosted on those servers.

[Assistant] SELECT s.server_name, s.region, a.name AS achievement_name FROM gaming_technology.servers AS s JOIN gaming_technology.achievements AS a ON s.game_id = a.game_id;

[User] Could you list the top 5 highest average session scores for each game, showing the game title, developer name, and the average score?

[Assistant]
SELECT g.title AS game_title,
       d.name AS developer_name,
       AVG(gs.score) AS average_score
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.games g ON gs.game_id = g.game_id
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
GROUP BY g.title, d.name
ORDER BY average_score DESC
LIMIT 5;

[User] Actually, I'd like to focus only on games in the 'Action' and 'RPG' genres.

[Assistant]
SELECT g.title AS game_title,
       d.name AS developer_name,
       AVG(gs.score) AS average_score
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.games g ON gs.game_id = g.game_id
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
WHERE g.genre IN ('Action','RPG')
GROUP BY g.title, d.name
ORDER BY average_score DESC
LIMIT 5;

[User] Also, include the total number of sessions for each of those games.

[Assistant]
SELECT g.title AS game_title,
       d.name AS developer_name,
       AVG(gs.score) AS average_score,
       COUNT(gs.session_id) AS session_count
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.games g ON gs.game_id = g.game_id
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
WHERE g.genre IN ('Action','RPG')
GROUP BY g.title, d.name
ORDER BY average_score DESC
LIMIT 5;

[User] Finally, restrict the results to games released after January 1, 2020.

[Assistant]
SELECT g.title AS game_title,
       d.name AS developer_name,
       AVG(gs.score) AS average_score,
       COUNT(gs.session_id) AS session_count
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.games g ON gs.game_id = g.game_id
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
WHERE g.genre IN ('Action','RPG')
  AND g.release_date > '2020-01-01'
GROUP BY g.title, d.name
ORDER BY average_score DESC
LIMIT 5;

[User] Which achievements have the highest unlock counts? List the top 5 achievement names along with the number of distinct players who unlocked each.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.name
ORDER BY player_count DESC
LIMIT 5;

[User] Only exclude hidden achievements from the ranking.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
WHERE a.hidden = FALSE
GROUP BY a.name
ORDER BY player_count DESC
LIMIT 5;

[User] Now include only achievements unlocked by at least 50 players and order by player_count descending.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
WHERE a.hidden = FALSE
GROUP BY a.name
HAVING COUNT(DISTINCT pa.player_id) >= 50
ORDER BY player_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 insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )

[User] I want to retrieve the agent ID, first and last name, along with their manager's contact email and phone number.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.contact_email AS manager_email,
       m.contact_phone AS manager_phone
FROM insurance.agents a
LEFT JOIN insurance.agents m
  ON a.manager_id = m.agent_id;

[User] Please filter to only agents who have a non-null manager and whose hire_date is after '2022-06-30'.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.contact_email AS manager_email,
       m.contact_phone AS manager_phone
FROM insurance.agents a
INNER JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE a.hire_date > '2022-06-30';

[User] Additionally, sort the results by the agent's hire_date in ascending order.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.contact_email AS manager_email,
       m.contact_phone AS manager_phone
FROM insurance.agents a
INNER JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE a.hire_date > '2022-06-30'
ORDER BY a.hire_date ASC;

[User] Finally, limit the result to 10 rows.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.contact_email AS manager_email,
       m.contact_phone AS manager_phone
FROM insurance.agents a
INNER JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE a.hire_date > '2022-06-30'
ORDER BY a.hire_date ASC
LIMIT 10;

[User] Please list the agent ID, agent's name, and manager's email for all agents who have a commission_rate greater than 0.12.

[Assistant]
SELECT a.agent_id, a.first_name || ' ' || a.last_name AS agent_name, m.contact_email AS manager_email
FROM insurance.agents a
LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.commission_rate > 0.12;

[User] Filter these results to only include agents whose own status is 'active'.

[Assistant]
SELECT a.agent_id, a.first_name || ' ' || a.last_name AS agent_name, m.contact_email AS manager_email
FROM insurance.agents a
LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.commission_rate > 0.12 AND a.status = 'active';

[User] What is the average commission_rate for each agent status and only show statuses with an average commission_rate above 0.05?

[Assistant]
SELECT status,
       AVG(commission_rate) AS avg_commission_rate
FROM insurance.agents
GROUP BY status
HAVING AVG(commission_rate) > 0.05;

[User] Find all agents hired after '2021-01-01', including their first_name, last_name, hire_date, and their manager's full name.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
LEFT JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE a.hire_date > '2021-01-01';

[User] Actually, include only those whose manager is in the same license_state as the agent.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
JOIN insurance.agents m
  ON a.manager_id = m.agent_id
 AND a.license_state = m.license_state
WHERE a.hire_date > '2021-01-01';

[User] I need only those with commission_rate above 0.05 and status 'Active'.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       a.commission_rate,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
JOIN insurance.agents m
  ON a.manager_id = m.agent_id
 AND a.license_state = m.license_state
WHERE a.hire_date > '2021-01-01'
  AND a.commission_rate > 0.05
  AND a.status = 'Active';

[User] Sort the results by commission_rate descending and limit to the top 10.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       a.commission_rate,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
JOIN insurance.agents m
  ON a.manager_id = m.agent_id
 AND a.license_state = m.license_state
WHERE a.hire_date > '2021-01-01'
  AND a.commission_rate > 0.05
  AND a.status = 'Active'
ORDER BY a.commission_rate DESC
LIMIT 10;

[User] Find managers who have at least one agent reporting to them whose status is 'inactive'. List the manager's full name and the full name of the inactive agent.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, T1.first_name AS agent_first_name, T1.last_name AS agent_last_name FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id WHERE T1.status = 'inactive'

[User] Could you also include the inactive agent's termination date in the results?

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, T1.first_name AS agent_first_name, T1.last_name AS agent_last_name, T1.termination_date FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id WHERE T1.status = 'inactive'

[User] Filter the results to only include cases where the manager is currently 'active'.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, T1.first_name AS agent_first_name, T1.last_name AS agent_last_name, T1.termination_date FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id WHERE T1.status = 'inactive' AND T2.status = 'active'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.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 character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)
CREATE TABLE legal_services.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)
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] List all documents along with the document type and the case name they are associated with.

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

[User] Show only documents uploaded by lawyers whose specialization is 'Employment Law'.

[Assistant]
SELECT d.document_name, d.document_type, c.case_name
FROM legal_services.documents d
JOIN legal_services.cases c ON d.case_id = c.case_id
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
WHERE l.specialization = 'Employment Law';

[User] Also, include the lawyer's full name and order the results by upload_timestamp descending.

[Assistant]
SELECT d.document_name, d.document_type, c.case_name, l.first_name || ' ' || l.last_name AS lawyer_full_name
FROM legal_services.documents d
JOIN legal_services.cases c ON d.case_id = c.case_id
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
WHERE l.specialization = 'Employment Law'
ORDER BY d.upload_timestamp DESC;

[User] Exclude any documents where the document_type is null.

[Assistant]
SELECT d.document_name, d.document_type, c.case_name, l.first_name || ' ' || l.last_name AS lawyer_full_name
FROM legal_services.documents d
JOIN legal_services.cases c ON d.case_id = c.case_id
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
WHERE l.specialization = 'Employment Law' AND d.document_type IS NOT NULL
ORDER BY d.upload_timestamp DESC;

[User] Show me a list of all appointments with the subject and full name of the assigned lawyer.

[Assistant]
SELECT a.appointment_id, a.subject, l.first_name || ' ' || l.last_name AS lawyer_full_name
FROM legal_services.appointments a
JOIN legal_services.lawyers l ON a.lawyer_id = l.lawyer_id;

[User] Can you show me all invoices with their invoice number, total amount, due date, and the full name of the client associated with the invoice?

[Assistant]
SELECT i.invoice_number, i.total_amount, i.due_date, c.first_name || ' ' || c.last_name AS client_full_name
FROM legal_services.invoices i
JOIN legal_services.clients c ON i.client_id = c.client_id;

[User] I only want invoices where the due date is in the next 14 days. Could you update the query?

[Assistant]
SELECT i.invoice_number, i.total_amount, i.due_date, c.first_name || ' ' || c.last_name AS client_full_name
FROM legal_services.invoices i
JOIN legal_services.clients c ON i.client_id = c.client_id
WHERE i.due_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '14 days';

[User] Also, add the status column from invoices and order the results by due_date ascending.

[Assistant]
SELECT i.invoice_number, i.total_amount, i.due_date, i.status, c.first_name || ' ' || c.last_name AS client_full_name
FROM legal_services.invoices i
JOIN legal_services.clients c ON i.client_id = c.client_id
WHERE i.due_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '14 days'
ORDER BY i.due_date ASC;

[User] Which lawyers have handled cases in the 'Federal Court' jurisdiction? Return each lawyer's first and last name, the case number, and the court jurisdiction.

[Assistant]
SELECT l.first_name, l.last_name, c.case_number, c.court_jurisdiction
FROM legal_services.lawyers l
JOIN legal_services.cases c ON l.lawyer_id = c.lead_lawyer_id
WHERE c.court_jurisdiction = 'Federal Court';

[User] Retrieve all lawyers specializing in 'Corporate Law', including their first_name, last_name, email, and phone.

[Assistant]
SELECT first_name, last_name, email, phone
FROM legal_services.lawyers
WHERE specialization = 'Corporate Law';


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 character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)

[User] For each trip, show the trip ID, vehicle ID, driver ID, and both the actual starting and ending location IDs.

[Assistant] SELECT trip_id, vehicle_id, driver_id, origin_location_id, destination_location_id FROM transportation.trips;

[User] List all unique pairs of origin and destination location IDs that have been used in trips, and count how many trips have occurred for each pair.

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count FROM transportation.trips GROUP BY origin_location_id, destination_location_id;

[User] Find pairs of trip IDs where both trips departed on the same calendar day, shared the same origin and destination locations, but were distinct trips.

[Assistant]
SELECT
  t1.trip_id AS trip_id_1,
  t2.trip_id AS trip_id_2,
  t1.origin_location_id,
  t1.destination_location_id,
  DATE(t1.scheduled_departure) AS departure_date
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.origin_location_id = t2.origin_location_id
  AND t1.destination_location_id = t2.destination_location_id
  AND DATE(t1.scheduled_departure) = DATE(t2.scheduled_departure)
  AND t1.trip_id < t2.trip_id;

[User] From those pairs, filter the results to only include pairs where the actual departure times were within 2 hours of each other.

[Assistant]
SELECT
  t1.trip_id AS trip_id_1,
  t2.trip_id AS trip_id_2,
  t1.origin_location_id,
  t1.destination_location_id,
  DATE(t1.scheduled_departure) AS departure_date,
  t1.actual_departure AS actual_departure_1,
  t2.actual_departure AS actual_departure_2
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.origin_location_id = t2.origin_location_id
  AND t1.destination_location_id = t2.destination_location_id
  AND DATE(t1.scheduled_departure) = DATE(t2.scheduled_departure)
  AND t1.trip_id < t2.trip_id
WHERE
  t1.actual_departure IS NOT NULL
  AND t2.actual_departure IS NOT NULL
  AND ABS(EXTRACT(EPOCH FROM (t1.actual_departure - t2.actual_departure))) <= 7200;

[User] Show the average passenger_count for each trip status.

[Assistant]
SELECT status, AVG(passenger_count) AS avg_passengers
FROM transportation.trips
GROUP BY status;

[User] Only include statuses with at least 10 trips.

[Assistant]
SELECT status, AVG(passenger_count) AS avg_passengers
FROM transportation.trips
GROUP BY status
HAVING COUNT(*) >= 10;

[User] Retrieve trip_id and passenger full names for all trips where the passenger record was created before the scheduled departure.

[Assistant]
SELECT t.trip_id, p.first_name || ' ' || p.last_name AS passenger_name
FROM transportation.trips t
JOIN transportation.passengers p
  ON p.created_at < t.scheduled_departure;

[User] Filter the results to only include trips with passenger_count greater than 5.

[Assistant]
SELECT t.trip_id, t.passenger_count, p.first_name || ' ' || p.last_name AS passenger_name
FROM transportation.trips t
JOIN transportation.passengers p
  ON p.created_at < t.scheduled_departure
WHERE t.passenger_count > 5;

[User] Also sort the output by passenger_count descending and limit to the top 10 records.

[Assistant]
SELECT t.trip_id, t.passenger_count, p.first_name || ' ' || p.last_name AS passenger_name
FROM transportation.trips t
JOIN transportation.passengers p
  ON p.created_at < t.scheduled_departure
WHERE t.passenger_count > 5
ORDER BY t.passenger_count DESC
LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 )

[User] List all service orders with quantity greater than 3, showing the order ID, total price, and the staff member who placed the order.

[Assistant]
SELECT order_id, total_price, staff_id_ordered
FROM hospitality_technology.service_orders
WHERE quantity > 3;

[User] Please add the delivery timestamp, and only show orders that were actually delivered (delivery_timestamp is not null).

[Assistant]
SELECT order_id, total_price, staff_id_ordered, delivery_timestamp
FROM hospitality_technology.service_orders
WHERE quantity > 3
  AND delivery_timestamp IS NOT NULL;

[User] Now, show only those orders where the delivered staff is different from the ordered staff, and sort by delivery timestamp ascending.

[Assistant]
SELECT order_id, total_price, staff_id_ordered, staff_id_delivered, delivery_timestamp
FROM hospitality_technology.service_orders
WHERE quantity > 3
  AND delivery_timestamp IS NOT NULL
  AND staff_id_ordered <> staff_id_delivered
ORDER BY delivery_timestamp ASC;

[User] List each staff member who delivered orders, along with the number of orders they delivered.

[Assistant] SELECT staff_id_delivered, COUNT(order_id) AS delivered_orders FROM hospitality_technology.service_orders WHERE staff_id_delivered IS NOT NULL GROUP BY staff_id_delivered;

[User] Only show staff who delivered more than 10 orders.

[Assistant] SELECT staff_id_delivered, COUNT(order_id) AS delivered_orders FROM hospitality_technology.service_orders WHERE staff_id_delivered IS NOT NULL GROUP BY staff_id_delivered HAVING COUNT(order_id) > 10;

[User] Get the total_quantity and total_revenue (sum of total_price) for each staff member who placed orders (staff_id_ordered).

[Assistant]
SELECT staff_id_ordered,
       SUM(quantity) AS total_quantity,
       SUM(total_price) AS total_revenue
FROM hospitality_technology.service_orders
GROUP BY staff_id_ordered;

[User] Filter to staff who have delivered at least one order (staff_id_delivered is not null).

[Assistant]
SELECT staff_id_ordered,
       SUM(quantity) AS total_quantity,
       SUM(total_price) AS total_revenue
FROM hospitality_technology.service_orders
WHERE staff_id_delivered IS NOT NULL
GROUP BY staff_id_ordered;

[User] For these staff members, list each order along with the previous order they placed, including first_order_timestamp and second_order_timestamp, and the time difference in hours.

[Assistant]
SELECT t1.staff_id_ordered,
       t1.order_id AS first_order_id,
       t2.order_id AS second_order_id,
       t1.order_timestamp AS first_order_timestamp,
       t2.order_timestamp AS second_order_timestamp,
       EXTRACT(EPOCH FROM (t2.order_timestamp - t1.order_timestamp)) / 3600 AS hours_diff
FROM hospitality_technology.service_orders t1
JOIN hospitality_technology.service_orders t2
  ON t1.staff_id_ordered = t2.staff_id_ordered
 AND t2.order_timestamp > t1.order_timestamp
 AND NOT EXISTS (
       SELECT 1 FROM hospitality_technology.service_orders t3
       WHERE t3.staff_id_ordered = t1.staff_id_ordered
         AND t3.order_timestamp > t1.order_timestamp
         AND t3.order_timestamp < t2.order_timestamp
   )
WHERE t1.staff_id_delivered IS NOT NULL
  AND t2.staff_id_delivered IS NOT NULL
ORDER BY t1.staff_id_ordered, t1.order_timestamp;

[User] Show me the total quantity and total price for each service ordered by each guest.

[Assistant] SELECT guest_id, service_id, SUM(quantity) AS total_quantity, SUM(total_price) AS total_price FROM hospitality_technology.service_orders GROUP BY guest_id, service_id;

[User] List the total number of service orders placed by each staff member who delivered the service.

[Assistant] SELECT staff_id_delivered, COUNT(*) AS order_count FROM hospitality_technology.service_orders GROUP BY staff_id_delivered;

[User] Show only those staff members who have delivered at least 20 service orders and order the results by order_count descending.

[Assistant] SELECT staff_id_delivered, COUNT(*) AS order_count FROM hospitality_technology.service_orders GROUP BY staff_id_delivered HAVING COUNT(*) >= 20 ORDER BY order_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 legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )

[User] Show me the subjects and start times of all appointments for a specific client, along with the assigned lawyer ID.

[Assistant] SELECT subject, start_time, lawyer_id FROM legal_services.appointments WHERE client_id = 'CLIENT123';

[User] Could you narrow it down to only include appointments where the status is 'Rescheduled' or 'Postponed'?

[Assistant] SELECT subject, start_time, lawyer_id FROM legal_services.appointments WHERE client_id = 'CLIENT123' AND status IN ('Rescheduled', 'Postponed');

[User] Also, please make sure the appointments were created after June 1st, 2024 and order the results by start_time ascending.

[Assistant] SELECT subject, start_time, lawyer_id FROM legal_services.appointments WHERE client_id = 'CLIENT123' AND status IN ('Rescheduled', 'Postponed') AND created_at > '2024-06-01' ORDER BY start_time ASC;

[User] I want to find all appointment pairs where two appointments are scheduled for the same client at overlapping times. Provide the appointment_id from both overlapping appointments.

[Assistant]
SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2
FROM legal_services.appointments a1
JOIN legal_services.appointments a2
  ON a1.client_id = a2.client_id
 AND a1.appointment_id < a2.appointment_id
 AND a1.start_time < a2.end_time
 AND a2.start_time < a1.end_time;

[User] Actually, only include pairs where both appointments have status 'scheduled'.

[Assistant]
SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2
FROM legal_services.appointments a1
JOIN legal_services.appointments a2
  ON a1.client_id = a2.client_id
 AND a1.appointment_id < a2.appointment_id
 AND a1.start_time < a2.end_time
 AND a2.start_time < a1.end_time
WHERE a1.status = 'scheduled'
  AND a2.status = 'scheduled';

[User] And ensure the overlapping appointments start within 1 hour of each other.

[Assistant]
SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2
FROM legal_services.appointments a1
JOIN legal_services.appointments a2
  ON a1.client_id = a2.client_id
 AND a1.appointment_id < a2.appointment_id
 AND a1.start_time < a2.end_time
 AND a2.start_time < a1.end_time
 AND ABS(EXTRACT(EPOCH FROM (a1.start_time - a2.start_time))) <= 3600
WHERE a1.status = 'scheduled'
  AND a2.status = 'scheduled';

[User] List each appointment along with the start_time of the next appointment for the same lawyer. Include appointment_id and next_start_time.

[Assistant]
SELECT appointment_id,
       LEAD(start_time) OVER (PARTITION BY lawyer_id ORDER BY start_time) AS next_start_time
FROM legal_services.appointments;

[User] Only include those where next_start_time is within 30 days of the original appointment.

[Assistant]
WITH ordered AS (
  SELECT appointment_id,
         start_time,
         LEAD(start_time) OVER (PARTITION BY lawyer_id ORDER BY start_time) AS next_start_time
  FROM legal_services.appointments
)
SELECT appointment_id, next_start_time
FROM ordered
WHERE next_start_time IS NOT NULL
  AND next_start_time <= start_time + INTERVAL '30 days';

[User] List all appointments for the client with ID 'client_001' showing the lawyer's ID, appointment subject, and start time.

[Assistant]
SELECT a.lawyer_id, a.subject, a.start_time
FROM legal_services.appointments a
WHERE a.client_id = 'client_001';

[User] Actually, please also include the case ID in the results.

[Assistant]
SELECT a.lawyer_id, a.subject, a.start_time, a.case_id
FROM legal_services.appointments a
WHERE a.client_id = 'client_001';

[User] Now, sort the results by start time from newest to oldest.

[Assistant]
SELECT a.lawyer_id, a.subject, a.start_time, a.case_id
FROM legal_services.appointments a
WHERE a.client_id = 'client_001'
ORDER BY a.start_time DESC;

[User] How many appointments have been scheduled on weekends?

[Assistant]
SELECT COUNT(*) AS weekend_appointments
FROM legal_services.appointments
WHERE EXTRACT(DOW FROM start_time) IN (0,6);


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.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)

[User] For each trip, provide the trip_id, the total fuel quantity refueled, and the number of refueling events that occurred during the trip.

[Assistant]
SELECT trip_id, SUM(quantity) AS total_fuel_quantity, COUNT(*) AS refuel_event_count
FROM transportation.fuel_logs
WHERE trip_id IS NOT NULL
GROUP BY trip_id;

[User] For each fuel type, list the number of unique locations where fuel refueling occurred, and also show the total quantity refueled for that fuel type and location.

[Assistant]
SELECT fuel_type, location_id, COUNT(DISTINCT location_id) AS unique_location_count, SUM(quantity) AS total_quantity
FROM transportation.fuel_logs
GROUP BY fuel_type, location_id;

[User] Show all fuel logs for vehicle_id 'VH123', including the timestamp, fuel type, quantity, and the location_id. Sort the list by timestamp descending.

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
ORDER BY log_timestamp DESC;

[User] Can you also include the odometer reading and total cost for each fuel log in the result?

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id, odometer_reading, total_cost
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
ORDER BY log_timestamp DESC;

[User] I only want to see records where the total_cost is above 100.

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id, odometer_reading, total_cost
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
  AND total_cost > 100
ORDER BY log_timestamp DESC;

[User] Actually, please limit the results to just the 5 most recent logs.

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id, odometer_reading, total_cost
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
  AND total_cost > 100
ORDER BY log_timestamp DESC
LIMIT 5;

[User] I need the total fuel cost per vehicle for each fuel type.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
GROUP BY vehicle_id, fuel_type;

[User] Filter this to only include records where the cost_per_unit is greater than 1.50.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
WHERE cost_per_unit > 1.50
GROUP BY vehicle_id, fuel_type;

[User] Also, sort the result by the total cost in descending order.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
WHERE cost_per_unit > 1.50
GROUP BY vehicle_id, fuel_type
ORDER BY total_cost_per_type DESC;

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

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
WHERE cost_per_unit > 1.50
GROUP BY vehicle_id, fuel_type
ORDER BY total_cost_per_type DESC
LIMIT 5;

[User] For each vehicle, show the first and last fueling events including their timestamps and the quantities refueled.

[Assistant]
WITH first_last AS (
  SELECT
    vehicle_id,
    MIN(log_timestamp) AS first_time,
    MAX(log_timestamp) AS last_time
  FROM transportation.fuel_logs
  GROUP BY vehicle_id
)
SELECT
  f1.vehicle_id,
  f1.log_timestamp AS first_refuel_time,
  f1.quantity AS first_quantity,
  f2.log_timestamp AS last_refuel_time,
  f2.quantity AS last_quantity
FROM first_last fl
JOIN transportation.fuel_logs f1
  ON fl.vehicle_id = f1.vehicle_id
  AND fl.first_time = f1.log_timestamp
JOIN transportation.fuel_logs f2
  ON fl.vehicle_id = f2.vehicle_id
  AND fl.last_time = f2.log_timestamp;


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.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )

[User] List all active insurance products, including their product name, type, and base premium.

[Assistant] SELECT product_name, product_type, base_premium FROM insurance.insurance_products WHERE is_active = TRUE;

[User] Show me all claim documents that are PDFs and were uploaded in the last 30 days, along with their claim IDs and file sizes.

[Assistant] SELECT cd.document_id, cd.claim_id, cd.file_size_bytes, c.policy_id FROM insurance.claim_documents cd JOIN insurance.claims c ON cd.claim_id = c.claim_id WHERE cd.mime_type = 'application/pdf' AND cd.uploaded_at >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY);

[User] I also want to see the policy details for these claims, including the coverage limit and premium amount.

[Assistant] SELECT cd.document_id, cd.claim_id, cd.file_size_bytes, c.policy_id, p.coverage_limit, p.premium_amount FROM insurance.claim_documents cd JOIN insurance.claims c ON cd.claim_id = c.claim_id JOIN insurance.policies p ON c.policy_id = p.policy_id WHERE cd.mime_type = 'application/pdf' AND cd.uploaded_at >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY);

[User] Now filter to only show documents larger than 1MB and include the upload date.

[Assistant] SELECT cd.document_id, cd.claim_id, cd.file_size_bytes, cd.uploaded_at, c.policy_id, p.coverage_limit, p.premium_amount FROM insurance.claim_documents cd JOIN insurance.claims c ON cd.claim_id = c.claim_id JOIN insurance.policies p ON c.policy_id = p.policy_id WHERE cd.mime_type = 'application/pdf' AND cd.uploaded_at >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) AND cd.file_size_bytes > 1000000;

[User] Finally, show me the count of such PDF documents per policy, ordered by count descending.

[Assistant] SELECT c.policy_id, COUNT(cd.document_id) AS pdf_count FROM insurance.claim_documents cd JOIN insurance.claims c ON cd.claim_id = c.claim_id WHERE cd.mime_type = 'application/pdf' AND cd.uploaded_at >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) AND cd.file_size_bytes > 1000000 GROUP BY c.policy_id ORDER BY pdf_count DESC;

[User] List all claims that have at least one document of type 'INVOICE', including the claim ID, incident date, estimated loss, and the document's file name.

[Assistant]
SELECT c.claim_id, c.incident_date, c.estimated_loss, d.file_name
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.document_type = 'INVOICE';

[User] Also show the file size in bytes and the uploaded date for each document.

[Assistant]
SELECT c.claim_id, c.incident_date, c.estimated_loss, d.file_name, d.file_size_bytes, d.uploaded_at
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.document_type = 'INVOICE';

[User] Actually, just show the claims where the document file size is greater than 100,000 bytes.

[Assistant]
SELECT c.claim_id, c.incident_date, c.estimated_loss, d.file_name, d.file_size_bytes, d.uploaded_at
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.document_type = 'INVOICE'
  AND d.file_size_bytes > 100000;

[User] Find all documents that are larger than 5MB. Show the document ID, claim ID, file name, and file size in bytes.

[Assistant]
SELECT document_id, claim_id, file_name, file_size_bytes
FROM insurance.claim_documents
WHERE file_size_bytes > 5242880;

[User] For each claim, count the number of documents linked to it. Show claim_id and document_count for claims that have more than 3 documents.

[Assistant]
SELECT claim_id, COUNT(*) AS document_count
FROM insurance.claim_documents
group by claim_id
HAVING COUNT(*) > 3;

[User] Please also show the incident date for those claims.

[Assistant]
SELECT c.claim_id, c.incident_date, COUNT(d.document_id) AS document_count
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
GROUP BY c.claim_id, c.incident_date
HAVING COUNT(d.document_id) > 3;