Skip to content

[Question] how to set dynamic query in where clause #967

Description

@hugehoo

Hello,

I'm currently working with the sqlx and have encountered a scenario where I need to conditionally include the column event_name filter in my SQL query. Specifically, I want to omit the event_name condition when its corresponding value is nil or not provided, without manually constructing the entire query string.

Here's the query and code I'm using:

	query := `
		SELECT *
		FROM i_event_log_kst_day e
		WHERE e.partition_timestamp BETWEEN DATE :startTime AND DATE :endTime
		AND e.partner_id = :partnerID
		AND e.event_name = :eventName
		ORDER BY e.created_at, e.user_id
	`
	arg := map[string]interface{}{
		"startTime": startTime,
		"endTime":   endTime,
		"partnerID": partnerID,
		"eventName": eventName,
	}
	
        result, err := a.db.NamedQuery(query, arg);

When eventName is nil or not provided, I would like the query to exclude the AND e.event_name = :eventName condition, effectively ignoring the event_name column in the filtering process.

Is there a recommended approach within the sqlx library to achieve this dynamic behavior without resorting to manual query string manipulation?

Thank you for your assistance.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions