Why use Select Top 100 Percent?

后端 未结 10 2312
花落未央
花落未央 2020-11-27 15:41

I understand that prior to SQL Server 2005, you could \"trick\" SQL Server to allow use of an order by in a view definition, by also include TOP 100 PERCENT

10条回答
  •  时光说笑
    2020-11-27 16:08

    ...allow use of an ORDER BY in a view definition.

    That's not a good idea. A view should never have an ORDER BY defined.

    An ORDER BY has an impact on performance - using it a view means that the ORDER BY will turn up in the explain plan. If you have a query where the view is joined to anything in the immediate query, or referenced in an inline view (CTE/subquery factoring) - the ORDER BY is always run prior to the final ORDER BY (assuming it was defined). There's no benefit to ordering rows that aren't the final result set when the query isn't using TOP (or LIMIT for MySQL/Postgres).

    Consider:

    CREATE VIEW my_view AS
        SELECT i.item_id,
               i.item_description,
               it.item_type_description
          FROM ITEMS i
          JOIN ITEM_TYPES it ON it.item_type_id = i.item_type_id
      ORDER BY i.item_description
    

    ...

      SELECT t.item_id,
             t.item_description,
             t.item_type_description
        FROM my_view t
    ORDER BY t.item_type_description
    

    ...is the equivalent to using:

      SELECT t.item_id,
             t.item_description,
             t.item_type_description
        FROM (SELECT i.item_id,
                     i.item_description,
                     it.item_type_description
                FROM ITEMS i
                JOIN ITEM_TYPES it ON it.item_type_id = i.item_type_id
            ORDER BY i.item_description) t
    ORDER BY t.item_type_description
    

    This is bad because:

    1. The example is ordering the list initially by the item description, and then it's reordered based on the item type description. It's wasted resources in the first sort - running as is does not mean it's running: ORDER BY item_type_description, item_description
    2. It's not obvious what the view is ordered by due to encapsulation. This does not mean you should create multiple views with different sort orders...

提交回复
热议问题