- PostgreSQL Server Programming(Second Edition)
- Usama Dar Hannu Krosing Jim Mlodgenski Kirk Roybal
- 188字
- 2021-07-23 20:36:46
Custom sort orders
The last example in this chapter, is about using functions for different ways of sorting.
Say we are given a task to sort words by their vowels only, and in addition to this, to make the last vowel the most significant one when sorting. While this task may seem really complicated at first, it can be easily solved with functions:
CREATE OR REPLACE FUNCTION reversed_vowels(word text) RETURNS text AS $$ vowels = [c for c in word.lower() if c in 'aeiou'] vowels.reverse() return ''.join(vowels) $$ LANGUAGE plpythonu IMMUTABLE; postgres=# select word,reversed_vowels(word) from words order by reversed_vowels(word); word | reversed_vowels -------------+----------------- Abracadabra | aaaaa Great | ae Barter | ea Revolver | eoe (4 rows)
The best part is that you can use your new function in an index definition:
postgres=# CREATE INDEX reversed_vowels_index ON words (reversed_vowels(word)); CREATE INDEX
The system will automatically use this index whenever the reversed_vowels(word)
function is used in the WHERE
or ORDER BY
clause.
推薦閱讀
- Learning Scala Programming
- JavaScript:Functional Programming for JavaScript Developers
- SpringMVC+MyBatis快速開發與項目實戰
- DevOps for Networking
- Visual Basic程序設計與應用實踐教程
- 網絡爬蟲原理與實踐:基于C#語言
- Java程序設計:原理與范例
- HTML5+CSS3 Web前端開發技術(第2版)
- Python+Tableau數據可視化之美
- Python預測分析與機器學習
- PHP項目開發全程實錄(第4版)
- Python數據可視化之matplotlib實踐
- Kohana 3.0 Beginner's Guide
- Getting Started with Windows Server Security
- Spring Boot 2+Thymeleaf企業應用實戰