PostgresQL中的NUlls first/last功能

來源:互聯網
上載者:User

標籤:

Nulls first/last功能簡介
Nulls first/last功能主要用於order by排序子句中,影響空值Null在排序結果中的位置。簡單來說,Nulls first表示Null值在排序時一直排在所有值的前面,也就是處理order by a desc時PostgresQL執行器認為Null值大於所有值,而order by a或order by a asc時執行器認為Null值小於所有值,將Null值排在前面。Nulls last表示Null值在排序時一直排在所有值的後面,也就是處理order by a desc時PostgresQL執行器認為Null值小於所有值,而order by a或order by a asc時執行器認為Null值大於所有值,將Null值排在前面。當不指定Nulls first/last功能時,執行器預設認為Null值要大於所有值,以此為依據處理order by子句的排序結果。

Nulls first/last功能簡單展示
以下測試均為Postgres資料庫下測試,資料庫版本為9.2.2,測試系統為Linux。

普通表簡易功能展示:

Create    table  test1(a int, b int);

Insertinto test1 values(1,2);

Insertinto test1 values(3,4);

Insertinto test1 values(5);

Select * from test1 order by b desc nulls first;

a    b

5

3    4

1    2

 

Select * from test1 order by b desc nulls last;

a    b

3    4

1    2

5

 

Select *from test1 order by b desc nulls;  報錯

 

分區表簡易功能展示,注意PostgresQL資料庫建分區表的方式:

createtable test_hash(a int, b int);

createtable test_hash1(check(a>=0 and a<5)) inherits(test_hash);

createtable test_hash2(check(a>=5)) inherits(test_hash);

 

createrule test_hash_1 as on insert to test_hash where(a>=0 and a<5) do insteadinsert into test_hash1 values(NEW.a,NEW.b);

createrule test_hash_2 as on insert to test_hash where(a>=5) do instead insertinto test_hash2 values(NEW.a,NEW.b);

 

Insertinto test_hash values(1,2);

Insertinto test_hash values(3,4);

Insertinto test_hash values(5);

 

Select *from test_hash order by b desc nulls first;

a      b

5

3      4

2      2

 

Select *from test_hash order by b desc nulls last;

a      b

3      4

1      2

5

以上均是select語句中的order by子句進行的Nulls first/last功能展示,建立索引等其他需要order by子句的地方同理。這裡只是簡單的展示了一下功能,有時間會寫一些剖析PostgresQL資料庫的文章出來

PostgresQL中的NUlls first/last功能

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.