Search Results

Search found 17924 results on 717 pages for 'order by'.

Page 2/717 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Column order can matter

    - by Dave Ballantyne
    Ordinarily, column order of a SQL statement does not matter. Select a,b,c from table will produce the same execution plan as   Select c,b,a from table However, sometimes it can make a difference.   Consider this statement (maxdop is used to make a simpler plan and has no impact to the main point):   select SalesOrderID, CustomerID, OrderDate, ROW_NUMBER() over (Partition By CustomerId order by OrderDate asc) as RownAsc, ROW_NUMBER() over (Partition By CustomerId order by OrderDate Desc) as RownDesc from sales.SalesOrderHeader order by CustomerID,OrderDateoption(maxdop 1) If you look at the execution plan, you will see similar to this That is three sorts.  One for RownAsc,  one for RownDesc and the final one for the ‘Order by’ clause.  Sorting is an expensive operation and one that should be avoided if possible.  So with this in mind, it may come as some surprise that the optimizer does not re-order operations to group them together when the incoming data is in a similar (if not exactly the same) sorted sequence.  A simple change to swap the RownAsc and RownDesc columns to produce this statement : select SalesOrderID, CustomerID, OrderDate, ROW_NUMBER() over (Partition By CustomerId order by OrderDate Desc) as RownDesc , ROW_NUMBER() over (Partition By CustomerId order by OrderDate asc) as RownAsc from Sales.SalesOrderHeader order by CustomerID,OrderDateoption(maxdop 1) Will result a different and more efficient query plan with one less sort. The optimizer, although unable to automatically re-order operations, HAS taken advantage of the data ordering if it is as required.  This is well worth taking advantage of if you have different sorting requirements in one statement. Try grouping the functions that require the same order together and save yourself a few extra sorts.

    Read the article

  • Convert a post-order binary tree traversal index to an level-order (breadth-first) index

    - by strfry
    Assuming a complete binary tree, each node can be adressed with the position it appears in a given tree traversal algorithm. For example, the node indices of a simple complete tree with height 3 would look like this: breadth first (aka level-order): 0 / \ 1 2 / \ / \ 3 4 5 6 post-order dept first: 6 / \ 2 5 / \ / \ 0 1 3 4 The height of the tree and an index in the post-order traversal is given. How can i calculate the breadth first index from this information?

    Read the article

  • Need to preserve order of elements sent in JSON from Java

    - by Kush
    I'm using JSON.org APIs for Java to use JSON in my JSP webapp, I know JSONObject doesn't preserve order of elements the way they are put into it and one has to use JSONArray for that but I don't know how to use it since I need to send key and value both as received from the database, and here I'm sending data to jQuery via JSON where I need the order of data to be maintained. Following is my servlet code, where I'm getting results from the database using ORDER BY and hence I want the order to be exact as returned from the database. Also this JSON object requested using $.post method of jQuery and is used to populate dropdown on reciever page. ResultSet rs = st.executeQuery("SELECT * FROM tbl_state order by state_name"); JSONObject options = new JSONObject(); while(rs.next()) options.put(rs.getString("state_id"),rs.getString("state_name")); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(options); Thanks.

    Read the article

  • Nhibernate criteria query inserts an extra order by expression when using JoinType.LeftOuterJoin and Projections

    - by Aaron Palmer
    Why would this nhibernate criteria query produce the sql query below? return Session.CreateCriteria(typeof(FundingCategory), "fc") .CreateCriteria("FundingPrograms", "fp") .CreateCriteria("Projects", "p", JoinType.LeftOuterJoin) .Add(Restrictions.Disjunction() .Add(Restrictions.Eq("fp.Recipient.Id", recipientId)) .Add(Restrictions.Eq("p.Recipient.Id", recipientId)) ) .SetProjection(Projections.ProjectionList() .Add(Projections.GroupProperty("fc.Name"), "fcn") .Add(Projections.Sum("fp.ObligatedAmount"), "fpo") .Add(Projections.Sum("p.ObligatedAmount"), "po") ) .AddOrder(Order.Desc("fpo")) .AddOrder(Order.Desc("po")) .AddOrder(Order.Asc("fcn")) .List<object[]>(); SELECT this_.Name as y0_, sum(fp1_.ObligatedAmount) as y1_, sum(p2_.ObligatedAmount) as y2_ FROM fundingCategories this_ inner join fundingPrograms fp1_ on this_.fundingCategoryId = fp1_.fundingCategoryId left outer join projects p2_ on fp1_.fundingProgramId = p2_.fundingProgramId WHERE (fp1_.recipientId = 6 /* @p0 */ or p2_.recipientId = 6 /* @p1 */) GROUP BY this_.Name ORDER BY p2_.name asc, y1_ desc, y2_ desc, y0_ asc It is incorrectly putting the p2_name asc into the ORDER BY statement, and causing it to crash. This only happens when I use JoinType.LeftOuterJoin on my Projects criteria. Is this a known nhibernate bug? I'm using nhibernate 2.0.1.4000. Thanks for any insight.

    Read the article

  • Creating an Order Column for encrypted data

    - by SetiSeeker
    I am saving encrypted data to a database. Is there a way I can create a "hashcode" or fingerprint or checksum of the plain text data, that if I sort / order by on the "hashcode" the order would be the same as if I had saved the plain text data and perform the same sort / order by operation on it? I basically need a SOUNDEX() type function that will give me a value that will maintain the order of the plain text data. I would then save both encrypted data and the "hashcode" and when querying the data order by the "hashcode" field. I need to perform this in the application and preferably not in the SQL DB if at all possible. I am using Entity Framework and SQL 2008 and C# 4.0.

    Read the article

  • Numeric Order By In Transact SQL (Ordering As String Instead Of Int)

    - by Pyronaut
    I have an issue where I am trying to order a result set by what I believe to be a numberic column in my database. However when I get the result set, It has sorted the column as if it was a string (So alphabetically), instead of sorting it as an int. As an example. I have these numbers, 1 , 2, 3, 4, 5, 10, 11 When I order by in Transact SQL, I get back : 1, 10, 11, 2, 3, 4, 5 I had the same issue with Datagridview's a while back, And the issue was because of the sorting being done as if it was a string. I assume the same thing is happening here. My full SQL code is : SELECT TOP (12) DATEPART(YEAR, [OrderDate]) AS 'Year', DATEPART(MONTH, [OrderDate]) AS 'Month' , COUNT(OrderRef) AS 'OrderCount' FROM [Order] WHERE [Status] LIKE('PaymentReceived') OR [Status] LIKE ('Shipped') GROUP BY DATEPART(MONTH, [OrderDate]), DATEPART(YEAR, [OrderDate]) ORDER BY DATEPART(YEAR, OrderDate) DESC, DATEPART(MONTH, OrderDate) desc DO NOTE The wrong sorting only happens when I cam calling the function from Visual Studio. As in my code is : using (SqlConnection conn = GetConnection()) { string query = @"SELECT TOP (12) DATEPART(YEAR, [OrderDate]) AS 'Year', DATEPART(MONTH, [OrderDate]) AS 'Month' , COUNT(OrderRef) AS 'OrderCount' FROM [Order] WHERE [Status] LIKE('PaymentReceived') OR [Status] LIKE ('Shipped') GROUP BY DATEPART(MONTH, [OrderDate]), DATEPART(YEAR, [OrderDate]) ORDER BY DATEPART(YEAR, OrderDate) DESC, DATEPART(MONTH, OrderDate) desc"; SqlCommand command = new SqlCommand(query, conn); command.CommandType = CommandType.Text; using (SqlDataReader reader = command.ExecuteReader()) etc. When I run the statement in MSSQL server, there is no issues. I am currently using MSSQL 2005 express edition, And Visual Studio 2005. I have tried numerous things that are strewn across the web. Including using Convert() and ABS() to no avail. Any help would be much appreciated.

    Read the article

  • ORDER BY in a Sql Server 2008 view

    - by eidylon
    Hi all... we have a view in our database which has an ORDER BY in it. Now, I realize views generally don't order, because different people may use it for different things, and want it differently ordered. This view however is used for a VERY SPECIFIC use-case which demands a certain order. (It is team standings for a soccer league.) The database is Sql Server 2008 Express, v.10.0.1763.0 on a Windows Server 2003 R2 box. The view is defined as such: CREATE VIEW season.CurrentStandingsOrdered AS SELECT TOP 100 PERCENT *, season.GetRanking(TEAMID) RANKING FROM season.CurrentStandings ORDER BY GENDER, TEAMYEAR, CODE, POINTS DESC, FORFEITS, GOALS_AGAINST, GOALS_FOR DESC, DIFFERENTIAL, RANKING It returns: GENDER, TEAMYEAR, CODE, TEAMID, CLUB, NAME, WINS, LOSSES, TIES, GOALS_FOR, GOALS_AGAINST, DIFFERENTIAL, POINTS, FORFEITS, RANKING Now, when I run a SELECT against the view, it orders the results by GENDER, TEAMYEAR, CODE, TEAMID. Notice that it is ordering by TEAMID instead of POINTS as the order by clause specifies. However, if I copy the SQL statement and run it exactly as is in a new query window, it orders correctly as specified by the ORDER BY clause.

    Read the article

  • Webcast on Monday, July 22 - Discover the Key to Profitable Order Fulfillment

    - by Pam Petropoulos
    When it comes to order fulfillment, organizations are challenged by the increasing complexity of global supply chains and an explosion of order and delivery channels. Attend this webcast on Monday, July 22 and hear Steve Banker, Service Director for Supply Chain Management at ARC Advisory Group, discuss how distributed order management solutions can help companies transform their fulfillment operations to gain greater supply chain visibility, improve order profitability, and increase customer service levels and satisfaction.  Hear too from Oracle executives who will showcase examples of customers successfully using Oracle Distributed Order Orchestration. Date: Monday, July 22, 2013 Time:  1:00 p.m. EST Click here to Register Download a free copy of the ARC Advisory Research Brief on Oracle’s Distributed Order Orchestration solution and discover how Boeing, the world’s leading aerospace company, is leveraging the solution to automate their proposal and order management processes and achieve an expected 30% reduction in order cycle times. 

    Read the article

  • Order by null/not null with ICriteria

    - by Kristoffer
    I'd like to sort my result like this: First I want all rows/objects where a column/property is not null, then all where the colmn/property is null. Then I want to sort by another column/property. How can I do this with ICriteria? Do I have to create my own Order class, or can it be done with existing code? ICriteria criteria = Session.CreateCriteria<MyClass>() .AddOrder(Order.Desc("NullableProperty")) // What do I do here? IProjection? Custom Order class? .AddOrder(Order.Asc("OtherProperty"));

    Read the article

  • How to specify the order of XmlAttributes, using XmlSerializer

    - by demoncodemonkey
    XmlElement has an "Order" attribute which you can use to specify the precise order of your properties (in relation to each other anyway) when serializing using XmlSerializer. Is there a similar thing for XmlAttribute? I just want to set the order of the attributes from something like <MyType end="bob" start="joe" /> to <MyType start="joe" end="bob" /> This is just for readability, my own benefit really.

    Read the article

  • Finding C++ static initialization order problems

    - by Fred Larson
    We've run into some problems with the static initialization order fiasco, and I'm looking for ways to comb through a whole lot of code to find possible occurrences. Any suggestions on how to do this efficiently? Edit: I'm getting some good answers on how to SOLVE the static initialization order problem, but that's not really my question. I'd like to know how to FIND objects that are subject to this problem. Evan's answer seems to be the best so far in this regard; I don't think we can use valgrind, but we may have memory analysis tools that could perform a similar function. That would catch problems only where the initialization order is wrong for a given build, and the order can change with each build. Perhaps there's a static analysis tool that would catch this. Our platform is IBM XLC/C++ compiler running on AIX.

    Read the article

  • MySQL: Changing order of auto-incremented primary keys?

    - by Tom
    Hi, I have a table with a auto-incremented primary key: user_id. For a currently theoretical reason, I might need to change a user_id to be something else than it was when originally created through auto-incrementation. This means there's a possibility that the keys will not be in incremental order anymore: PK: 1 2 3 952 // changed key 4 5 6 7 I'm wondering whether this will cause problems, and whether MySQL reads something special to the incremental order of the keys, given that they should have come to existence in incremental order (which persists even when some rows are deleted). Assuming there are no associated foreignkey issues, or that these are under control, is there a problem with "messing with" the order of MySQL's autoincremented keys? Thank you.

    Read the article

  • SQL: select rows with the same order as IN clause

    - by Andrea3000
    I know that this question has been asked several times and I've read all the answer but none of them seem to completely solve my problem. I'm switching from a mySQL database to a MS Access database with MS SQL. In both of the case I use a php script to connect to the database and perform SQL queries. I need to find a suitable replacement for a query I used to perform on mySQL. I want to: perform a first query and order records alphabetically based on one of the columns construct a list of IDs which reflects the previous alphabetical order perform a second query with the IN clause applied with the IDs' list and ordered by this list. In mySQL I used to perform the last query this way: SELECT name FROM users WHERE id IN ($name_ids) ORDER BY FIND_IN_SET(id,'$name_ids') Since FIND_IN_SET is available only in mySQL and CHARINDEX and PATINDEX are not available from my php script, how can I achieve this? I know that I could write something like: SELECT name FROM users WHERE id IN ($name_ids) ORDER BY CASE id WHEN ... THEN 1 WHEN ... THEN 2 WHEN ... THEN 3 WHEN ... THEN 4 END but you have to consider that: IDs' list has variable length and elements because it depends on the first query that list can easily contains thousands of elements Have you got any hint on this? Is there a way to programmatically construct the ORDER BY CASE ... WHEN ... statement? Is there a better approach since my list of IDs can be big?

    Read the article

  • Row insertion order entity framework

    - by Wouter
    I'm using a transaction to insert multiple rows in multiple tables. For these rows I would like to add these rows in order. Upon calling SaveChanges all the rows are inserted out of order. When not using a transaction and saving changes after each insertion does keep order, but I really need a transaction for all entries.

    Read the article

  • Sqlite3 and PDO problem with ORDER BY

    - by Maenny
    Hi, I try to use the SQL statement SELECT * FROM table ORDER BY column via an PDO-Object in PHP. Problem is, that I always get an error (Call to a member function fetchall() on a non-object - that means, the query did not return a PDO-object) when using the names of all columnname EXCEPT for ID. When I query SELECT * FROM table ORDER BY ID it works. ID is the PRIMARY INTEGER KEY, all other columns are TEXT or NUMERIC, neither of them would works with the ORDER BY clause. Any ideas?

    Read the article

  • mysql ORDER BY date_time field not sorting as expected

    - by undefined
    I have a field in my database that stores the datetime that an item was added to the database. If I want to sort the items in reverse chronological order I would expect that doing ORDER by date_added DESC would do the trick. But this seems not to work. I also tried ORDER by UNIX_TIMESTAMP(date_added) but this still did not sort the results as I would expect. I also have an auto-increment field that I can use to sort items so I will use this, but I am curious as to why ORDER by datetime was not behaving as expected. any ideas?

    Read the article

  • XmlDocument SelectNodes(Xpath): Order of result

    - by crauscher
    This is an example xml from MSDN <?xml version="1.0"?> <!-- A fragment of a book store inventory database --> <bookstore xmlns:bk="urn:samples"> <book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8"> <title>Pride And Prejudice</title> </book> <book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1"> <title>The Handmaid's Tale</title> </book> <book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6"> <title>Emma</title> </book> <book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3"> <title>Sense and Sensibility</title> </book> </bookstore> When I select all book nodes using the following code, which order will these nodes have? XmlDocument doc = new XmlDocument(); doc.Load("booksort.xml"); var nodeList =doc.SelectNodes("bookstore/book"); Will the order of the items in the nodelist be the same as the order in the xml? Is this order guaranteed?

    Read the article

  • complex sql which runs extremely slow when the query has order by clause

    - by basit.
    I have following complex query which I need to use. When I run it, it takes 30 to 40 seconds. But if I remove the order by clause, it takes 0.0317 sec to return the result, which is really fast compare to 30 sec or 40. select DISTINCT media.* , username from album as album , album_permission as permission , user as user, media as media where ((media.album_id = album.album_id and album.private = 'yes' and album.album_id = permission.album_id and (permission.email = '' or permission.user_id = '') ) or (media.album_id = album.album_id and album.private = 'no' ) or media.album_id = '0' ) and media.user_id = user.user_id and media.media_type = 'video' order by media.id DESC LIMIT 0,20 The id on order by is primary key which is indexed too. So I don't know what is the problem. I also have album and album permission table, just to check if media is public or private, if private then check if user has permission or not. I was thinking maybe that is causing the issue. What if I did this in sub query, would that work better? Also can someone help me write that sub query, if that is the solution? If you can't help write it, just at least tell me. I'm really going crazy with this issue.. SOLUTION MAYBE Yes, I think sub-query would be best solution for this, because the following query runs at 0.0022 seconds. But I'm not sure if validation of an album would be accurate or not, please check. select media.*, username from media as media , user as user where media.user_id = user.user_id and media.media_type = 'video' and media.id in (select media2.id from media as media2 , album as album , album_permission as permission where ((media2.album_id = album.album_id and album.private = 'yes' and album.album_id = permission.album_id and (permission.email = '' or permission.user_id = '')) or (media.album_id = album.album_id and album.private = 'no' ) or media.album_id = '0' ) and media.album_id = media2.album_id ) order by media.id DESC LIMIT 0,20

    Read the article

  • Java: volatile guarantees and out-of-order execution

    - by WizardOfOdds
    Note that this question is solely about the volatile keyword and the volatile guarantees: it is not about the synchronized keyword (so please don't answer "you must use synchronize" for I don't have any issue to solve: I simply want to understand the volatile guarantees (or lack of guarantees) regarding out-of-order execution). Say we have an object containing two volatile String references that are initialized to null by the constructor and that we have only one way to modify the two String: by calling setBoth(...) and that we can only set their references afterwards to non-null reference (only the constructor is allowed to set them to null). For example (it's just an example, there's no question yet): public class SO { private volatile String a; private volatile String b; public SO() { a = null; b = null; } public void setBoth( @NotNull final String one, @NotNull final String two ) { a = one; b = two; } public String getA() { return a; } public String getB() { return b; } } In setBoth(...), the line assigning the non-null parameter "a" appears before the line assigning the non-null parameter "b". Then if I do this (once again, there's no question, the question is coming next): if ( so.getB() != null ) { System.out.println( so.getA().length ); } Am I correct in my understanding that due to out-of-order execution I can get a NullPointerException? In other words: there's no guarantee that because I read a non-null "b" I'll read a non-null "a"? Because due to out-of-order (multi)processor and the way volatile works "b" could be assigned before "a"? volatile guarantees that reads subsequent to a write shall always see the last written value, but here there's an out-of-order "issue" right? (once again, the "issue" is made on purpose to try to understand the semantics of the volatile keyword and the Java Memory Model, not to solve a problem).

    Read the article

  • A question about the order of pagination

    - by SpawnCxy
    Currently I'm deal with a history message page using Cakephp.And I got a problem about records' order.In the controller,codes about pagination as follows $this->paginate['Msg'] = array('order'=>'Msg.created desc'); $msgs = $this->paginate('Msg'); $this->set('historymsgs',$msgs); Then I got a page of messges like this: tom:I'm eighteen. Jerry:How old are you? tom:Tom. Jerry:what's your name? tom:Hi nice to meet you too! Jerry:Hello,nice to meet you! But what I need is the reversed order of the messages.How can I append a condition of Msg.created asc here? Thanks in advance.

    Read the article

  • "SELECT TOP", "LEFT OUTER JOIN", "ORDER BY" gives extra rows

    - by Codesleuth
    I have the following Access query I'm running through OLE DB in .NET: SELECT TOP 25 tblClient.ClientCode, tblRegion.Region FROM (tblClient LEFT OUTER JOIN tblRegion ON tblClient.RegionCode = tblRegion.RegionCode) ORDER BY tblRegion.Region There are 431 records within tblClient that have RegionCode set to NULL. For some reason, the query above returns all these 431 records instead of the first 25. If I change the query to ORDER BY tblClient.Client (the name of the client) like so: SELECT TOP 25 tblClient.ClientCode, tblRegion.Region FROM (tblClient LEFT OUTER JOIN tblRegion ON tblClient.RegionCode = tblRegion.RegionCode) ORDER BY tblClient.Client I get the expected result set of 25 records, showing a mixture of region names and NULL values. Why is it that ordering by a field retrieved through a LEFT OUTER JOIN will the TOP clause not work?

    Read the article

  • Order By Rand by Time (HQL)

    - by Felipe
    Hi all, I'm developing a web application using asp.net Mvc 2 and NHibernate, and I'm paging data (products in a category) in my page, but this data are random, so, I'm using a HQL statement link this: string hql = "from Product p where p.Category.Id=:IdCategory order by rand()"; It's working fine, but when I page, sometimes the same product appears in the first, second, etc... pages because it's order by rand(). Is there any way to make a random order by fixed by period (time internal) ? Or any solution ? thanks Cheers

    Read the article

  • Return order of MySQL SHOW COLUMNS

    - by rich
    Hey guys. Simple one this, but one I can't seem to find any information on so here goes. I need to find the columns in a specific table, which is no problem.... SHOW COLUMNS FROM tablename LIKE '%ColumnPrefix%'; But I need to know what order they will be returned, preferable by choosing to order the results ascending alphabetically. I have had no luck with using ORDER BY Field. Any ideas? Cheers!

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >