1

I couldn't find an answer to this specific to BigQuery. Basically I want to be able to count ROW_NUMBER in a query and then modify the row number with basic math operators (add, subtract, etc) without using a subquery.

I know the following code works, but to me it seems unnecessary to use a subquery just to append basic math operators

SELECT
  id,
  title,
  language,
  rn+5
FROM
(
  SELECT
    id,
    title,
    language,
    ROW_NUMBER() OVER() AS rn
  FROM [publicdata:samples.wikipedia] LIMIT 1000
)

However when I try to add the plus sign without the subquery I get an error

SELECT
  id,
  title,
  language,
  ROW_NUMBER() OVER() +5  AS rn_offset,
FROM [publicdata:samples.wikipedia] LIMIT 1000

Is what I'm trying to do possible in BigQuery without a subquery, or is my syntax in error?

Thanks, Onji

4
  • 2
    You have a trailing , before the FROM clause
    – Siyual
    Commented Jul 15, 2016 at 14:58
  • in BigQuery Legacy SQL trailing , before FROM clause is not a problem at all! Commented Jul 15, 2016 at 15:14
  • @onji I can agree with you on the fact that using subquery just to append with basic match operator can seem as unnecessary - BUT at the same time I see no practical use of your example at all! What would be reason for you to increase ROW_NUMBER() inline with row_number() itself. if there is some further use of it - it should be reflected there which most likely anyway will involve subquery. Anyway - can you give your exact practical use case? Commented Jul 15, 2016 at 15:18
  • @Siyual. Yep that was my bad, ugly code. As Mikhail said BigQuery Legacy doesn't care about the trailing comma. Still I try not to leave them in there.
    – onji
    Commented Jul 18, 2016 at 7:08

1 Answer 1

1

This is a limitation of BigQuery's legacy SQL - various computations cannot be composed without using a subselect. It is unfortunate, but unlikely to be changed at this point. This is just one example among many.

However, you can do this in standard SQL without a subquery:

SELECT
  id,
  title,
  language,
  ROW_NUMBER() OVER() +5  AS rn_offset
FROM `publicdata.samples.wikipedia` LIMIT 1000

If limitations like this annoy you while using legacy SQL, I suggest looking into using standard SQL.

1
  • This is great, I didn't know about the option to enable standard SQL. I've been hoping for Google to make BigQuery more standardised and less quirky. Thanks Danny!
    – onji
    Commented Jul 18, 2016 at 7:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.