conversations
listlengths 2
8
| system
stringlengths 276
8.23k
|
|---|---|
[
{
"role": "user",
"content": "Show me all cryptocurrency assets that have been traded more than 50 times but have never been traded in quantities greater than 100, along with their average trade price."
},
{
"role": "assistant",
"content": "SELECT a.asset_id, a.name, a.symbol, COUNT(t.trade_id) AS trade_count, AVG(t.price) AS avg_price FROM trading_platform.assets a JOIN trading_platform.trades t ON a.asset_id = t.asset_id WHERE a.type = 'cryptocurrency' GROUP BY a.asset_id, a.name, a.symbol HAVING COUNT(t.trade_id) > 50 AND MAX(t.quantity) <= 100;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
CREATE TABLE trading_platform.utxos ( utxo_id character varying(64) NOT NULL, transaction_id character varying(64) NOT NULL, output_index integer NOT NULL, address character varying(128) NOT NULL, amount numeric(38,14) NOT NULL, spent boolean NOT NULL, PRIMARY KEY (utxo_id) )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_id) )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, status character varying(32) NOT NULL, reviewed_at timestamp NOT NULL, PRIMARY KEY (kyc_audit_id) )
CREATE TABLE trading_platform.notifications ( notification_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, message text NOT NULL, sent_at timestamp NOT NULL, read_at timestamp, PRIMARY KEY (notification_id) )
|
[
{
"role": "user",
"content": "Show me the top 5 ERC20 tokens with the highest total supply, along with their names and contract addresses, but only include tokens where the price is greater than $0.10."
},
{
"role": "assistant",
"content": "SELECT tm.name, tm.contract_address, tm.total_supply FROM token_metas tm WHERE tm.is_erc20 = 1 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;"
},
{
"role": "user",
"content": "I think there's a typo in your query - it should be 'total_supply' not 'total_supply'. Also, can you join this with the token_prices_latest table to include the current price of each token?"
},
{
"role": "assistant",
"content": "SELECT tm.name, tm.contract_address, tm.total_supply, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price > 0.10 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;"
},
{
"role": "user",
"content": "The token_prices_latest table isn't in the schema. Can you modify the query to use the erc20_balances table instead to show the total balance held across all wallets for each token?"
},
{
"role": "assistant",
"content": "SELECT tm.name, tm.contract_address, tm.total_supply, SUM(CAST(eb.amount AS decimal)) AS total_balance FROM token_metas tm JOIN erc20_balances eb ON tm.contract_address = eb.contract_address WHERE tm.is_erc20 = 1 GROUP BY tm.name, tm.contract_address, tm.total_supply ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas (
block_timestamp timestamp(6) NOT NULL, -- Timestamp of the block when token metadata was recorded
block_number bigint NOT NULL, -- Block number uniquely identifying the block
transaction_hash varchar NOT NULL, -- Hash value of the transaction
transaction_index bigint NOT NULL, -- Index of the transaction within the block
from_address varchar NOT NULL, -- Address from which the transaction originated
contract_address varchar NOT NULL, -- Address of the token contract
symbol varchar NOT NULL, -- Symbol of the token
total_supply varchar NOT NULL, -- erc20 contract total supply
name varchar NOT NULL, -- Name of the token
decimals bigint NOT NULL, -- Number of decimal places for the token
is_erc20 integer NOT NULL, -- Flag indicating if the token is an ERC-20 token (0 or 1)
is_erc721 integer NOT NULL, -- Flag indicating if the token is an ERC-721 token (0 or 1)
is_erc1155 integer NOT NULL, -- Flag indicating if the token is an ERC-1155 token (0 or 1)
is_proxy integer NOT NULL, -- Flag indicating if the token is a proxy (0 or 1)
extra_info varchar NOT NULL, -- Additional information about the token
pk integer NOT NULL -- Partition key for the table(floor(block_number / 5760))
)
CREATE TABLE erc1155_approval_for_all (
block_number bigint NOT NULL, -- Block number containing the transaction
block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
transaction_index integer NOT NULL, -- Index of the transaction within the block
transaction_hash varchar(66) NOT NULL, -- Transaction hash
log_index integer NOT NULL, -- Log index
contract_address varchar(42) NOT NULL -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders (
block_number bigint NOT NULL, -- Block number containing the transaction
contract_address varchar NOT NULL, -- Event contract address
wallet_address varchar NOT NULL, -- The wallet address for the contract(with bloom filter)
token_id varchar NOT NULL, -- NFT token id
contract_type varchar NOT NULL, -- NFT contract type
amount varchar NOT NULL, -- Number of held NFTs
pk varchar NOT NULL -- The last string partition of the contract.
)
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_info (
block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
tick varchar NOT NULL, -- Token tick
max_supply decimal(38,0) NOT NULL, -- Max supply
lim decimal(38,0) NOT NULL, -- Limit of each mint
wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
dec integer NOT NULL, -- Decimal for minimum divie
creator varchar(42) NOT NULL -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_activities (
block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
log_index integer NOT NULL, -- Index of the log within the transaction
type varchar NOT NULL, -- mint | transfer | burn
tick varchar NOT NULL, -- Token tick
id varchar(255) NOT NULL, -- Unique identifier of the inscription
amt decimal(38,0) NOT NULL, -- Mint amount
from_address varchar(42) NOT NULL, -- Address sending the inscription (matches from_address in transactions table)
to_address varchar(42) NOT NULL -- Address receiving the inscription (match to_address in transactions table)
)
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
|
[
{
"role": "user",
"content": "List all claim IDs that have both an 'Accident Report' and a 'Damage Assessment' document, and show the earliest upload timestamp for each type."
},
{
"role": "assistant",
"content": "SELECT a.claim_id,\n MIN(a.uploaded_at) AS accident_report_date,\n MIN(d.uploaded_at) AS damage_assessment_date\nFROM insurance.claim_documents AS a\nJOIN insurance.claim_documents AS d\n ON a.claim_id = d.claim_id\nWHERE a.document_type = 'Accident Report'\n AND d.document_type = 'Damage Assessment'\nGROUP BY a.claim_id;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
|
[
{
"role": "user",
"content": "How many trips are there for each driver?"
},
{
"role": "assistant",
"content": "SELECT driver_id, COUNT(*) AS trip_count FROM transportation.trips GROUP BY driver_id;"
},
{
"role": "user",
"content": "Can you also show the total number of completed trips for each driver?"
},
{
"role": "assistant",
"content": "SELECT driver_id, COUNT(*) AS completed_trip_count FROM transportation.trips WHERE status = 'Completed' GROUP BY driver_id;"
},
{
"role": "user",
"content": "Now, include both the total trips and completed trips for each driver in the same result."
},
{
"role": "assistant",
"content": "SELECT driver_id, COUNT(*) AS total_trips, SUM(CASE WHEN status = 'Completed' THEN 1 ELSE 0 END) AS completed_trips FROM transportation.trips GROUP BY driver_id;"
},
{
"role": "user",
"content": "Sort the output by the number of completed trips in descending order."
},
{
"role": "assistant",
"content": "SELECT driver_id, COUNT(*) AS total_trips, SUM(CASE WHEN status = 'Completed' THEN 1 ELSE 0 END) AS completed_trips FROM transportation.trips GROUP BY driver_id ORDER BY completed_trips DESC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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)
)
|
[
{
"role": "user",
"content": "List all customers who have policies that expired in the last 30 days."
},
{
"role": "assistant",
"content": "SELECT DISTINCT c.customer_id, c.first_name, c.last_name, c.email FROM insurance.customers c JOIN insurance.policies p ON c.customer_id = p.customer_id WHERE p.end_date BETWEEN CURRENT_DATE - INTERVAL '30 days' AND CURRENT_DATE AND p.status = 'Expired';"
},
{
"role": "user",
"content": "Now show me only those customers who haven't renewed their policies yet (no new active policies with the same product)."
},
{
"role": "assistant",
"content": "SELECT DISTINCT c.customer_id, c.first_name, c.last_name, c.email FROM insurance.customers c JOIN insurance.policies expired_p ON c.customer_id = expired_p.customer_id LEFT JOIN insurance.policies active_p ON c.customer_id = active_p.customer_id AND expired_p.product_id = active_p.product_id AND active_p.status = 'Active' WHERE expired_p.end_date BETWEEN CURRENT_DATE - INTERVAL '30 days' AND CURRENT_DATE AND expired_p.status = 'Expired' AND active_p.policy_id IS NULL;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers (
customer_id character varying(64) NOT NULL, -- unique identifier for the customer
first_name character varying(100) NOT NULL, -- customer's first name
last_name character varying(100) NOT NULL, -- customer's last name
date_of_birth date NOT NULL, -- customer's date of birth
ssn_hash character varying(128), -- Hashed social security number (or national ID)
address_line1 character varying(255) NOT NULL,
address_line2 character varying(255),
city character varying(100) NOT NULL,
state character varying(50) NOT NULL,
zip_code character varying(20) NOT NULL,
country character varying(50) NOT NULL DEFAULT 'USA',
phone_number character varying(30),
email character varying(128) UNIQUE, -- unique email address
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
updated_at timestamp, -- when the customer record was last updated
status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
PRIMARY KEY (customer_id)
)
CREATE TABLE insurance.policies (
policy_id character varying(64) NOT NULL, -- unique identifier for the policy
customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
start_date date NOT NULL, -- date the policy coverage begins
end_date date NOT NULL, -- date the policy coverage ends
premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
cancellation_date date,
cancellation_reason text,
PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.claims (
claim_id character varying(64) NOT NULL, -- unique identifier for the claim
policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
description text NOT NULL, -- detailed description of the incident and claim
estimated_loss numeric(15, 2), -- initial estimated cost of the loss
status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
settlement_amount numeric(15, 2), -- final amount paid out
settlement_date date,
claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
police_report_number character varying(100),
PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.premium_payments (
payment_id character varying(64) NOT NULL, -- unique identifier for the payment
policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
transaction_reference character varying(128) UNIQUE, -- reference from payment processor
due_date date, -- due date for this payment installment
payment_period_start date, -- start date of the period this payment covers
payment_period_end date, -- end date of the period this payment covers
status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
PRIMARY KEY (payment_id)
)
CREATE TABLE insurance.claim_documents (
document_id character varying(64) NOT NULL, -- unique identifier for the document
claim_id character varying(64) NOT NULL, -- identifier of the claim this document relates to (FK to claims)
document_type character varying(50) NOT NULL, -- e.g., Police Report, Photo, Invoice, Medical Bill
file_name character varying(255) NOT NULL, -- original name of the uploaded file
file_path character varying(512) NOT NULL, -- storage path (e.g., S3 URL, network path)
file_size_bytes integer, -- size of the file in bytes
mime_type character varying(100), -- MIME type of the file (e.g., 'image/jpeg', 'application/pdf')
uploaded_by character varying(64), -- identifier of the user/system who uploaded (FK to users/customers)
uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- time of upload
description text, -- optional description of the document
PRIMARY KEY (document_id)
)
|
[
{
"role": "user",
"content": "Find appointments that are longer than 30 minutes."
},
{
"role": "assistant",
"content": "SELECT * FROM legal_services.appointments WHERE end_time IS NOT NULL AND start_time IS NOT NULL AND end_time > start_time + INTERVAL '30 minutes'"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )
|
[
{
"role": "user",
"content": "Which five customers have the highest cumulative estimated_loss from approved or settled claims? Provide customer_id and total_estimated_loss."
},
{
"role": "assistant",
"content": "SELECT customer_id,\n SUM(estimated_loss) AS total_estimated_loss\nFROM insurance.claims\nWHERE status IN ('Approved', 'Settled')\nGROUP BY customer_id\nORDER BY total_estimated_loss DESC\nLIMIT 5;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims (
claim_id character varying(64) NOT NULL, -- unique identifier for the claim
policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
description text NOT NULL, -- detailed description of the incident and claim
estimated_loss numeric(15, 2), -- initial estimated cost of the loss
status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
settlement_amount numeric(15, 2), -- final amount paid out
settlement_date date,
claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
police_report_number character varying(100),
PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
|
[
{
"role": "user",
"content": "What is the average processing time in days for each service category?"
},
{
"role": "assistant",
"content": "SELECT category, AVG(average_processing_time_days) AS avg_processing_time\nFROM government_services.services\nGROUP BY category;"
},
{
"role": "user",
"content": "Only include categories where the average_processing_time_days is greater than 5."
},
{
"role": "assistant",
"content": "SELECT category, AVG(average_processing_time_days) AS avg_processing_time\nFROM government_services.services\nGROUP BY category\nHAVING AVG(average_processing_time_days) > 5;"
},
{
"role": "user",
"content": "Also include only active services in the calculation."
},
{
"role": "assistant",
"content": "SELECT category, AVG(average_processing_time_days) AS avg_processing_time\nFROM government_services.services\nWHERE is_active = TRUE\nGROUP BY category\nHAVING AVG(average_processing_time_days) > 5;"
},
{
"role": "user",
"content": "Sort the results by avg_processing_time in descending order."
},
{
"role": "assistant",
"content": "SELECT category, AVG(average_processing_time_days) AS avg_processing_time\nFROM government_services.services\nWHERE is_active = TRUE\nGROUP BY category\nHAVING AVG(average_processing_time_days) > 5\nORDER BY avg_processing_time DESC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
|
[
{
"role": "user",
"content": "I need to identify customers who have two different policies that have overlapping coverage periods. List the customer_id along with the two policy_ids."
},
{
"role": "assistant",
"content": "SELECT p1.customer_id,\n p1.policy_id AS policy1_id,\n p2.policy_id AS policy2_id\nFROM insurance.policies p1\nJOIN insurance.policies p2\n ON p1.customer_id = p2.customer_id\n AND p1.policy_id < p2.policy_id\n AND p1.start_date <= p2.end_date\n AND p2.start_date <= p1.end_date;"
},
{
"role": "user",
"content": "Actually, restrict this to only policies where status = 'active'."
},
{
"role": "assistant",
"content": "SELECT p1.customer_id,\n p1.policy_id AS policy1_id,\n p2.policy_id AS policy2_id\nFROM insurance.policies p1\nJOIN insurance.policies p2\n ON p1.customer_id = p2.customer_id\n AND p1.policy_id < p2.policy_id\n AND p1.start_date <= p2.end_date\n AND p2.start_date <= p1.end_date\nWHERE p1.status = 'active'\n AND p2.status = 'active';"
},
{
"role": "user",
"content": "Also include the overlapping period dates labeled as overlap_start and overlap_end."
},
{
"role": "assistant",
"content": "SELECT p1.customer_id,\n p1.policy_id AS policy1_id,\n p2.policy_id AS policy2_id,\n GREATEST(p1.start_date, p2.start_date) AS overlap_start,\n LEAST(p1.end_date, p2.end_date) AS overlap_end\nFROM insurance.policies p1\nJOIN insurance.policies p2\n ON p1.customer_id = p2.customer_id\n AND p1.policy_id < p2.policy_id\n AND p1.start_date <= p2.end_date\n AND p2.start_date <= p1.end_date\nWHERE p1.status = 'active'\n AND p2.status = 'active';"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
|
[
{
"role": "user",
"content": "Show me all events emitted by contracts where the event name contains 'Approval', along with the contract ID and transaction ID, sorted by emitted timestamp in descending order."
},
{
"role": "assistant",
"content": "SELECT event_id, contract_id, event_name, transaction_id, emitted_at FROM web3.events WHERE event_name LIKE '%Approval%' ORDER BY emitted_at DESC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.events (
event_id character varying(64) NOT NULL, -- unique identifier for the event
contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
event_name character varying(128) NOT NULL, -- name of the event
data text NOT NULL, -- data payload of the event
emitted_at timestamp NOT NULL, -- time when the event was emitted
transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
log_index integer NOT NULL, -- index of the event log in the transaction
PRIMARY KEY (event_id)
)
|
[
{
"role": "user",
"content": "Find all pairs of different insurance records that share the same group_number, and show group_number, the patient_insurance_id of both records, and their corresponding patient_ids."
},
{
"role": "assistant",
"content": "SELECT a.group_number,\n a.patient_insurance_id AS pi_id1,\n a.patient_id AS patient1_id,\n b.patient_insurance_id AS pi_id2,\n b.patient_id AS patient2_id\nFROM healthcare.patient_insurance a\nJOIN healthcare.patient_insurance b\n ON a.group_number = b.group_number\n AND a.patient_insurance_id < b.patient_insurance_id\nWHERE a.group_number IS NOT NULL;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
|
[
{
"role": "user",
"content": "I need to find passengers who have a specific phone number prefix '+1555'. Can you help with that?"
},
{
"role": "assistant",
"content": "db.passengers.find({ phone_number: { $regex: '^\\+1555' } }, { first_name: 1, last_name: 1, phone_number: 1, email: 1, _id: 0 })"
},
{
"role": "user",
"content": "Can you also filter these results to include only passengers born before 1995?"
},
{
"role": "assistant",
"content": "db.passengers.find({ phone_number: { $regex: '^\\+1555' }, date_of_birth: { $lt: ISODate('1995-01-01T00:00:00Z') } }, { first_name: 1, last_name: 1, phone_number: 1, email: 1, _id: 0 })"
},
{
"role": "user",
"content": "Can you limit the results to the first 5 passengers?"
},
{
"role": "assistant",
"content": "db.passengers.find({ phone_number: { $regex: '^\\+1555' }, date_of_birth: { $lt: ISODate('1995-01-01T00:00:00Z') } }, { first_name: 1, last_name: 1, phone_number: 1, email: 1, _id: 0 }).limit(5)"
}
] |
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
// db.createCollection('passengers')
// Optional: db.passengers.createIndex({ passenger_id: 1 }, { unique: true })
// Optional: db.passengers.createIndex({ email: 1 }, { unique: true, sparse: true })
// Optional: db.passengers.createIndex({ phone_number: 1 }, { unique: true, sparse: true })
{
_id: ObjectId(),
passenger_id: "pass_pqr", // String (unique)
first_name: "Alice", // String
last_name: "Smith", // String
email: "alice.smith@example.com", // String (unique, sparse)
phone_number: "+15551234567", // String (unique, sparse)
date_of_birth: ISODate("1990-03-20"), // Date
loyalty_program_id: "LOYALTY123", // String
created_at: ISODate("2023-02-01T11:00:00Z") // Date
}
|
[
{
"role": "user",
"content": "For each claim, show the corresponding product_type of the insurance product for the related policy."
},
{
"role": "assistant",
"content": "SELECT cl.claim_id, ip.product_type\nFROM insurance.claims cl\nJOIN insurance.policies p ON cl.policy_id = p.policy_id\nJOIN insurance.insurance_products ip ON p.product_id = ip.product_id;"
},
{
"role": "user",
"content": "Sorry, there is no policies table, I got an error. Can you try joining claims to insurance_products another way?"
},
{
"role": "assistant",
"content": "-- Unable to join directly since there is no 'policies' table connecting claims to insurance_products. If policy_id equals product_id, you may try:\nSELECT claim_id, policy_id, product_type\nFROM insurance.claims\nJOIN insurance.insurance_products ON claims.policy_id = insurance_products.product_id;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.claims ( claim_id.text, 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, 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, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
|
[
{
"role": "user",
"content": "What are the personal contact details of the staff member associated with staff_id 'STAFF789' who worked on a specific maintenance record?"
},
{
"role": "assistant",
"content": "I'm sorry, but I can't provide personal contact details of staff members as this information is not stored in the maintenance_records table and is outside the scope of the available data."
}
] |
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id text, asset_id text, asset_type text, maintenance_type text, staff_id text, start_datetime timestamp, end_datetime timestamp, description text, cost numeric, status text )
|
[
{
"role": "user",
"content": "Retrieve each agent's ID, full name, and the count of 'Pending' policies they have sold with a premium_amount greater than 2000. Order the results by the policy count descending."
},
{
"role": "assistant",
"content": "SELECT a.agent_id,\n a.first_name || ' ' || a.last_name AS agent_name,\n COUNT(p.policy_id) AS pending_policy_count\nFROM insurance.agents a\nJOIN insurance.policies p ON a.agent_id = p.agent_id\nWHERE p.status = 'Pending'\n AND p.premium_amount > 2000\nGROUP BY a.agent_id, agent_name\nORDER BY pending_policy_count DESC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims (
claim_id character varying(64) NOT NULL, -- unique identifier for the claim
policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
description text NOT NULL, -- detailed description of the incident and claim
estimated_loss numeric(15, 2), -- initial estimated cost of the loss
status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
settlement_amount numeric(15, 2), -- final amount paid out
settlement_date date,
claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
police_report_number character varying(100),
PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
|
[
{
"role": "user",
"content": "What is the fuel efficiency of the train car with car_id 'TC456'?"
},
{
"role": "assistant",
"content": "I'm sorry, but I don't have access to information about the fuel efficiency of specific train cars. The data available in the train_cars table only includes details such as car_id, train_id, car_number, car_type, class, capacity, and features. If you have another question or need assistance with something else, I'm happy to help."
}
] |
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.train_cars ( car_id.text, train_id.text, car_number.text, car_type.text, class.text, capacity.integer, features.text )
|
[
{
"role": "user",
"content": "Show all insurance plans where the plan name includes the word 'Care'."
},
{
"role": "assistant",
"content": "SELECT plan_id, plan_name, insurance_provider, plan_type\nFROM healthcare.insurance_plans\nWHERE plan_name ILIKE '%Care%';"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
|
[
{
"role": "user",
"content": "Get the number of direct reports for each manager, showing manager_id and report_count."
},
{
"role": "assistant",
"content": "SELECT manager_id,\n COUNT(*) AS report_count\nFROM hospitality_technology.staff\nWHERE manager_id IS NOT NULL\nGROUP BY manager_id;"
},
{
"role": "user",
"content": "Exclude managers who have fewer than 2 direct reports."
},
{
"role": "assistant",
"content": "SELECT manager_id,\n COUNT(*) AS report_count\nFROM hospitality_technology.staff\nWHERE manager_id IS NOT NULL\nGROUP BY manager_id\nHAVING COUNT(*) >= 2;"
},
{
"role": "user",
"content": "Also include the manager's full name alongside their ID."
},
{
"role": "assistant",
"content": "SELECT m.staff_id AS manager_id,\n m.first_name || ' ' || m.last_name AS manager_full_name,\n COUNT(s.staff_id) AS report_count\nFROM hospitality_technology.staff s\nJOIN hospitality_technology.staff m\n ON s.manager_id = m.staff_id\nGROUP BY m.staff_id, m.first_name, m.last_name\nHAVING COUNT(s.staff_id) >= 2;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, position character varying(100) NOT NULL, work_email character varying(255) UNIQUE, work_phone character varying(30), hire_date date NOT NULL, termination_date date, is_active boolean NOT NULL DEFAULT true, access_level integer NOT NULL, manager_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (staff_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id) )
|
[
{
"role": "user",
"content": "Get each staff member who delivered service orders in the last month and the count of orders they delivered."
},
{
"role": "assistant",
"content": "SELECT s.staff_id,\n s.first_name,\n s.last_name,\n COUNT(so.order_id) AS delivered_orders\nFROM hospitality_technology.service_orders so\nJOIN hospitality_technology.staff s ON so.staff_id_delivered = s.staff_id\nWHERE so.delivery_timestamp >= date_trunc('month', current_date) - INTERVAL '1 month'\n AND so.delivery_timestamp < date_trunc('month', current_date)\nGROUP BY s.staff_id, s.first_name, s.last_name;"
},
{
"role": "user",
"content": "Actually, only include staff who delivered more than 5 orders and order the result by delivered_orders descending."
},
{
"role": "assistant",
"content": "SELECT s.staff_id,\n s.first_name,\n s.last_name,\n COUNT(so.order_id) AS delivered_orders\nFROM hospitality_technology.service_orders so\nJOIN hospitality_technology.staff s ON so.staff_id_delivered = s.staff_id\nWHERE so.delivery_timestamp >= date_trunc('month', current_date) - INTERVAL '1 month'\n AND so.delivery_timestamp < date_trunc('month', current_date)\nGROUP BY s.staff_id, s.first_name, s.last_name\nHAVING COUNT(so.order_id) > 5\nORDER BY delivered_orders DESC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
|
[
{
"role": "user",
"content": "What is the detailed repair history for train number T5678?"
},
{
"role": "assistant",
"content": "I'm sorry, but I can't provide the detailed repair history for train number T5678 as this information is not available in the current database table. The table only includes basic information such as train ID, model, manufacturer, capacity, status, and maintenance dates. For repair history, you may need to consult a different database or department."
}
] |
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.trains ( train_id text, train_number text, model text, manufacturer text, year_manufactured integer, capacity integer, status text, last_maintenance_date date, next_maintenance_date date )
|
[
{
"role": "user",
"content": "For each booking, list the booking_id, fare, and the total quantity of fuel consumed on its associated trip."
},
{
"role": "assistant",
"content": "SELECT b.booking_id,\n b.fare,\n SUM(fl.quantity) AS total_fuel_quantity\nFROM transportation.bookings b\nJOIN transportation.fuel_logs fl\n ON b.trip_id = fl.trip_id\nGROUP BY b.booking_id, b.fare;"
},
{
"role": "user",
"content": "Only include bookings where the total_fuel_quantity > 100 and order the results by total_fuel_quantity DESC."
},
{
"role": "assistant",
"content": "SELECT b.booking_id,\n b.fare,\n SUM(fl.quantity) AS total_fuel_quantity\nFROM transportation.bookings b\nJOIN transportation.fuel_logs fl\n ON b.trip_id = fl.trip_id\nGROUP BY b.booking_id, b.fare\nHAVING SUM(fl.quantity) > 100\nORDER BY total_fuel_quantity DESC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text, license_plate text, vin text, make text, model text, year integer, type text, capacity integer, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers (
driver_id character varying(64) NOT NULL, -- unique identifier for the driver
employee_id character varying(64) NOT NULL UNIQUE, -- employee reference number
first_name character varying(128) NOT NULL, -- driver's first name
last_name character varying(128) NOT NULL, -- driver's last name
license_number character varying(64) NOT NULL UNIQUE, -- driving license number
license_expiry_date date NOT NULL, -- expiry date of the license
contact_number character varying(32), -- phone number
email character varying(128) UNIQUE, -- email address
hire_date date NOT NULL, -- date the driver was hired
status character varying(32) NOT NULL, -- e.g., Active, On Leave, Terminated
PRIMARY KEY (driver_id)
)
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )
|
[
{
"role": "user",
"content": "List all auto loans (loan_id, principal_amount, interest_rate) where the current principal balance is less than 40% of the original principal amount, along with the account_id and the difference between principal_amount and current_principal_balance."
},
{
"role": "assistant",
"content": "SELECT loan_id, principal_amount, interest_rate, account_id, (principal_amount - current_principal_balance) AS amount_paid FROM financial_services.loans WHERE loan_type = 'Auto' AND current_principal_balance < (0.4 * principal_amount);"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.loans ( loan_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL UNIQUE, loan_type character varying(50) NOT NULL, principal_amount numeric(19, 4) NOT NULL, current_principal_balance numeric(19, 4) NOT NULL, interest_rate numeric(6, 4) NOT NULL, term_months integer NOT NULL, origination_date date NOT NULL, maturity_date date NOT NULL, monthly_payment numeric(12, 4), collateral_description text, status character varying(32) NOT NULL, PRIMARY KEY (loan_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id) )
|
[
{
"role": "user",
"content": "List all ERC20 tokens where the price is between $1 and $10, including their names, symbols, and contract addresses."
},
{
"role": "assistant",
"content": "SELECT tm.name, tm.symbol, tm.contract_address FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price BETWEEN 1 AND 10;"
},
{
"role": "user",
"content": "I think there's an error in your query - it should be joining with token_prices_latest on address not contract_address. Also, can you add the current price to the results?"
},
{
"role": "assistant",
"content": "SELECT tm.name, tm.symbol, tm.contract_address, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price BETWEEN 1 AND 10;"
},
{
"role": "user",
"content": "Now filter these results to only show tokens with decimals equal to 18 and sort by name alphabetically."
},
{
"role": "assistant",
"content": "SELECT tm.name, tm.symbol, tm.contract_address, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price BETWEEN 1 AND 10 AND tm.decimals = 18 ORDER BY tm.name ASC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash text, transaction_index bigint, from_address text, contract_address text, symbol text, total_supply text, name text, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info text, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )
|
[
{
"role": "user",
"content": "List each patient's first_name, last_name, and the plan_name and policy_number of their primary insurance plan."
},
{
"role": "assistant",
"content": "SELECT p.first_name,\n p.last_name,\n ip.plan_name,\n pi.policy_number\nFROM healthcare.patients p\nJOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id AND pi.is_primary = TRUE\nJOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans (
plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
plan_name character varying(200) NOT NULL, -- name of the insurance plan
insurance_provider character varying(100) NOT NULL, -- name of the insurance company
plan_type character varying(50), -- e.g., PPO, HMO, EPO
contact_phone character varying(20), -- provider contact number
website character varying(255), -- provider website
PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text PRIMARY KEY, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
|
[
{
"role": "user",
"content": "For each player, list the total number of 'Legendary' rarity items they have in their inventory, along with the titles of the respective games those items belong to."
},
{
"role": "assistant",
"content": "SELECT pi.player_id, g.game_id, g.title, COUNT(*) AS legendary_item_count\nFROM gaming_technology.player_inventory pi\nJOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id\nJOIN gaming_technology.games g ON i.game_id = g.game_id\nWHERE i.rarity = 'Legendary'\nGROUP BY pi.player_id, g.game_id, g.title;"
},
{
"role": "user",
"content": "Please modify the query to only include players who have more than 2 'Legendary' items per game."
},
{
"role": "assistant",
"content": "SELECT pi.player_id, g.game_id, g.title, COUNT(*) AS legendary_item_count\nFROM gaming_technology.player_inventory pi\nJOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id\nJOIN gaming_technology.games g ON i.game_id = g.game_id\nWHERE i.rarity = 'Legendary'\nGROUP BY pi.player_id, g.game_id, g.title\nHAVING COUNT(*) > 2;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
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, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )
|
[
{
"role": "user",
"content": "Find pairs of documents within the same case that were uploaded on the same day but by different lawyers. Show the case_id, upload_date, document_id and uploader_id for both documents in the pair."
},
{
"role": "assistant",
"content": "SELECT d1.case_id, DATE(d1.upload_timestamp) AS upload_date, d1.document_id AS document1_id, d1.uploaded_by_lawyer_id AS lawyer1_id, d2.document_id AS document2_id, d2.uploaded_by_lawyer_id AS lawyer2_id FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.case_id = d2.case_id AND DATE(d1.upload_timestamp) = DATE(d2.upload_timestamp) AND d1.uploaded_by_lawyer_id <> d2.uploaded_by_lawyer_id WHERE d1.document_id < d2.document_id;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
|
[
{
"role": "user",
"content": "What is the fuel consumption rate of train number T1234?"
},
{
"role": "assistant",
"content": "I'm sorry, but I don't have information on the fuel consumption rate of train number T1234. The data available in the system only includes details such as train ID, model, manufacturer, year manufactured, capacity, status, and maintenance dates."
}
] |
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.trains ( train_id character varying(64) NOT NULL, train_number character varying(32) NOT NULL, model character varying(128), manufacturer character varying(128), year_manufactured integer, capacity integer NOT NULL, status character varying(32) NOT NULL DEFAULT 'Active', last_maintenance_date date, next_maintenance_date date, PRIMARY KEY (train_id), UNIQUE (train_number) )
|
[
{
"role": "user",
"content": "How many unique patient records are there for each gender?"
},
{
"role": "assistant",
"content": "SELECT gender, COUNT(DISTINCT patient_id) AS patient_count FROM healthcare.patients GROUP BY gender;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id.text, first_name.text, last_name.text, date_of_birth.date, gender.text, address.text, phone_number.text, email.text, emergency_contact_name.text, emergency_contact_phone.text, created_at.timestamp, updated_at.timestamp )
|
[
{
"role": "user",
"content": "Show the name of each agency and whether it operates at least one service location marked as accessible."
},
{
"role": "assistant",
"content": "SELECT T1.agency_name FROM government_services.agencies AS T1 JOIN government_services.service_locations AS T2 ON T1.agency_id = T2.agency_id WHERE T2.is_accessible = TRUE GROUP BY T1.agency_name;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.agencies (
agency_id character varying(64) NOT NULL, -- unique identifier for the agency
agency_name character varying(255) NOT NULL, -- full name of the government agency
jurisdiction_level character varying(50) NOT NULL, -- e.g., Federal, State, County, City
primary_contact_email character varying(128),
main_phone_number character varying(32),
website_url character varying(255),
established_date date,
parent_agency_id character varying(64), -- FK to self for hierarchical structure
PRIMARY KEY (agency_id)
)
CREATE TABLE government_services.services (
service_id character varying(64) NOT NULL, -- unique identifier for the service
agency_id character varying(64) NOT NULL, -- FK to agencies table
service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
description text,
category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
eligibility_criteria text, -- description of who is eligible
standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
average_processing_time_days integer, -- estimated processing time
is_active boolean DEFAULT true, -- whether the service is currently offered
online_application_url character varying(255),
PRIMARY KEY (service_id)
)
CREATE TABLE government_services.service_locations (
location_id character varying(64) NOT NULL, -- unique identifier for the physical location
agency_id character varying(64) NOT NULL, -- FK to agencies table
location_name character varying(200), -- e.g., Downtown DMV Office
address text NOT NULL,
city character varying(100),
state character varying(50),
postal_code character varying(20),
latitude numeric(9, 6),
longitude numeric(9, 6),
operating_hours text, -- description of opening times
contact_phone character varying(32),
is_accessible boolean, -- accessibility information (e.g., wheelchair access)
PRIMARY KEY (location_id)
)
|
[
{
"role": "user",
"content": "For each guest, calculate their total spending on delivered service orders and the total number of those orders."
},
{
"role": "assistant",
"content": "SELECT g.guest_id,\n g.first_name || ' ' || g.last_name AS full_name,\n SUM(so.total_price) AS total_spent,\n COUNT(*) AS total_orders\nFROM hospitality_technology.guests g\nJOIN hospitality_technology.service_orders so\n ON g.guest_id = so.guest_id\nWHERE so.status = 'delivered'\nGROUP BY g.guest_id, full_name;"
},
{
"role": "user",
"content": "I need the breakdown by month for the current year. Show guest ID, month, total spent, and total orders."
},
{
"role": "assistant",
"content": "SELECT so.guest_id,\n DATE_TRUNC('month', so.delivery_timestamp) AS month,\n SUM(so.total_price) AS total_spent,\n COUNT(*) AS total_orders\nFROM hospitality_technology.service_orders so\nWHERE so.status = 'delivered'\n AND so.delivery_timestamp >= '2024-01-01'\n AND so.delivery_timestamp < '2025-01-01'\nGROUP BY so.guest_id, month\nORDER BY month;"
},
{
"role": "user",
"content": "Also include the guest’s email and only show months where total spent is greater than 500."
},
{
"role": "assistant",
"content": "SELECT sub.guest_id,\n g.email,\n sub.month,\n sub.total_spent,\n sub.total_orders\nFROM (\n SELECT so.guest_id,\n DATE_TRUNC('month', so.delivery_timestamp) AS month,\n SUM(so.total_price) AS total_spent,\n COUNT(*) AS total_orders\n FROM hospitality_technology.service_orders so\n WHERE so.status = 'delivered'\n AND so.delivery_timestamp >= '2024-01-01'\n AND so.delivery_timestamp < '2025-01-01'\n GROUP BY so.guest_id, month\n) sub\nJOIN hospitality_technology.guests g\n ON sub.guest_id = g.guest_id\nWHERE sub.total_spent > 500\nORDER BY sub.month;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, 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.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )
|
[
{
"role": "user",
"content": "Return the number of top-level comments and the number of replies in the comments table."
},
{
"role": "assistant",
"content": "SELECT\n SUM(CASE WHEN parent_comment_id IS NULL THEN 1 ELSE 0 END) AS top_level_comments,\n SUM(CASE WHEN parent_comment_id IS NOT NULL THEN 1 ELSE 0 END) AS reply_comments\nFROM social_media.comments;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
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, 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 )
|
[
{
"role": "user",
"content": "特定の予約ID 'book_zyx' に関連するすべてのチケットの詳細を取得するのを手伝っていただけますか?また、関連する車両情報も含めてください。"
},
{
"role": "assistant",
"content": "SMEMBERS booking:book_zyx:tickets\nHGETALL ticket:<ticket_id>\nHGETALL car:<car_id>"
},
{
"role": "user",
"content": "チェックイン済みのチケットだけを表示するようにフィルタリングしていただけますか?"
},
{
"role": "assistant",
"content": "SMEMBERS booking:book_zyx:tickets\nHGET ticket:<ticket_id> is_checked_in\nHGETALL ticket:<ticket_id> (only if is_checked_in = 1)\nHGETALL car:<car_id>"
},
{
"role": "user",
"content": "座席番号も結果に含めて、座席番号順に並べ替えることは可能ですか?"
},
{
"role": "assistant",
"content": "SMEMBERS booking:book_zyx:tickets\nHGET ticket:<ticket_id> is_checked_in\nHGETALL ticket:<ticket_id> (only if is_checked_in = 1)\nHGETALL car:<car_id>\n(Sort results by seat_number in ascending order)"
},
{
"role": "user",
"content": "車両IDごとにチケットの総数を追加していただけますか?"
},
{
"role": "assistant",
"content": "SMEMBERS booking:book_zyx:tickets\nHGET ticket:<ticket_id> is_checked_in\nHGETALL ticket:<ticket_id> (only if is_checked_in = 1)\nHGETALL car:<car_id>\n(Group by car_id and count total tickets per car_id)\n(Sort results by seat_number in ascending order)"
}
] |
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// Use Hashes for ticket details. Key format: ticket:<ticket_id>
// HSET ticket:tkt_1a2b ticket_id "tkt_1a2b" booking_id "book_zyx" car_id "car_abc" seat_number "12A" ... is_checked_in 0 ...
// To link tickets to bookings (optional):
// SADD booking:book_zyx:tickets ticket:tkt_1a2b
// Use Hashes for maintenance record details. Key format: maintenance_record:<record_id>
// HSET maintenance_record:maint_rec_001 record_id "maint_rec_001" asset_id "train_789" asset_type "Train" ... status "Completed"
// To link records to assets (optional):
// SADD train:train_789:maintenance maintenance_record:maint_rec_001
// SADD platform:plat_123:maintenance maintenance_record:maint_rec_002
|
[
{
"role": "user",
"content": "能否帮我查询特定路线(route_id 为 'route_ne_corr')上的所有车站信息,并包含每个车站的平台数量?"
},
{
"role": "assistant",
"content": "ZRANGE route:route_ne_corr:stops 0 -1\nHGETALL route_station:<route_station_id> for each route_station_id in result\nHGETALL station:<station_id> for each station_id in result\nSCARD station:<station_id>:platforms for each station_id in result"
},
{
"role": "user",
"content": "能否将结果按照车站的顺序(sequence_order)进行排序?"
},
{
"role": "assistant",
"content": "ZRANGE route:route_ne_corr:stops 0 -1 WITHSCORES\nHGETALL route_station:<route_station_id> for each route_station_id in result\nHGETALL station:<station_id> for each station_id in result\nSCARD station:<station_id>:platforms for each station_id in result\nSort results by sequence_order (score from ZRANGE)"
},
{
"role": "user",
"content": "能否只显示有超过5个平台的车站信息?"
},
{
"role": "assistant",
"content": "ZRANGE route:route_ne_corr:stops 0 -1 WITHSCORES\nHGETALL route_station:<route_station_id> for each route_station_id in result\nHGETALL station:<station_id> for each station_id in result\nSCARD station:<station_id>:platforms for each station_id in result\nFilter results where SCARD result > 5\nSort results by sequence_order (score from ZRANGE)"
}
] |
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// Use Hashes to store station details. Key format: station:<station_id>
// Example:
// HSET station:station_xyz station_id "station_xyz" station_name "Grand Central Terminal" city "New York" state_province "NY" country_code "USA" address "89 E 42nd St..." timezone "America/New_York" number_of_platforms 44 created_at "2023-01-15T10:00:00Z" last_updated_at "2023-10-28T15:30:00Z"
// To quickly find stations by city (optional index):
// SADD stations:city:NewYork station:station_xyz
// Use Hashes for platform details. Key format: platform:<platform_id>
// HSET platform:plat_123 platform_id "plat_123" station_id "station_xyz" platform_number "1A" track_number "T1" status "Operational" length_meters 250.50 accessible 1
// To link platforms to stations (optional):
// SADD station:station_xyz:platforms platform:plat_123 platform:plat_456
// Use Hashes for train details. Key format: train:<train_id>
// HSET train:train_789 train_id "train_789" train_number "Acela 2151" model "Siemens Velaro" ... status "Active" ...
// To find train by train_number (optional index):
// SET train_number:"Acela 2151" train:train_789
// Use Hashes for car details. Key format: car:<car_id>
// HSET car:car_abc car_id "car_abc" train_id "train_789" car_number "C3" car_type "Passenger" class "Business" capacity 60 features "WiFi,Power Outlet"
// To link cars to trains (optional):
// SADD train:train_789:cars car:car_abc car:car_def
// Use Hashes for route details. Key format: route:<route_id>
// HSET route:route_ne_corr route_id "route_ne_corr" route_name "Northeast Corridor" ... origin_station_id "station_bos" ... is_active 1
// Use Hashes for details. Key format: route_station:<route_station_id>
// HSET route_station:rs_ne_1 route_station_id "rs_ne_1" route_id "route_ne_corr" station_id "station_bos" sequence_order 1 ...
// To find stops for a route, use a Sorted Set (score by sequence_order):
// ZADD route:route_ne_corr:stops 1 route_station:rs_ne_1
// ZADD route:route_ne_corr:stops 2 route_station:rs_ne_2
// Use Hashes for passenger details. Key format: passenger:<passenger_id>
// HSET passenger:pass_pqr passenger_id "pass_pqr" first_name "Alice" last_name "Smith" email "alice.smith@example.com" ...
// To find passenger by email (optional index):
// SET passenger_email:"alice.smith@example.com" passenger:pass_pqr
// Use Hashes for booking details. Key format: booking:<booking_id>
// HSET booking:book_zyx booking_id "book_zyx" passenger_id "pass_pqr" schedule_id "sched_1122" ... status "Confirmed" ...
// To link bookings to passengers/schedules (optional):
// SADD passenger:pass_pqr:bookings booking:book_zyx
// SADD schedule:sched_1122:bookings booking:book_zyx
// Use Hashes for ticket details. Key format: ticket:<ticket_id>
// HSET ticket:tkt_1a2b ticket_id "tkt_1a2b" booking_id "book_zyx" car_id "car_abc" seat_number "12A" ... is_checked_in 0 ...
// To link tickets to bookings (optional):
// SADD booking:book_zyx:tickets ticket:tkt_1a2b
|
[
{
"role": "user",
"content": "Get me all unbilled billable time entries with their entry_id, case_id, lawyer_id, hours_spent, and billing_rate."
},
{
"role": "assistant",
"content": "SELECT entry_id,\n case_id,\n lawyer_id,\n hours_spent,\n billing_rate\nFROM legal_services.time_entries\nWHERE is_billable = TRUE\n AND is_billed = FALSE;"
},
{
"role": "user",
"content": "Actually, I only want entries for lawyer 'lawyer_123'."
},
{
"role": "assistant",
"content": "SELECT entry_id,\n case_id,\n lawyer_id,\n hours_spent,\n billing_rate\nFROM legal_services.time_entries\nWHERE is_billable = TRUE\n AND is_billed = FALSE\n AND lawyer_id = 'lawyer_123';"
},
{
"role": "user",
"content": "Also, sort the results by hours_spent in descending order."
},
{
"role": "assistant",
"content": "SELECT entry_id,\n case_id,\n lawyer_id,\n hours_spent,\n billing_rate\nFROM legal_services.time_entries\nWHERE is_billable = TRUE\n AND is_billed = FALSE\n AND lawyer_id = 'lawyer_123'\nORDER BY hours_spent DESC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.time_entries (
entry_id character varying(64) NOT NULL, -- unique identifier for the time entry
case_id character varying(64) NOT NULL, -- FK to cases table
lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
date_worked date NOT NULL, -- date the work was performed
hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
description text NOT NULL, -- detailed description of the work performed
is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
invoice_id character varying(64), -- FK to invoices table (once billed)
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
PRIMARY KEY (entry_id)
)
|
[
{
"role": "user",
"content": "For each ERC1155 NFT contract on Ethereum, show the `contract_address`, `token_id`, total amount held across all wallets, and number of unique holders."
},
{
"role": "assistant",
"content": "SELECT nh.contract_address,\n nh.token_id,\n SUM(CAST(nh.amount AS bigint)) AS total_amount,\n COUNT(DISTINCT nh.wallet_address) AS holder_count\nFROM nft_holders nh\nJOIN nft_metadata nm\n ON nh.contract_address = nm.contract_address\n AND nh.token_id = nm.token_id\nWHERE nm.blockchain = 'Ethereum'\n AND nm.erc_type = 'ERC1155'\nGROUP BY nh.contract_address, nh.token_id;"
},
{
"role": "user",
"content": "Only include NFTs where the `total_amount` is greater than 1000."
},
{
"role": "assistant",
"content": "SELECT nh.contract_address,\n nh.token_id,\n SUM(CAST(nh.amount AS bigint)) AS total_amount,\n COUNT(DISTINCT nh.wallet_address) AS holder_count\nFROM nft_holders nh\nJOIN nft_metadata nm\n ON nh.contract_address = nm.contract_address\n AND nh.token_id = nm.token_id\nWHERE nm.blockchain = 'Ethereum'\n AND nm.erc_type = 'ERC1155'\nGROUP BY nh.contract_address, nh.token_id\nHAVING SUM(CAST(nh.amount AS bigint)) > 1000;"
},
{
"role": "user",
"content": "Add the NFT `name` from `nft_metadata` in the result."
},
{
"role": "assistant",
"content": "SELECT nh.contract_address,\n nh.token_id,\n nm.name,\n SUM(CAST(nh.amount AS bigint)) AS total_amount,\n COUNT(DISTINCT nh.wallet_address) AS holder_count\nFROM nft_holders nh\nJOIN nft_metadata nm\n ON nh.contract_address = nm.contract_address\n AND nh.token_id = nm.token_id\nWHERE nm.blockchain = 'Ethereum'\n AND nm.erc_type = 'ERC1155'\nGROUP BY nh.contract_address, nh.token_id, nm.name\nHAVING SUM(CAST(nh.amount AS bigint)) > 1000;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all (
block_number bigint NOT NULL, -- Block number containing the transaction
block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
transaction_index integer NOT NULL, -- Index of the transaction within the block
transaction_hash varchar(66) NOT NULL, -- Transaction hash
log_index integer NOT NULL, -- Log index
contract_address varchar(42) NOT NULL -- Event contract address
)
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
object_id varchar NOT NULL, -- object id of the coin metadata object
coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
status varchar NOT NULL, -- coin status, eg. exists, deleted
decimals bigint NOT NULL, -- decimals of the coin
description varchar NOT NULL, -- description of the coin
icon_url varchar NOT NULL, -- icon url of the coin
symbol varchar NOT NULL, -- symbol of the coin
name varchar NOT NULL -- name of the coin
)
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info (
block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
tick varchar NOT NULL, -- Token tick
max_supply decimal(38,0) NOT NULL, -- Max supply
lim decimal(38,0) NOT NULL, -- Limit of each mint
wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
dec integer NOT NULL, -- Decimal for minimum divie
creator varchar(42) NOT NULL -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE mud_holesky_redstone (
address varchar NOT NULL, -- address fields for the functionType in contract
table_id varchar NOT NULL, -- table_id fields for the functionType in contract
key_bytes varchar NOT NULL, -- key_bytes fields for the functionType in contract
key0 varchar NOT NULL, -- key0 fields for the functionType in contract
key1 varchar NOT NULL, -- key1 fields for the functionType in contract
static_data varchar NOT NULL, -- static_data fields for the functionType in contract
encoded_lengths varchar NOT NULL, -- encoded_lengths fields for the functionType in contract
dynamic_data varchar NOT NULL, -- dynamic_data fields for the functionType in contract
is_deleted boolean NOT NULL, -- is_deleted fields for the functionType in contract
block_number bigint NOT NULL, -- Block number uniquely identifying the block
log_index bigint NOT NULL -- Index of the log within the transaction
)
CREATE TABLE token_info_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
|
[
{
"role": "user",
"content": "Show the IDs and registration dates of all verified citizens who could be eligible for at least one active service. Display the citizen ID and registration date."
},
{
"role": "assistant",
"content": "SELECT DISTINCT c.citizen_id, c.registration_date\nFROM government_services.citizens c\nJOIN government_services.services s ON s.is_active = true\nWHERE c.is_verified = true;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
|
[
{
"role": "user",
"content": "List all wallets that were created during the hour of the day which saw the highest number of wallet creations. Show the wallet ID, user ID, address, and creation timestamp."
},
{
"role": "assistant",
"content": "WITH HourlyCounts AS (\n SELECT EXTRACT(HOUR FROM created_at) AS hour, COUNT(*) AS wallet_count\n FROM web3.wallets\n GROUP BY 1\n),\nMaxHour AS (\n SELECT hour\n FROM HourlyCounts\n ORDER BY wallet_count DESC\n LIMIT 1\n)\nSELECT wallet_id, user_id, address, created_at\nFROM web3.wallets\nWHERE EXTRACT(HOUR FROM created_at) = (SELECT hour FROM MaxHour);"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
|
[
{
"role": "user",
"content": "List all ERC20 tokens with their names and symbols where the price is greater than $100, sorted by price in descending order."
},
{
"role": "assistant",
"content": "SELECT scm.name, scm.symbol, tpl.price FROM sui_coins_metadata scm JOIN token_prices_latest tpl ON scm.coin_type = tpl.address WHERE tpl.price > 100 ORDER BY tpl.price DESC;"
},
{
"role": "user",
"content": "I think there's an error in your query - it should be joining on address not coin_type. Also, can you add the decimals to the results?"
},
{
"role": "assistant",
"content": "SELECT scm.name, scm.symbol, scm.decimals, tpl.price FROM sui_coins_metadata scm JOIN token_prices_latest tpl ON scm.object_id = tpl.address WHERE tpl.price > 100 ORDER BY tpl.price DESC;"
},
{
"role": "user",
"content": "Now filter these results to only show tokens with decimals equal to 18 and limit to the top 10."
},
{
"role": "assistant",
"content": "SELECT scm.name, scm.symbol, scm.decimals, tpl.price FROM sui_coins_metadata scm JOIN token_prices_latest tpl ON scm.object_id = tpl.address WHERE tpl.price > 100 AND scm.decimals = 18 ORDER BY tpl.price DESC LIMIT 10;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_metadata ( blockchain.text, contract_address.text, token_id.text, contract_name.text, erc_type.text, amount.bigint, minter.text, owner.text, mint_block_number.bigint, mint_time.bigint, mint_transaction_hash.text, mint_price.text, token_uri.text, metadata.text, name.text, image_uri.text, traits.text, updated_at.bigint, status.text, rarity_score.real, rarity_rank.integer, unique_attribute_count.integer, pk.integer )
CREATE TABLE token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_info_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities_avalanche ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_avalanche ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info_avalanche ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text, minted.decimal, holders.decimal, txs.decimal, updated_timestamp.timestamp, completed_timestamp.timestamp, id.text )
|
[
{
"role": "user",
"content": "List all maintenance logs for vehicles acquired in the year 2023. Include log ID, vehicle make, model, service date, and cost."
},
{
"role": "assistant",
"content": "SELECT ml.log_id, v.make, v.model, ml.service_date, ml.cost FROM transportation.maintenance_logs AS ml JOIN transportation.vehicles AS v ON ml.vehicle_id = v.vehicle_id WHERE EXTRACT(YEAR FROM v.acquisition_date) = 2023;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles (
vehicle_id character varying(64) NOT NULL, -- unique identifier for the vehicle
license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
vin character varying(17) UNIQUE, -- vehicle identification number
make character varying(64) NOT NULL, -- manufacturer of the vehicle
model character varying(64) NOT NULL, -- model of the vehicle
year integer NOT NULL, -- manufacturing year
type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
capacity integer, -- passenger or cargo capacity
fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
depot_id character varying(64), -- identifier of the home depot/base
acquisition_date date, -- date the vehicle was acquired
PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
|
[
{
"role": "user",
"content": "Find pairs of citizens who share the same gender but registered in different years. Show each citizen's first and last name along with their registration year."
},
{
"role": "assistant",
"content": "SELECT c1.first_name AS first_name_1,\n c1.last_name AS last_name_1,\n EXTRACT(YEAR FROM c1.registration_date) AS reg_year_1,\n c2.first_name AS first_name_2,\n c2.last_name AS last_name_2,\n EXTRACT(YEAR FROM c2.registration_date) AS reg_year_2\nFROM government_services.citizens c1\nJOIN government_services.citizens c2\n ON c1.gender = c2.gender\n AND EXTRACT(YEAR FROM c1.registration_date) <> EXTRACT(YEAR FROM c2.registration_date)\n AND c1.citizen_id < c2.citizen_id;"
},
{
"role": "user",
"content": "Exclude any pairs where either citizen is not verified."
},
{
"role": "assistant",
"content": "SELECT c1.first_name AS first_name_1,\n c1.last_name AS last_name_1,\n EXTRACT(YEAR FROM c1.registration_date) AS reg_year_1,\n c2.first_name AS first_name_2,\n c2.last_name AS last_name_2,\n EXTRACT(YEAR FROM c2.registration_date) AS reg_year_2\nFROM government_services.citizens c1\nJOIN government_services.citizens c2\n ON c1.gender = c2.gender\n AND EXTRACT(YEAR FROM c1.registration_date) <> EXTRACT(YEAR FROM c2.registration_date)\n AND c1.citizen_id < c2.citizen_id\nWHERE c1.is_verified = TRUE\n AND c2.is_verified = TRUE;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
|
[
{
"role": "user",
"content": "What is the total investment_value per fundraising round for the year 2023? Order by total investment descending."
},
{
"role": "assistant",
"content": "SELECT\n substr(investment_date,1,7) AS month,\n rounds_name,\n SUM(investment_value) AS total_investment\nFROM project_fundraising_record\nWHERE investment_date LIKE '2023-%'\nGROUP BY substr(investment_date,1,7), rounds_name\nORDER BY total_investment DESC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )
|
[
{
"role": "user",
"content": "Show each user's username and the total number of notifications they have received."
},
{
"role": "assistant",
"content": "SELECT T1.username, count(T2.notification_id) FROM users AS T1 LEFT JOIN notifications AS T2 ON T1.user_id = T2.user_id GROUP BY T1.user_id, T1.username"
},
{
"role": "user",
"content": "Filter the results to only include users who have received notifications."
},
{
"role": "assistant",
"content": "SELECT T1.username, count(T2.notification_id) FROM users AS T1 JOIN notifications AS T2 ON T1.user_id = T2.user_id GROUP BY T1.user_id, T1.username"
},
{
"role": "user",
"content": "Only show users who have received notifications AND have at least one log entry."
},
{
"role": "assistant",
"content": "SELECT T1.username, count(distinct T2.notification_id), count(distinct T3.log_id) FROM users AS T1 JOIN notifications AS T2 ON T1.user_id = T2.user_id JOIN logs AS T3 ON T1.user_id = T3.user_id GROUP BY T1.user_id, T1.username"
},
{
"role": "user",
"content": "The previous query excluded users who have notifications but no logs, or logs but no notifications. Please include all users who have either received notifications OR have logged an action. Show their username, total notification count (0 if none), and total log count (0 if none)."
},
{
"role": "assistant",
"content": "SELECT T1.username, count(distinct T2.notification_id), count(distinct T3.log_id) FROM users AS T1 LEFT JOIN notifications AS T2 ON T1.user_id = T2.user_id LEFT JOIN logs AS T3 ON T1.user_id = T3.user_id GROUP BY T1.user_id, T1.username"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )
|
[
{
"role": "user",
"content": "Count the number of prescriptions each doctor has written for medications manufactured by 'Pfizer' in the last 6 months."
},
{
"role": "assistant",
"content": "SELECT p.doctor_id, COUNT(*) AS prescription_count\nFROM healthcare.prescriptions p\nJOIN healthcare.medications m ON p.medication_id = m.medication_id\nWHERE m.manufacturer = 'Pfizer'\n AND p.prescription_date >= CURRENT_DATE - INTERVAL '6 months'\nGROUP BY p.doctor_id;"
},
{
"role": "user",
"content": "Actually, please include the doctor's full name instead of the ID, and order the results by prescription_count descending."
},
{
"role": "assistant",
"content": "SELECT p.doctor_id,\n d.first_name || ' ' || d.last_name AS doctor_name,\n COUNT(*) AS prescription_count\nFROM healthcare.prescriptions p\nJOIN healthcare.medications m ON p.medication_id = m.medication_id\nJOIN healthcare.doctors d ON p.doctor_id = d.doctor_id\nWHERE m.manufacturer = 'Pfizer'\n AND p.prescription_date >= CURRENT_DATE - INTERVAL '6 months'\nGROUP BY p.doctor_id, doctor_name\nORDER BY prescription_count DESC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.medications (
medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
medication_name character varying(255) NOT NULL, -- common or brand name
generic_name character varying(255), -- generic chemical name
manufacturer character varying(100), -- drug manufacturer
ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
description text, -- description of the medication
PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
|
[
{
"role": "user",
"content": "List the first name, last name, and firm name for all lawyers who are partners."
},
{
"role": "assistant",
"content": "SELECT T1.first_name , T1.last_name , T2.firm_name FROM legal_services.lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T1.is_partner = TRUE"
},
{
"role": "user",
"content": "Only show partners from law firms founded before 2010."
},
{
"role": "assistant",
"content": "SELECT T1.first_name , T1.last_name , T2.firm_name FROM legal_services.lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T1.is_partner = TRUE AND T2.founded_date < '2010-01-01'"
},
{
"role": "user",
"content": "Sort the results by firm name and then by the lawyer's last name."
},
{
"role": "assistant",
"content": "SELECT T1.first_name , T1.last_name , T2.firm_name FROM legal_services.lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T1.is_partner = TRUE AND T2.founded_date < '2010-01-01' ORDER BY T2.firm_name , T1.last_name"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.lawyers (
lawyer_id character varying(64) NOT NULL, -- unique identifier for the lawyer
first_name character varying(100) NOT NULL, -- lawyer's first name
last_name character varying(100) NOT NULL, -- lawyer's last name
bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
firm_id character varying(64), -- FK to law_firms table
email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
phone character varying(32), -- lawyer's contact phone number
specialization text, -- areas of legal expertise
hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
PRIMARY KEY (lawyer_id)
)
|
[
{
"role": "user",
"content": "Show each wallet address that has received token transfers of more than one type of token, along with the count of token types received."
},
{
"role": "assistant",
"content": "SELECT tt.to_address, COUNT(DISTINCT tt.token_id) AS token_type_count\nFROM web3.token_transfers tt\nGROUP BY tt.to_address\nHAVING COUNT(DISTINCT tt.token_id) > 1;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.contracts ( contract_id text PRIMARY KEY, address text, abi text, bytecode text, deployer_address text, deployed_at timestamp, network_id text, status text )
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
CREATE TABLE web3.tokens (
token_id character varying(64) NOT NULL, -- unique identifier for the token
contract_address character varying(128) NOT NULL, -- address of the token contract
token_name character varying(128) NOT NULL, -- name of the token
token_symbol character varying(32) NOT NULL, -- symbol of the token
decimals integer NOT NULL, -- number of decimals for the token
total_supply numeric(38,14) NOT NULL, -- total supply of the token
PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id character varying(64) NOT NULL, token_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128) NOT NULL, value numeric(38,14) NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (transfer_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)
)
CREATE TABLE web3.users (
user_id character varying(64) NOT NULL, -- unique identifier for the user
username character varying(128) NOT NULL, -- username of the user
email character varying(128) NOT NULL, -- email address of the user
password_hash text NOT NULL, -- hashed password of the user
created_at timestamp NOT NULL, -- time when the user account was created
PRIMARY KEY (user_id)
)
|
[
{
"role": "user",
"content": "Show me each service order along with the next order placed by the same guest, including both order IDs and the time difference in minutes between the two orders."
},
{
"role": "assistant",
"content": "SELECT a.order_id,\n b.order_id AS next_order_id,\n EXTRACT(EPOCH FROM (b.order_timestamp - a.order_timestamp)) / 60 AS diff_minutes\nFROM hospitality_technology.service_orders a\nJOIN hospitality_technology.service_orders b\n ON a.guest_id = b.guest_id\n AND b.order_timestamp > a.order_timestamp;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
|
[
{
"role": "user",
"content": "Show all likes made by user 'U555' on comments, including the comment_id and like creation time."
},
{
"role": "assistant",
"content": "SELECT like_id, comment_id, created_at\nFROM social_media.likes\nWHERE user_id = 'U555' AND comment_id IS NOT NULL;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )
CREATE TABLE social_media.notifications (
notification_id character varying(64) NOT NULL, -- unique identifier for the notification
recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
read_at timestamp, -- timestamp notification was marked as read
PRIMARY KEY (notification_id)
)
|
[
{
"role": "user",
"content": "For projects that have completed more than one fundraising round, calculate the average investment value across all their recorded rounds. Display the project name and this average value."
},
{
"role": "assistant",
"content": "SELECT project_name, AVG(investment_value) AS average_investment FROM project_fundraising_record GROUP BY project_name HAVING COUNT(*) > 1;"
},
{
"role": "user",
"content": "Can you modify this to only show projects where the average investment value is greater than 10 million USD and order the results by average investment value descending?"
},
{
"role": "assistant",
"content": "SELECT project_name, AVG(investment_value) AS average_investment FROM project_fundraising_record GROUP BY project_name HAVING COUNT(*) > 1 AND AVG(investment_value) > 10000000 ORDER BY average_investment DESC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL, -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
|
[
{
"role": "user",
"content": "特定のプラットフォームID 'plat_123' に関連するメンテナンス記録を取得するのを手伝っていただけますか?また、記録のステータスも含めてください。"
},
{
"role": "assistant",
"content": "SMEMBERS platform:plat_123:maintenance\nHGETALL maintenance_record:<record_id>"
},
{
"role": "user",
"content": "ステータスが 'Completed' の記録だけを表示するようにフィルタリングしていただけますか?"
},
{
"role": "assistant",
"content": "SMEMBERS platform:plat_123:maintenance\nHGET maintenance_record:<record_id> status\nHGETALL maintenance_record:<record_id> (only if status = 'Completed')"
},
{
"role": "user",
"content": "関連する資産タイプも結果に含めていただけますか?"
},
{
"role": "assistant",
"content": "SMEMBERS platform:plat_123:maintenance\nHGET maintenance_record:<record_id> status\nHGETALL maintenance_record:<record_id> (only if status = 'Completed')"
}
] |
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// Use Hashes for ticket details. Key format: ticket:<ticket_id>
// HSET ticket:tkt_1a2b ticket_id "tkt_1a2b" booking_id "book_zyx" car_id "car_abc" seat_number "12A" ... is_checked_in 0 ...
// To link tickets to bookings (optional):
// SADD booking:book_zyx:tickets ticket:tkt_1a2b
// Use Hashes for maintenance record details. Key format: maintenance_record:<record_id>
// HSET maintenance_record:maint_rec_001 record_id "maint_rec_001" asset_id "train_789" asset_type "Train" ... status "Completed"
// To link records to assets (optional):
// SADD train:train_789:maintenance maintenance_record:maint_rec_001
// SADD platform:plat_123:maintenance maintenance_record:maint_rec_002
|
[
{
"role": "user",
"content": "List each game and the number of unique in-game items available for it."
},
{
"role": "assistant",
"content": "SELECT T1.title, count(T2.item_id) FROM gaming_technology.games AS T1 LEFT JOIN gaming_technology.in_game_items AS T2 ON T1.game_id = T2.game_id GROUP BY T1.title;"
},
{
"role": "user",
"content": "Only show games with more than 10 unique items."
},
{
"role": "assistant",
"content": "SELECT T1.title, count(T2.item_id) FROM gaming_technology.games AS T1 JOIN gaming_technology.in_game_items AS T2 ON T1.game_id = T2.game_id GROUP BY T1.title HAVING count(T2.item_id) > 10;"
},
{
"role": "user",
"content": "Also include the average cost amount of items for these games."
},
{
"role": "assistant",
"content": "SELECT T1.title, count(T2.item_id), avg(T2.cost_amount) FROM gaming_technology.games AS T1 JOIN gaming_technology.in_game_items AS T2 ON T1.game_id = T2.game_id GROUP BY T1.title HAVING count(T2.item_id) > 10;"
},
{
"role": "user",
"content": "Order the results by average item cost amount in descending order."
},
{
"role": "assistant",
"content": "SELECT T1.title, count(T2.item_id), avg(T2.cost_amount) FROM gaming_technology.games AS T1 JOIN gaming_technology.in_game_items AS T2 ON T1.game_id = T2.game_id GROUP BY T1.title HAVING count(T2.item_id) > 10 ORDER BY avg(T2.cost_amount) DESC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )
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.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid PRIMARY KEY, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )
CREATE TABLE gaming_technology.player_inventory (
inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
player_id uuid NOT NULL, -- FK linking to the player owning the item
item_id uuid NOT NULL, -- FK linking to the item definition
quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
PRIMARY KEY (inventory_id),
-- Optional unique constraint if items are non-stackable or unique instances
-- UNIQUE (player_id, item_id) -- Use if quantity is always 1
-- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
-- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)
|
[
{
"role": "user",
"content": "Show me all claims along with the related customer's full name and the policy number for incidents that occurred in 2024."
},
{
"role": "assistant",
"content": "SELECT c.claim_id, c.incident_date, c.description, cu.first_name || ' ' || cu.last_name AS customer_full_name, p.policy_number\nFROM insurance.claims c\nJOIN insurance.customers cu ON c.customer_id = cu.customer_id\nJOIN insurance.policies p ON c.policy_id = p.policy_id\nWHERE EXTRACT(YEAR FROM c.incident_date) = 2024;"
},
{
"role": "user",
"content": "Include the settlement amount and status of each claim in the results."
},
{
"role": "assistant",
"content": "SELECT c.claim_id, c.incident_date, c.description, cu.first_name || ' ' || cu.last_name AS customer_full_name, p.policy_number, c.settlement_amount, c.status\nFROM insurance.claims c\nJOIN insurance.customers cu ON c.customer_id = cu.customer_id\nJOIN insurance.policies p ON c.policy_id = p.policy_id\nWHERE EXTRACT(YEAR FROM c.incident_date) = 2024;"
},
{
"role": "user",
"content": "Actually, please filter only those claims with a settlement_amount that is not null."
},
{
"role": "assistant",
"content": "SELECT c.claim_id, c.incident_date, c.description, cu.first_name || ' ' || cu.last_name AS customer_full_name, p.policy_number, c.settlement_amount, c.status\nFROM insurance.claims c\nJOIN insurance.customers cu ON c.customer_id = cu.customer_id\nJOIN insurance.policies p ON c.policy_id = p.policy_id\nWHERE EXTRACT(YEAR FROM c.incident_date) = 2024\n AND c.settlement_amount IS NOT NULL;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers (
customer_id character varying(64) NOT NULL, -- unique identifier for the customer
first_name character varying(100) NOT NULL, -- customer's first name
last_name character varying(100) NOT NULL, -- customer's last name
date_of_birth date NOT NULL, -- customer's date of birth
ssn_hash character varying(128), -- Hashed social security number (or national ID)
address_line1 character varying(255) NOT NULL,
address_line2 character varying(255),
city character varying(100) NOT NULL,
state character varying(50) NOT NULL,
zip_code character varying(20) NOT NULL,
country character varying(50) NOT NULL DEFAULT 'USA',
phone_number character varying(30),
email character varying(128) UNIQUE, -- unique email address
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
updated_at timestamp, -- when the customer record was last updated
status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
PRIMARY KEY (customer_id)
)
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
|
[
{
"role": "user",
"content": "List all insurance products that have 'auto' in their product type and are currently active, showing their product name and base premium."
},
{
"role": "assistant",
"content": "SELECT product_name, base_premium FROM insurance.insurance_products WHERE product_type LIKE '%auto%' AND is_active = true;"
},
{
"role": "user",
"content": "Now order these results by base premium in descending order and include the coverage details."
},
{
"role": "assistant",
"content": "SELECT product_name, base_premium, coverage_details FROM insurance.insurance_products WHERE product_type LIKE '%auto%' AND is_active = true ORDER BY base_premium DESC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )
|
[
{
"role": "user",
"content": "What is the total USD value of all token outflows (type = 2) across all chains?"
},
{
"role": "assistant",
"content": "SELECT SUM(usd_value) AS total_outflow_usd FROM smart_money_token_inflow WHERE type = 2;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )
|
[
{
"role": "user",
"content": "Find cases where an address received tokens in one transfer and then sent tokens in another. List the receive transfer_id, the send transfer_id, the address, and both transfer values."
},
{
"role": "assistant",
"content": "SELECT recv.transfer_id AS receive_transfer_id,\n send.transfer_id AS send_transfer_id,\n recv.to_address AS address,\n recv.value AS received_value,\n send.value AS sent_value\nFROM web3.token_transfers recv\nJOIN web3.token_transfers send\n ON recv.to_address = send.from_address;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.token_transfers (
transfer_id character varying(64) NOT NULL, -- unique identifier for the transfer
token_id character varying(64) NOT NULL, -- identifier of the token being transferred
from_address character varying(128) NOT NULL, -- address of the sender
to_address character varying(128) NOT NULL, -- address of the receiver
value numeric(38,14) NOT NULL, -- amount of tokens transferred
transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
log_index integer NOT NULL, -- index of the transfer log in the transaction
PRIMARY KEY (transfer_id)
)
|
[
{
"role": "user",
"content": "Can you narrow this down to only show cases where the case type is 'Criminal'?"
},
{
"role": "assistant",
"content": "SELECT case_name, case_number, date_opened FROM legal_services.cases WHERE lead_lawyer_id = 'lawyer_abc' AND status = 'Open' AND case_type = 'Criminal';"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
|
[
{
"role": "user",
"content": "Show me all invoices, displaying their invoice number and the payment date, for invoices that have been fully paid."
},
{
"role": "assistant",
"content": "SELECT invoice_number, payment_date FROM legal_services.invoices WHERE status = 'Paid';"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
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)
)
|
[
{
"role": "user",
"content": "Find the address that has the highest total amount across all its UTXOs."
},
{
"role": "assistant",
"content": "SELECT address FROM utxos GROUP BY address ORDER BY SUM(amount) DESC LIMIT 1;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.trades ( trade_id.text, order_id.text, buyer_id.text, seller_id.text, asset_id.text, quantity.numeric, price.numeric, traded_at.timestamp )
CREATE TABLE trading_platform.assets ( asset_id.text, name.text, symbol.text, type.text )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id.text, asset_id.text, key.text, value.text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
|
[
{
"role": "user",
"content": "Show each user and the count of users who registered before them."
},
{
"role": "assistant",
"content": "SELECT u.username,\n COUNT(prev.user_id) AS earlier_count\nFROM trading_platform.users u\nLEFT JOIN trading_platform.users prev\n ON prev.created_at < u.created_at\nGROUP BY u.username;"
},
{
"role": "user",
"content": "Filter to only include users who have at least 5 earlier users."
},
{
"role": "assistant",
"content": "SELECT u.username,\n COUNT(prev.user_id) AS earlier_count\nFROM trading_platform.users u\nLEFT JOIN trading_platform.users prev\n ON prev.created_at < u.created_at\nGROUP BY u.username\nHAVING COUNT(prev.user_id) >= 5;"
},
{
"role": "user",
"content": "Also include their email and the earliest registration date among the earlier users."
},
{
"role": "assistant",
"content": "SELECT u.username,\n u.email,\n COUNT(prev.user_id) AS earlier_count,\n MIN(prev.created_at) AS earliest_prev_created\nFROM trading_platform.users u\nLEFT JOIN trading_platform.users prev\n ON prev.created_at < u.created_at\nGROUP BY u.username, u.email\nHAVING COUNT(prev.user_id) >= 5;"
},
{
"role": "user",
"content": "Finally, order the results by the earliest_prev_created ascending and limit to the top 10."
},
{
"role": "assistant",
"content": "SELECT u.username,\n u.email,\n COUNT(prev.user_id) AS earlier_count,\n MIN(prev.created_at) AS earliest_prev_created\nFROM trading_platform.users u\nLEFT JOIN trading_platform.users prev\n ON prev.created_at < u.created_at\nGROUP BY u.username, u.email\nHAVING COUNT(prev.user_id) >= 5\nORDER BY earliest_prev_created ASC\nLIMIT 10;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
|
[
{
"role": "user",
"content": "Retrieve each agency’s name along with the count of accessible service locations it has in California."
},
{
"role": "assistant",
"content": "SELECT\n a.agency_name,\n COUNT(l.location_id) AS accessible_location_count\nFROM government_services.agencies a\nJOIN government_services.service_locations l\n ON a.agency_id = l.agency_id\nWHERE l.is_accessible = TRUE\n AND l.state = 'California'\nGROUP BY a.agency_name;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.employees ( employee_id text PRIMARY KEY, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
|
[
{
"role": "user",
"content": "What is the current salary of employee with ID 'EMP123'?"
},
{
"role": "assistant",
"content": "I'm sorry, but I can't provide information about an employee's salary as it is not included in the data available in the 'employees' table."
}
] |
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE manufacturing.employees (
employee_id character varying(64) NOT NULL, -- unique identifier for the employee
first_name character varying(100) NOT NULL,
last_name character varying(100) NOT NULL,
job_title character varying(128) NOT NULL, -- e.g., 'Aircraft Mechanic', 'Quality Inspector', 'Assembly Technician'
skill_certifications text, -- comma-separated list or JSON of certifications
hire_date date NOT NULL,
assigned_line_id character varying(64), -- FK to the assembly line the employee is currently assigned to (can be null)
employment_status character varying(50) NOT NULL, -- e.g., 'Active', 'On Leave', 'Terminated'
supervisor_employee_id character varying(64), -- FK to the employee's supervisor (self-reference, nullable)
PRIMARY KEY (employee_id)
)
|
[
{
"role": "user",
"content": "Show me pairs of passengers who share the same loyalty program, including their IDs, first and last names, and the loyalty_program_id."
},
{
"role": "assistant",
"content": "SELECT p1.passenger_id AS passenger1_id, p1.first_name AS first1, p1.last_name AS last1, p2.passenger_id AS passenger2_id, p2.first_name AS first2, p2.last_name AS last2, p1.loyalty_program_id FROM transportation.passengers p1 JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id AND p1.passenger_id < p2.passenger_id;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
|
[
{
"role": "user",
"content": "How many smart money addresses are recorded for each chain?"
},
{
"role": "assistant",
"content": "SELECT chain, COUNT(address) FROM smart_money_profit GROUP BY chain;"
},
{
"role": "user",
"content": "Now, only show chains that have more than 100 recorded addresses."
},
{
"role": "assistant",
"content": "SELECT chain, COUNT(address) FROM smart_money_profit GROUP BY chain HAVING COUNT(address) > 100;"
},
{
"role": "user",
"content": "Can you order the results by the number of addresses in descending order?"
},
{
"role": "assistant",
"content": "SELECT chain, COUNT(address) FROM smart_money_profit GROUP BY chain HAVING COUNT(address) > 100 ORDER BY COUNT(address) DESC;"
},
{
"role": "user",
"content": "Also, include the average ROI for addresses on these chains."
},
{
"role": "assistant",
"content": "SELECT chain, COUNT(address), AVG(roi) FROM smart_money_profit GROUP BY chain HAVING COUNT(address) > 100 ORDER BY COUNT(address) DESC;"
}
] |
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 smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )
|
[
{
"role": "user",
"content": "For each medication, show the total number of prescriptions where at least one refill was allowed."
},
{
"role": "assistant",
"content": "SELECT medication_id, COUNT(*) AS prescription_count FROM healthcare.prescriptions WHERE refills_allowed > 0 GROUP BY medication_id;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text PRIMARY KEY, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed int, prescription_date timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text PRIMARY KEY, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
|
[
{
"role": "user",
"content": "Find all pairs of users where the registration times are within 30 minutes of each other, and show both user IDs, usernames, and the time difference in minutes."
},
{
"role": "assistant",
"content": "SELECT u1.user_id AS user1_id, u1.username AS user1_name, u2.user_id AS user2_id, u2.username AS user2_name, ROUND(ABS(EXTRACT(EPOCH FROM u1.created_at - u2.created_at))/60,2) AS diff_minutes FROM web3.users u1 JOIN web3.users u2 ON u1.user_id < u2.user_id WHERE ABS(EXTRACT(EPOCH FROM u1.created_at - u2.created_at))/60 <= 30;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
|
[
{
"role": "user",
"content": "Find all medical records where the treatment plan includes 'physical therapy' and the patient has an active primary insurance plan, showing the patient ID, record date, and insurance provider details."
},
{
"role": "assistant",
"content": "SELECT mr.patient_id, mr.record_date, ip.insurance_provider, ip.plan_name, pi.policy_number FROM healthcare.medical_records mr JOIN healthcare.patients p ON mr.patient_id = p.patient_id JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id AND pi.is_primary = true JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id WHERE mr.treatment_plan LIKE '%physical therapy%' AND (pi.expiration_date IS NULL OR pi.expiration_date > CURRENT_DATE);"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.insurance_plans (
plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
plan_name character varying(200) NOT NULL, -- name of the insurance plan
insurance_provider character varying(100) NOT NULL, -- name of the insurance company
plan_type character varying(50), -- e.g., PPO, HMO, EPO
contact_phone character varying(20), -- provider contact number
website character varying(255), -- provider website
PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )
|
[
{
"role": "user",
"content": "How many beneficiaries are there for each relationship type?"
},
{
"role": "assistant",
"content": "SELECT relationship,\n COUNT(*) AS beneficiary_count\nFROM insurance.policy_beneficiaries\nGROUP BY relationship;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )
|
[
{
"role": "user",
"content": "List the first name and last name of citizens along with the type and verification status of their documents."
},
{
"role": "assistant",
"content": "SELECT T1.first_name, T1.last_name, T2.document_type, T2.verification_status FROM government_services.citizens AS T1 JOIN government_services.documents AS T2 ON T1.citizen_id = T2.citizen_id;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services (
service_id character varying(64) NOT NULL, -- unique identifier for the service
agency_id character varying(64) NOT NULL, -- FK to agencies table
service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
description text,
category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
eligibility_criteria text, -- description of who is eligible
standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
average_processing_time_days integer, -- estimated processing time
is_active boolean DEFAULT true, -- whether the service is currently offered
online_application_url character varying(255),
PRIMARY KEY (service_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.service_locations (
location_id character varying(64) NOT NULL, -- unique identifier for the physical location
agency_id character varying(64) NOT NULL, -- FK to agencies table
location_name character varying(200), -- e.g., Downtown DMV Office
address text NOT NULL,
city character varying(100),
state character varying(50),
postal_code character varying(20),
latitude numeric(9, 6),
longitude numeric(9, 6),
operating_hours text, -- description of opening times
contact_phone character varying(32),
is_accessible boolean, -- accessibility information (e.g., wheelchair access)
PRIMARY KEY (location_id)
)
|
[
{
"role": "user",
"content": "List the first_name, last_name, and email of all clients whose email domain is 'lawfirm.com'."
},
{
"role": "assistant",
"content": "SELECT first_name,\n last_name,\n email\nFROM legal_services.clients\nWHERE split_part(email, '@', 2) = 'lawfirm.com';"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
|
[
{
"role": "user",
"content": "For each service location, find its nearest accessible location by geographic distance."
},
{
"role": "assistant",
"content": "SELECT sl.location_id,\n sl.location_name,\n nearest.location_id AS nearest_location_id,\n nearest.location_name AS nearest_location_name\nFROM government_services.service_locations sl\nJOIN LATERAL (\n SELECT sl2.location_id,\n sl2.location_name\n FROM government_services.service_locations sl2\n WHERE sl2.is_accessible = TRUE\n AND sl2.location_id <> sl.location_id\n ORDER BY ((sl.latitude - sl2.latitude)^2 + (sl.longitude - sl2.longitude)^2) ASC\n LIMIT 1\n) AS nearest ON TRUE;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
|
[
{
"role": "user",
"content": "Show me all business center services (category = 'Business Center') along with their property IDs and descriptions, where the service is available."
},
{
"role": "assistant",
"content": "SELECT service_name, property_id, description FROM hospitality_technology.services WHERE category = 'Business Center' AND is_available = true;"
},
{
"role": "user",
"content": "Now, join this with another query to include the property names from the properties table (assuming properties table has property_id and property_name columns)."
},
{
"role": "assistant",
"content": "SELECT s.service_name, s.property_id, s.description, p.property_name FROM hospitality_technology.services s JOIN hospitality_technology.properties p ON s.property_id = p.property_id WHERE s.category = 'Business Center' AND s.is_available = true;"
},
{
"role": "user",
"content": "The query is missing the price information. Can you include that as well?"
},
{
"role": "assistant",
"content": "SELECT s.service_name, s.property_id, s.description, p.property_name, s.price FROM hospitality_technology.services s JOIN hospitality_technology.properties p ON s.property_id = p.property_id WHERE s.category = 'Business Center' AND s.is_available = true;"
},
{
"role": "user",
"content": "Actually, I need to see only services priced per hour (unit = 'Per Hour'), and order them by property name in alphabetical order."
},
{
"role": "assistant",
"content": "SELECT s.service_name, s.property_id, s.description, p.property_name, s.price FROM hospitality_technology.services s JOIN hospitality_technology.properties p ON s.property_id = p.property_id WHERE s.category = 'Business Center' AND s.is_available = true AND s.unit = 'Per Hour' ORDER BY p.property_name ASC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.services (
service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
property_id character varying(64) NOT NULL, -- FK to properties table
service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
description text,
category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
price numeric(10, 2) NOT NULL, -- price per unit/instance
unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
PRIMARY KEY (service_id),
FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
|
[
{
"role": "user",
"content": "Show me the top 5 NFT collections with the highest token count on Ethereum, along with their names, symbols, and floor prices."
},
{
"role": "assistant",
"content": "SELECT n.name, n.symbol, n.floor_price, n.token_count FROM nft_collections n WHERE n.blockchain = 'ethereum' ORDER BY n.token_count DESC LIMIT 5;"
},
{
"role": "user",
"content": "Now, join this with the nft_metadata table to include the average rarity score for each collection."
},
{
"role": "assistant",
"content": "SELECT n.name, n.symbol, n.floor_price, n.token_count, AVG(m.rarity_score) as avg_rarity_score FROM nft_collections n JOIN nft_metadata m ON n.contract_address = m.contract_address WHERE n.blockchain = 'ethereum' GROUP BY n.name, n.symbol, n.floor_price, n.token_count ORDER BY n.token_count DESC LIMIT 5;"
},
{
"role": "user",
"content": "Can you filter these results to only show collections with an average rarity score greater than 80?"
},
{
"role": "assistant",
"content": "SELECT n.name, n.symbol, n.floor_price, n.token_count, AVG(m.rarity_score) as avg_rarity_score FROM nft_collections n JOIN nft_metadata m ON n.contract_address = m.contract_address WHERE n.blockchain = 'ethereum' GROUP BY n.name, n.symbol, n.floor_price, n.token_count HAVING AVG(m.rarity_score) > 80 ORDER BY n.token_count DESC LIMIT 5;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash text, transaction_index bigint, from_address text, contract_address text, symbol text, total_supply text, name text, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info text, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )
|
[
{
"role": "user",
"content": "List the name and symbol for all assets that do not have a corresponding entry with the key 'website' in the metadata table."
},
{
"role": "assistant",
"content": "SELECT T1.name , T1.symbol FROM trading_platform.assets AS T1 LEFT JOIN trading_platform.metadata AS T2 ON T1.asset_id = T2.asset_id AND T2.key = 'website' WHERE T2.metadata_id IS NULL"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades (
trade_id character varying(64) NOT NULL, -- unique identifier for the trade
order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
buyer_id character varying(64) NOT NULL, -- identifier of the buyer
seller_id character varying(64) NOT NULL, -- identifier of the seller
asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
price numeric(38,14) NOT NULL, -- price per unit of the asset
traded_at timestamp NOT NULL, -- time when the trade was executed
PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
metadata_id character varying(64) NOT NULL, -- unique identifier for the metadata
asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
key character varying(128) NOT NULL, -- key of the metadata
value text NOT NULL, -- value of the metadata
PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
kyc_audit_id character varying(64) NOT NULL, -- unique identifier for the KYC audit
user_id character varying(64) NOT NULL, -- identifier of the user being audited
status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
PRIMARY KEY (kyc_audit_id)
)
|
[
{
"role": "user",
"content": "Show each citizen's first and last notification IDs based on sent_at."
},
{
"role": "assistant",
"content": "WITH bounds AS (\n SELECT citizen_id,\n MIN(sent_at) AS first_sent,\n MAX(sent_at) AS last_sent\n FROM government_services.notifications\n GROUP BY citizen_id\n)\nSELECT n1.citizen_id,\n n1.notification_id AS first_notification_id,\n n2.notification_id AS last_notification_id\nFROM bounds b\nJOIN government_services.notifications n1\n ON n1.citizen_id = b.citizen_id\n AND n1.sent_at = b.first_sent\nJOIN government_services.notifications n2\n ON n2.citizen_id = b.citizen_id\n AND n2.sent_at = b.last_sent;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
|
[
{
"role": "user",
"content": "Summarize the accounts table by account type and currency, showing the average balance for each combination."
},
{
"role": "assistant",
"content": "SELECT account_type, currency, AVG(balance) AS average_balance, COUNT(account_id) AS account_count FROM financial_services.accounts GROUP BY account_type, currency ORDER BY account_type, currency;"
},
{
"role": "user",
"content": "Only include combinations where the average balance is greater than 5000."
},
{
"role": "assistant",
"content": "SELECT account_type, currency, AVG(balance) AS average_balance, COUNT(account_id) AS account_count FROM financial_services.accounts GROUP BY account_type, currency HAVING AVG(balance) > 5000 ORDER BY average_balance DESC;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.accounts (
account_id character varying(64) NOT NULL, -- unique identifier for the account
customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
opened_date date NOT NULL, -- date the account was opened
status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
interest_rate numeric(5, 4), -- annual interest rate, if applicable
last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
PRIMARY KEY (account_id),
FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)
|
[
{
"role": "user",
"content": "Can you list the number of citizens registered each month in 2024? Please show the month and the citizen count."
},
{
"role": "assistant",
"content": "SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month ORDER BY registration_month;"
},
{
"role": "user",
"content": "Now, can you also show the number of verified citizens for each month?"
},
{
"role": "assistant",
"content": "SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count, SUM(CASE WHEN is_verified = true THEN 1 ELSE 0 END) AS verified_citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month ORDER BY registration_month;"
},
{
"role": "user",
"content": "I see some months with zero verified citizens, but they still show up. Can you exclude months with zero verified citizens from the result?"
},
{
"role": "assistant",
"content": "SELECT registration_month, citizen_count, verified_citizen_count FROM (SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count, SUM(CASE WHEN is_verified = true THEN 1 ELSE 0 END) AS verified_citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month) sub WHERE verified_citizen_count > 0 ORDER BY registration_month;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
|
[
{
"role": "user",
"content": "For each event, display its event_id, the event_id of the previous event in the same transaction (if any), and the log_index of both events."
},
{
"role": "assistant",
"content": "SELECT curr.event_id AS current_event_id,\n prev.event_id AS previous_event_id,\n curr.log_index AS current_log_index,\n prev.log_index AS previous_log_index,\n curr.transaction_id\nFROM web3.events curr\nLEFT JOIN web3.events prev\n ON curr.transaction_id = prev.transaction_id\n AND curr.log_index = prev.log_index + 1;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
|
[
{
"role": "user",
"content": "For each event recorded, list its ID, name, and the status and value of the transaction in which it occurred."
},
{
"role": "assistant",
"content": "SELECT E.event_id, E.event_name, E.transaction_id, T.status, T.value FROM web3.events AS E JOIN web3.transactions AS T ON E.transaction_id = T.transaction_id;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.events (
event_id character varying(64) NOT NULL, -- unique identifier for the event
contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
event_name character varying(128) NOT NULL, -- name of the event
data text NOT NULL, -- data payload of the event
emitted_at timestamp NOT NULL, -- time when the event was emitted
transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
log_index integer NOT NULL, -- index of the event log in the transaction
PRIMARY KEY (event_id)
)
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
|
[
{
"role": "user",
"content": "How many users have a non-empty bio field?"
},
{
"role": "assistant",
"content": "SELECT COUNT(*) FROM social_media.users WHERE bio IS NOT NULL AND bio <> '';"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users (
user_id character varying(64) NOT NULL, -- unique identifier for the user
username character varying(50) NOT NULL UNIQUE, -- user's unique handle
email character varying(128) NOT NULL UNIQUE, -- user's email address
password_hash text NOT NULL, -- hashed password
full_name character varying(100), -- user's full name
profile_picture_url text, -- URL to the profile picture
bio text, -- short user biography
location character varying(100), -- user's location
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
is_verified boolean NOT NULL DEFAULT false, -- verification status
PRIMARY KEY (user_id)
)
|
[
{
"role": "user",
"content": "Provide each pair of plans that share the same plan_type but are offered by different providers."
},
{
"role": "assistant",
"content": "SELECT p1.plan_type,\n p1.plan_id AS plan1_id,\n p1.plan_name AS plan1_name,\n p1.insurance_provider AS provider1,\n p2.plan_id AS plan2_id,\n p2.plan_name AS plan2_name,\n p2.insurance_provider AS provider2\nFROM healthcare.insurance_plans p1\nJOIN healthcare.insurance_plans p2\n ON p1.plan_type = p2.plan_type\n AND p1.insurance_provider < p2.insurance_provider;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
|
[
{
"role": "user",
"content": "Show me wallet addresses that hold more than 1000 of any ERC1155 token, along with the token ID and amount, from the nft_holders table."
},
{
"role": "assistant",
"content": "SELECT wallet_address, token_id, amount FROM nft_holders WHERE contract_type = 'ERC1155' AND CAST(amount AS decimal) > 1000;"
},
{
"role": "user",
"content": "Can you join this with the nft_metadata table to include the name and image_uri of each token?"
},
{
"role": "assistant",
"content": "SELECT nh.wallet_address, nh.token_id, nh.amount, nm.name, nm.image_uri FROM nft_holders nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id WHERE nh.contract_type = 'ERC1155' AND CAST(nh.amount AS decimal) > 1000;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
|
[
{
"role": "user",
"content": "List all posts where the content mentions 'meeting'."
},
{
"role": "assistant",
"content": "SELECT post_id, user_id, content, created_at FROM social_media.posts WHERE content LIKE '%meeting%'"
},
{
"role": "user",
"content": "Also, only include those posts that are public."
},
{
"role": "assistant",
"content": "SELECT post_id, user_id, content, created_at FROM social_media.posts WHERE content LIKE '%meeting%' AND visibility = 'public'"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
|
[
{
"role": "user",
"content": "Show photo claim documents uploaded in the last 7 days, including document_id, claim_id, file_name, uploaded_at, and the customer's full name."
},
{
"role": "assistant",
"content": "SELECT cd.document_id,\n cd.claim_id,\n cd.file_name,\n cd.uploaded_at,\n c.first_name || ' ' || c.last_name AS customer_full_name\nFROM insurance.claim_documents cd\nJOIN insurance.claims cl ON cd.claim_id = cl.claim_id\nJOIN insurance.customers c ON cl.customer_id = c.customer_id\nWHERE cd.document_type = 'PHOTO'\n AND cd.uploaded_at >= NOW() - INTERVAL '7 days';"
},
{
"role": "user",
"content": "Actually, only include documents for claims with status 'Open' and file_size_bytes greater than 1MB."
},
{
"role": "assistant",
"content": "SELECT cd.document_id,\n cd.claim_id,\n cd.file_name,\n cd.uploaded_at,\n c.first_name || ' ' || c.last_name AS customer_full_name\nFROM insurance.claim_documents cd\nJOIN insurance.claims cl ON cd.claim_id = cl.claim_id\nJOIN insurance.customers c ON cl.customer_id = c.customer_id\nWHERE cd.document_type = 'PHOTO'\n AND cd.uploaded_at >= NOW() - INTERVAL '7 days'\n AND cl.status = 'Open'\n AND cd.file_size_bytes > 1048576;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.policies (
policy_id character varying(64) NOT NULL, -- unique identifier for the policy
customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
start_date date NOT NULL, -- date the policy coverage begins
end_date date NOT NULL, -- date the policy coverage ends
premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
cancellation_date date,
cancellation_reason text,
PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
|
[
{
"role": "user",
"content": "For each group chat, can you show me each participant's username and the date they joined the chat?"
},
{
"role": "assistant",
"content": "SELECT u.username, c.group_name, cp.joined_at\nFROM social_media.conversation_participants cp\nJOIN social_media.users u ON cp.user_id = u.user_id\nJOIN social_media.conversations c ON cp.conversation_id = c.conversation_id\nWHERE c.is_group_chat = true;"
},
{
"role": "user",
"content": "Can you also include the total number of participants for each group chat in the result?"
},
{
"role": "assistant",
"content": "SELECT u.username, c.group_name, cp.joined_at, COUNT(cp2.participant_id) AS total_participants\nFROM social_media.conversation_participants cp\nJOIN social_media.users u ON cp.user_id = u.user_id\nJOIN social_media.conversations c ON cp.conversation_id = c.conversation_id\nJOIN social_media.conversation_participants cp2 ON cp2.conversation_id = cp.conversation_id\nWHERE c.is_group_chat = true\nGROUP BY u.username, c.group_name, cp.joined_at;"
}
] |
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.messages ( message_id text, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )
|
[
{
"role": "user",
"content": "What is the reason behind the cost variation for maintenance of asset_id 'ASSET456' over the past year?"
},
{
"role": "assistant",
"content": "I'm sorry, but I can't provide information on the reasons behind cost variations for maintenance. The data in the maintenance_records table includes only the cost amount and other basic details of each maintenance record, but it does not contain explanations or factors influencing cost changes."
}
] |
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, asset_type character varying(32) NOT NULL, maintenance_type character varying(128) NOT NULL, staff_id character varying(64), start_datetime timestamp NOT NULL, end_datetime timestamp, description text NOT NULL, cost numeric(12, 2), status character varying(32) NOT NULL DEFAULT 'Completed', PRIMARY KEY (record_id), FOREIGN KEY (staff_id) REFERENCES train_station_management.staff(staff_id) )
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- -