def build_query(main_prop, optional_props=None, lang=None):
    """
    Construct a sparql query returning items containing a given property.

    The main_prop is given the label 'value' whereas any optional_props
    use the property pid as the label.

    :param main_prop: property pid (with P-prefix) to require
    :param optional_props: list of other properties pids to include as
        optional
    :param lang: language code to request the item label for
    """
    optional_props = optional_props or []
    query = 'SELECT ?item ?value '
    if optional_props:
        query += '?{0} '.format(' ?'.join(optional_props))
    if lang:
        query += '?itemLabel '
    query += 'WHERE { '
    query += '?item wdt:{0} ?value . '.format(main_prop)
    for prop in optional_props:
        query += 'OPTIONAL { ?item wdt:%s ?%s } ' % (prop, prop)
    if lang:
        query += ('SERVICE wikibase:label '
                  '{ bd:serviceParam wikibase:language "%s". }' % lang)
    query += '}'
    return query