X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.2]) by svr1.postgresql.org (Postfix) with ESMTP id 6EFA9D1D6CC for ; Sun, 1 Feb 2004 13:35:09 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (neptune.hub.org [200.46.204.2]) (amavisd-new, port 10024) with ESMTP id 91035-02 for ; Sun, 1 Feb 2004 09:35:09 -0400 (AST) Received: from tigger.fuhr.org (tigger.fuhr.org [209.38.250.30]) by svr1.postgresql.org (Postfix) with ESMTP id A1A21D1D597 for ; Sun, 1 Feb 2004 09:35:04 -0400 (AST) Received: from winnie.fuhr.org (winnie.fuhr.org [10.1.0.1]) by tigger.fuhr.org (8.12.10/8.12.10) with ESMTP id i11DYqeS045251 (version=TLSv1/SSLv3 cipher=DHE-RSA-AES256-SHA bits=256 verify=OK); Sun, 1 Feb 2004 06:34:55 -0700 (MST) (envelope-from mfuhr@winnie.fuhr.org) Received: from winnie.fuhr.org (localhost [127.0.0.1]) by winnie.fuhr.org (8.12.10/8.12.10) with ESMTP id i11DYqYs013102; Sun, 1 Feb 2004 06:34:52 -0700 (MST) (envelope-from mfuhr@winnie.fuhr.org) Received: (from mfuhr@localhost) by winnie.fuhr.org (8.12.10/8.12.10/Submit) id i11DYpqJ013101; Sun, 1 Feb 2004 06:34:51 -0700 (MST) (envelope-from mfuhr) Date: Sun, 1 Feb 2004 06:34:51 -0700 From: Michael Fuhr To: darnold@northcoast.com Cc: pgsql-sql@postgresql.org Subject: Re: An order by question Message-ID: <20040201133451.GA13002@winnie.fuhr.org> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline X-Virus-Scanned: by amavisd-new at postgresql.org X-Archive-Number: 200402/2 X-Sequence-Number: 16693 > I need a little help on a sorting problem. Imagine a table, call it > records, that has fields: > > lastName > firstName > term > > I want to sort the records by last name, then first name, and finally by > term. This almost does what I want: > > select * from records order by lastName, firstName, term; > > However, the possible values for term are: > > 2002F > 2003S > 2003X > 2003F > > Where F is for fall, S for spring, and X for summer session. Thus, a > straight alphabetical sort doesn't give me what I want. If the year is the > same, then I want a sort with S, then X, then F for identical year. Consider storing the session in a separate field and assigning each session a value that collates in the order you want. Here's a way to order the sessions using their current format: SELECT * FROM records ORDER BY lastName, firstName, SUBSTRING(term FROM 1 FOR 4), CASE SUBSTRING(term FROM 5) WHEN 'S' THEN 1 WHEN 'X' THEN 2 ELSE 3 END; -- Michael Fuhr http://www.fuhr.org/~mfuhr/