Need a row count after SELECT statement: what's the optimal SQL approach?

后端 未结 10 1062
悲哀的现实
悲哀的现实 2020-12-05 02:19

I\'m trying to select a column from a single table (no joins) and I need the count of the number of rows, ideally before I begin retrieving the rows. I have come to two app

相关标签:
10条回答
  • 2020-12-05 02:46

    Here are some ideas:

    • Go with Approach #1 and resize the array to hold additional results or use a type that automatically resizes as neccessary (you don't mention what language you are using so I can't be more specific).
    • You could execute both statements in Approach #1 within a transaction to guarantee the counts are the same both times if your database supports this.
    • I'm not sure what you are doing with the data but if it is possible to process the results without storing all of them first this might be the best method.
    0 讨论(0)
  • 2020-12-05 02:51

    Just to add this because this is the top result in google for this question. In sqlite I used this to get the rowcount.

    WITH temptable AS
      (SELECT one,two
       FROM
         (SELECT one, two
          FROM table3
          WHERE dimension=0
          UNION ALL SELECT one, two
          FROM table2
          WHERE dimension=0
          UNION ALL SELECT one, two
          FROM table1
          WHERE dimension=0)
       ORDER BY date DESC)
    SELECT *
    FROM temptable
    LEFT JOIN
      (SELECT count(*)/7 AS cnt,
                            0 AS bonus
       FROM temptable) counter
    WHERE 0 = counter.bonus
    
    0 讨论(0)
  • 2020-12-05 02:55

    You might want to think about a better pattern for dealing with data of this type.

    No self-prespecting SQL driver will tell you how many rows your query will return before returning the rows, because the answer might change (unless you use a Transaction, which creates problems of its own.)

    The number of rows won't change - google for ACID and SQL.

    0 讨论(0)
  • 2020-12-05 02:58
    IF (@@ROWCOUNT > 0)
    BEGIN
    SELECT my_table.my_col
      FROM my_table
     WHERE my_table.foo = 'bar'
    END
    
    0 讨论(0)
提交回复
热议问题