<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PostgreSQL Archives | Programming Zen</title>
	<atom:link href="https://programmingzen.com/tag/postgresql/feed/" rel="self" type="application/rss+xml" />
	<link>https://programmingzen.com/tag/postgresql/</link>
	<description>Meditations on programming, startups, and technology</description>
	<lastBuildDate>Thu, 02 Apr 2020 17:14:33 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
<site xmlns="com-wordpress:feed-additions:1">1397766</site>	<item>
		<title>Sorting Results by Specific Values in SQL with CASE</title>
		<link>https://programmingzen.com/sorting-results-by-specific-values-in-sql-with-case/</link>
					<comments>https://programmingzen.com/sorting-results-by-specific-values-in-sql-with-case/#respond</comments>
		
		<dc:creator><![CDATA[Antonio Cangiano]]></dc:creator>
		<pubDate>Wed, 01 Apr 2020 01:50:06 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[SQL]]></category>
		<guid isPermaLink="false">https://programmingzen.com/?p=2411</guid>

					<description><![CDATA[<p>In this article, I show a handy example of how to use the SQL CASE statement. Recently I rewrote the backend for my service, Any New Books, due to an Amazon API change. Generally speaking, rewriting an entire codebase is a bad idea. However, the code was quite old and the API changes rather drastic, so I took the opportunity to rewrite the whole thing in Rails 6. This service allows you to subscribe (100% for free) to categories of your choosing and then receive a weekly email for each category with a selection of newly released books. In the </p>
<p>The post <a href="https://programmingzen.com/sorting-results-by-specific-values-in-sql-with-case/">Sorting Results by Specific Values in SQL with CASE</a> appeared first on <a href="https://programmingzen.com">Programming Zen</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="has-text-align-center"><em>In this article, I show a handy example of how to use the SQL CASE statement.</em></p>



<p>Recently I rewrote the backend for my service, <a rel="noreferrer noopener" aria-label="Any New Books (opens in a new tab)" href="https://anynewbooks.com" target="_blank">Any New Books</a>, due to an Amazon API change. Generally speaking, rewriting an entire codebase is a bad idea. However, the code was quite old and the API changes rather drastic, so I took the opportunity to rewrite the whole thing in Rails 6.</p>



<p>This service allows you to subscribe (100% for free) to categories of your choosing and then receive a weekly email for each category with a selection of newly released books. </p>



<p>In the backend, the algorithm uses a few heuristics to determine how to present new books for a given category, so that the best candidates surface to the top to be manually selected by a (human) editor.</p>



<h2 class="wp-block-heading">Sorting results by specific values with CASE</h2>



<p>One of the parameters to consider is, believe it or not, whether a book&#8217;s binding is hardcover, paperback, Kindle, or audiobook. So at some point, I needed to sort results by these specific values in SQL.</p>



<p>In the backend I rely on PostgreSQL, so I used the following simple case statement:</p>



<pre class="wp-block-code"><code class="prettyprinted">SELECT *
FROM   books
ORDER  BY CASE binding
            WHEN 'Hardcover' THEN 1
            WHEN 'Paperback' THEN 2
            WHEN 'Kindle Edition' THEN 3
            WHEN 'Audiobook' THEN 4
            ELSE 5
          END</code>
</pre>



<p>This will order books placing hardcover books first, then paperbacks, then Kindle Edition ones, then audiobooks. And if a book has a binding/format that was not included in the list (e.g., MP3 CD), it will be placed last.</p>



<p>SQL CASE statements like this are quite handy and will work in the majority of modern relational databases.</p>



<h2 class="wp-block-heading">Ordering by multiple fields</h2>



<p>This is cool, but can we do if we also want independently published books (whose publisher in the database is &#8220;Independently Published&#8221;) to appear first in the list? (Hey, let&#8217;s throw a bone to the indie crowd.)</p>



<p>That has nothing to do with binding used as the condition for the CASE statement; it&#8217;s another field altogether.&nbsp;</p>



<p>Here is what we cannot do:</p>



<pre class="wp-block-code"><code class="prettyprinted">SELECT *
FROM   books
ORDER  BY publisher,
          CASE binding
            WHEN 'Hardcover' THEN 1
            WHEN 'Paperback' THEN 2
            WHEN 'Kindle Edition' THEN 3
            WHEN 'Audiobook' THEN 4
            ELSE 5
          END
</code>
</pre>



<p>I mean, that will execute. But a book published by &#8220;Acme&#8221; will appear before independently published books which is not what we want. Likewise, if we use <code>ORDER BY publisher DESC, ...</code> books published by, say, &#8220;Wrox&#8221; will appear before independently published ones. (Wrox books tend to be great but still, it&#8217;s not what we want.)</p>



<p>You might be tempted to comma separate two CASE statements, one to sort by publisher and the existing one to sort by binding. Thankfully we don&#8217;t have to do that. There is a much simpler way using a single CASE statement:</p>



<pre class="wp-block-code"><code class="prettyprinted">SELECT *
FROM   books
ORDER  BY CASE
            WHEN publisher = 'Independently Published' THEN 1
            WHEN binding = 'Hardcover' THEN 2
            WHEN binding = 'Paperback' THEN 3
            WHEN binding = 'Kindle Edition' THEN 4
            WHEN binding = 'Audiobook' THEN 5
            ELSE 6
          END
</code>
</pre>



<h2 class="wp-block-heading">The LIKE operator in a CASE statement</h2>



<p>We can even inject a LIKE operator to pick up books whose publishers contain the string &#8220;Independent&#8221;:</p>



<pre class="wp-block-code"><code class="prettyprinted">SELECT *
FROM   books
ORDER  BY CASE
            WHEN publisher LIKE '%Independent%' THEN 1
            WHEN binding = 'Hardcover' THEN 2
            WHEN binding = 'Paperback' THEN 3
            WHEN binding = 'Kindle Edition' THEN 4
            WHEN binding = 'Audiobook' THEN 5
            ELSE 6
          END
</code>
</pre>



<p>Thanks to the <code>ILIKE</code> variant, we can make the LIKE operator case insensitive:</p>



<pre class="wp-block-code"><code class="prettyprinted">SELECT *
FROM   books
ORDER  BY CASE
            WHEN publisher ILIKE '%independent%' THEN 1
            WHEN binding = 'Hardcover' THEN 2
            WHEN binding = 'Paperback' THEN 3
            WHEN binding = 'Kindle Edition' THEN 4
            WHEN binding = 'Audiobook' THEN 5
            ELSE 6
          END
</code>
</pre>



<p>There you have it!</p>



<p>This is basic stuff, no two ways about it. Lately, though, I’ve been reflecting more on the fact that what&#8217;s basic to me might not be so basic to people who are just starting out. </p>



<p>As a result, I want to share more on this blog and hope that in doing so, I will help someone, somewhere. Make sure you subscribe below if you are interested in seeing further content like this.</p>



<h2 class="wp-block-heading">The Art of PostgreSQL is amazing</h2>



<p>While we are on the topic, I cannot stress my recommendation for <a href="https://netrich--theartofpostgresql.thrivecart.com/full-edition/?ref=sorting-results">The Art of PostgreSQL</a> highly enough. It houses fantastic content for those who already have a basic understanding of SQL and wish to take their knowledge of PostgreSQL (and SQL in general) to the next level.</p>
<p>The post <a href="https://programmingzen.com/sorting-results-by-specific-values-in-sql-with-case/">Sorting Results by Specific Values in SQL with CASE</a> appeared first on <a href="https://programmingzen.com">Programming Zen</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programmingzen.com/sorting-results-by-specific-values-in-sql-with-case/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2411</post-id>	</item>
	</channel>
</rss>
