16

I'm using QGIS 1.8 on windows XP machine and I try to do a concatenation of several fields to label the names of my local roads in the attribute table, but I can not find the correct syntax. The first field consists of om the street, the second type of link, eg: Avenue and the third orientation, for example, East or West. Could you tell me how to write the correct syntax using the dialog box of labels based on a formula. Attached a screenshot that shows the attribute table.

enter image description here

underdark
  • 84,148
  • 21
  • 231
  • 413
Gabriel Giroux
  • 261
  • 1
  • 3
  • 7

2 Answers2

24

The concatenation operator is || (odd huh?), so you would use something like:

street || ', ' || link || ', ' || orientation

Intersperse them with any separators and static strings you like.

As @NathanW noted, this will fail if any of the fields is NULL, but you can use a fallback value in that case:

street || ', ' || CASE WHEN ("link" IS NULL) THEN '(nodata)' ELSE "link" END || ', ' || orientation

QGIS supports a helper function coalesce since version 2.0. It is there to avoid the problems of NULLs and the example would look like:

 street || ', ' || coalesce(link, '(nodata)') || ', ' || orientation
lynxlynxlynx
  • 4,247
  • 3
  • 29
  • 45
  • 2
    There is also the concat function in the dev versions. Using || doesn't handle NULL, if link is NULL the whole label is null concat doesn't have this issue. || is taken from Postgres http://www.postgresql.org/docs/9.1/static/functions-string.html – Nathan W Jul 12 '12 at 12:07
  • Looks like it doesn't support case statements directly. Is the only option without using SQL directly to create a non-NULL copy of the link column? – lynxlynxlynx Jul 12 '12 at 12:22
  • 1
    What do you mean doesn't support case statements? – Nathan W Jul 12 '12 at 12:23
  • I tried just: CASE WHEN ("link" IS NULL) THEN '(nodata)' ELSE "link" -- but it was a syntax error – lynxlynxlynx Jul 12 '12 at 12:45
  • 3
    You are missing END. The correct string is CASE WHEN ("link" IS NULL) THEN '(nodata)' ELSE "link" END – Nathan W Jul 12 '12 at 12:48
  • doh, silly me. :) Too bad it doesn't support ternary though. – lynxlynxlynx Jul 12 '12 at 13:22
  • concat in master also has that "issue". but master also has coalesce(link,'(nodata)') (shorter than CASE). – jef Jul 12 '12 at 16:20
  • 1
    ahh coalesce is the the one I meant. – Nathan W Jul 13 '12 at 12:37
3

On QGIS veriosn 2.0.1 the simple expression worked like this:

"field1" || ' (' || "field2" || ')'

desired output: field1 (field2)

Pavlarian
  • 31
  • 2