Does a select on a view keep the order by from the view? - sql

When view is created including an ORDER BY clause, will that order be maintained when using SELECT * FROM VIEW?
Or is it necessary to state SELECT * FROM VIEW ORDER BY ?

You would need an order by on the outer query to guarantee that the rows are returned in the order you want.
If you run a select * from view query against the view without a where clause, it is likely that the rows would be returned in the order defined in the order by. But that's not something that you should depend on.

I dont believe you can create a view using order by. You need to select from the view and then order by in that statement.

Related

Can't use ORDER BY in a derived table

I am trying to select the last 20 rows of my SQL Database, but I get this error:
[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
My query is:
SELECT TOP 20 * FROM (SELECT * FROM TBArticles ORDER BY id_art DESC)
I think it's because I am using ORDER BY in this second expression... but what can I do to select the 20 last rows fixing this error?
You don't need a subquery for this:
SELECT TOP 20 *
FROM TBArticles
ORDER BY id_art DESC
The documentation is quite clear on the use of ORDER BY in subqueries:
The ORDER BY clause is not valid in views, inline functions, derived tables, and subqueries, unless either the TOP or OFFSET and FETCH clauses are also specified. When ORDER BY is used in these objects, the clause is used only to determine the rows returned by the TOP clause or OFFSET and FETCH clauses. The ORDER BY clause does not guarantee ordered results when these constructs are queried, unless ORDER BY is also specified in the query itself.
Gordon's answer is probably the most direct way to handle your requirement. However, if you wanted to use a query along the same lines as the pattern you were already using, you could use ROW_NUMBER here:
SELECT *
FROM
(
SELECT *, ROW_NUMBER() OVER (ORDER BY id_art DESC) rn
FROM TBArticles
) t
WHERE rn <= 20;
By computing a row number in the derived table, the ordering "sticks" in the same way your original query was expecting.

Order by error in create view in SQL Server

I'm trying to create this view in SQL Server:
CREATE VIEW tblSanPham_VIEW
AS
SELECT TenSP, MaDanhMuc, Mamau
FROM tblSanPham
ORDER BY MaSP DESC
I'm getting this error:
Msg 1033, Level 15, State 1, Procedure tblSanPham_VIEW, Line 6 [Batch Start Line 47]
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
SQL Server doesn't support ORDER BY inside a view. This happens to remove the possibility of a "double sort" where the view defines a sorting order then the application requests a different sort order when the view is accessed.
In fact, you can use it if you add TOP:
CREATE VIEW tblSanPham_VIEW
AS
SELECT TOP 100 PERCENT
TenSP,
MaDanhMuc,
Mamau
FROM tblSanPham
ORDER BY MaSP DESC
In this case, the view gets created without an error but if you try to pull data from it ORDER BY is completely ignored.
Try using ORDER BY clause to the queries that pull data from your view, not to the code of the view itself.
by adding a TOP clause
CREATE VIEW tblSanPham_VIEW
AS
SELECT TOP (99.9999) PERCENT TenSP,
MaDanhMuc,
Mamau
FROM tblSanPham
ORDER BY
MaSP DESC
OR if you just select from the view, without an ORDER BY clause:
CREATE VIEW tblSanPham_VIEW
AS
SELECT TenSP,
MaDanhMuc,
Mamau
FROM tblSanPham
Then:
SELECT *
FROM dbo.tblSanPham_VIEW
ORDER BY
MaSP DESC

SQL ORDER BY in SQL table returning function

so I have simple function trying to get two fields from database. I'm trying to use order by for the results however I cannot use ORDER BY in return clause.
It tells me
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
Is is it possible to use ORDER BY in RETURN statement? I would like to avoid using order by when executing the function.
CREATE FUNCTION goalsGames1 () RETURNS TABLE
AS RETURN(
SELECT MAX(goals_scored) goals,
no_games
FROM Player
GROUP BY no_games
ORDER BY no_games DESC )
One trick to skip this error is using top as it is mentioned in the error message:
CREATE FUNCTION goalsGames1 () RETURNS TABLE
AS RETURN(
SELECT Top 100 Percent MAX(goals_scored) goals,
no_games
FROM Player
GROUP BY no_games
ORDER BY no_games DESC )
I would like to avoid using order by when executing the function.
If you are using the function and want the results in a particular order, then you need to use ORDER BY.
This is quite clearly stated in the documentation:
The ORDER clause does not guarantee ordered results when a SELECT query is executed, unless ORDER BY is also specified in the query.
use order by intimes of selection your function not in times of creation
so use here in select * from goalsGames1 order by col
and your error tells you where order by is invalid
You cannot order by inside a function, the idea is to order the resultset returned by the function.
select *
from dbo.goalsGames1()
order by no_games
Even if you would order by inside the function, there is no guaranty that this ordering would be preserved when the resultset is returned. The executing query (select * from functionname) has to be responsible for setting the order, not the function or view.
Who ever receives the rows is the only one that can order them, so in this case, the select * from goalsGames1() is the receiver, and this query has to order the results.

Jet-SQL to TSQL

In MS Access 2010 I have the following code:
SELECT
[Teile-LF-Beziehungen].Lieferant,
COUNT([Teile-LF-Beziehungen].Lieferant) AS [Anz Teile],
First([Teile-LF-Beziehungen].Name) AS Name
FROM
[Teile-LF-Beziehungen]
GROUP BY
[Teile-LF-Beziehungen].Lieferant
ORDER BY
COUNT([Teile-LF-Beziehungen].Lieferant) DESC;
I want to put that query into SQL Server, because MS Access should be only the frontend.
But in SQL Server I can't use the ORDER in a view. But why? I don't understand it. The code I want to use in SQL Server:
SELECT
[Lieferant],
COUNT([Lieferant]) AS [Anz Teile],
MIN([Name]) AS [Name]
FROM
[dbo].[VIEW_Teile-LF-Beziehungen]
GROUP BY
[Lieferant]
ORDER BY
COUNT([Lieferant]) DESC;
I know it don't work. But is there any way to incur a MS Access query 1:1 to a SQL Server query (view)?
Only the outermost select can use an order by (but you might state a TOP 100 percent to trick this out). Therefore it is perfectly OK, that at VIEW does not allow this.
Many people think, that tables have kind of an implicit order (as you see the result ordered), but this is random... The next call could lead to a different sorting.
There is another way using ROW_NUMBER with OVER(ORDER BY). The result is delivered in this order and the order is guaranteed as long the orderby is sorting after unique values.
EDIT
Sorry my first attempt was to quick. The ROW_NUMBER was not allowed due to the grouping
This should work:
SELECT tbl.Lieferant
,tbl.[Anz Teile]
,tbl.Name
,ROW_NUMBER() OVER(ORDER BY tbl.[Anz Teile] DESC) AS Sort
FROM
(
SELECT [Lieferant]
,COUNT([Lieferant]) AS [Anz Teile]
,MIN([Name]) AS [Name]
FROM [dbo].[VIEW_Teile-LF-Beziehungen]
GROUP BY [Lieferant]
) AS tbl;
EDIT2
This SELECT can be placed within a VIEW, just place your CREATE VIEW YourViewName AS before the SELECT and execute. After this you'll be able to do a SELECT * FROM YourViewName to get a sorted list.
BUT
As stated in many places: The best is the outermost ORDER BY in any case!
ORDER BY doesnt work inside the view. SQL server is free to return the rows anyway he want if you dont include the order by when calling the View
So you need
SELECT *
FROM yourView
ORDER BY yourField
EDIT: Im saying if your view is
CREATE VIEW yourView AS
SELECT
[Lieferant],
COUNT([Lieferant]) AS [Anz Teile],
MIN([Name]) AS [Name]
FROM
[dbo].[VIEW_Teile-LF-Beziehungen]
GROUP BY
[Lieferant];
Then you call your View like this
SELECT *
FROM yourView
ORDER BY [Anz Teile]

How to sort within a sql view

I've created a sql view and I need to sort the results of select by using the ORDER BY on 4 fields, but I'm getting message that ORDER BY cannot be used in views unless I use TOP.
Can someone explain why TOP is needed, and does someone have a workaround for sorting in a sql view?
Thanks.
you don't need to sort a view. a view is like a table so you sort it when you select from it:
select * from yourView order by yourColumns
There is no guarantee the output of the view will be ordered
Only the outermost ORDER BY applies for result sets: not any inner ones. So only this ORDER BY can be guaranteed to work:
SELECT col1, col2, FROm MyView ORDER BY col2
You can add it to views or derived tables and it forces "intermediate materialisation" because the results have to be ordered. However, for SQL Server 2005 and above, you have to use TOP 2000000000 not TOP 100 PERCENT (except for that HF that Daniel Vassallo mentioned!)
Someone will use your view with a different order to that internally at some point too.
You can try:
CREATE VIEW View_Products
AS
SELECT ProductID, ProductName, UnitPrice, CreateDate FROM Products
Order by CreateDate DESC
OFFSET 0 ROWS
Would creating an index on the column with which you intend to sort the view help?