Takeaway: When designing a database table structure, it's important to choose an efficient strategy for storing a logical Boolean that you can use in many programming environments. Find out how from this Oracle expert.

When designing a database table structure, it's important to choose an efficient strategy for storing a logical Boolean that you can use in many programming environments. (Although Oracle doesn't come with a Boolean datatype for database columns, it does have a Boolean datatype in PL/SQL.)

Any Boolean-defined column should also be properly constrained by checks to make sure that only valid values are entered at insert/update time.

create table tbool (bool char check (bool in ('N','Y'));
insert into tbool values ('N');
insert into tbool values ('Y');

The most commonly seen design is to imitate the
many Boolean-like flags that Oracle's data dictionary views use,
selecting 'Y' for true and 'N' for false. However, to interact
correctly with host environments, such as JDBC, OCCI, and other
programming environments, it's better to select 0 for false and 1 for true so it can work
correctly with the getBoolean and setBoolean functions.

We could define a Boolean as NUMBER(1);
however, in Oracle's internal number format, 0 takes 1 byte and 1
takes 2 bytes after the length byte (so it's more efficient to
store it as CHAR). Even though the character is defined as CHAR,
SQL can convert and verify against actual numbers.

create table tbool (bool char check (bool in
(0,1));
insert into tbool values(0);
insert into tbool values(1);

Here is a Java example:

import java.sql.*;

public class bool
{
    public static void main(String[] args)
throws SQLException
    {
        try
        {
           
Class.forName("oracle.jdbc.driver.OracleDriver");
        }
        catch
(ClassNotFoundException e)
        {
            System.out.println("error:
driver not in CLASSPATH");
            return;

}
        Connection conn =
DriverManager.getConnection(
           
"jdbc:oracle:oci8:@","scott","tiger");
        Statement stmt =
conn.createStatement();
        ResultSet rset =
stmt.executeQuery("select bool from tbool");
        Boolean
bool;
        while
(rset.next())
        {
            if
(rset.getBoolean(1))
               
System.out.println("bool is true");
            else
System.out.println("bool is false");
        }
        rset.close();

stmt.close();

conn.close();

}
}

Also, in OCI, OCCI, and PRO/C, if the selected
value is requested as an integer (SQLT_INT or OCCIINT), it will
automatically convert into binary 0 or 1 by the client-side
libraries, which can be used as native Boolean values.

Here is the same sample in OCCI:

#include <string>
#include <iostream>
#include <occi.h>
using namespace oracle::occi;
using namespace std;

int main(int argc,char* argv[])
{
    bool b;
    Environment* env =
Environment::createEnvironment();
    try
    {
        Connection* conn =
env->createConnection("scott","tiger");
        Statement* stmt =
conn->createStatement("select bool from tbool");
        ResultSet* rset =
stmt->executeQuery();
        rset->setDataBuffer(1,&b,OCCIINT,sizeof(bool));

while
(rset->next())
        {
            if
(b) cout << "bool was true" << endl;
            else
cout << "bool was false" << endl;
        }
        stmt->closeResultSet(rset);

conn->terminateStatement(stmt);
        env->terminateConnection(conn);

}
    catch (SQLException e)
    {
        cout <<
e.what() << endl;
    }
    Environment::terminateEnvironment(env);
    return 0;
}

By using setDataBuffer with a C++ bool value,
the correct integer value gets bound to a C++ bool. Unfortunately,
there's no getBoolean in OCCI. Therefore, it may be more portable
to use an int or char, or use rset->getInt(1) instead
of binding. (Note: In my tests, there is apparently a bug in OCCI
where using getInt(1) on a CHAR column failed unless I used
to_number(bool) or bool+0.)

When creating a Boolean data column, you should
be careful to make sure that the column is properly "nullable." If
a column with two possible values isn't constrained with NOT NULL,
then you're allowing three possible values: true, false, and unknown. This is often not
what is intended and host languages environments must deal with the
possibility that NULL is returned. Either 2-value or 3-value may be
acceptable in certain circumstances. This SQL restricts a BOOLEAN
value to 2-values only:

create table tbool (bool char not null check (bool
in (0,1));

However, Oracle SQL still requires a condition
operator, so there's no way to get around testing for the actual
value being 1 or 0, although you can hide these values in a
standardization package. For instance, see how I can reuse/expose
the keywords true and false through a PL/SQL
package:

create or replace package bool
as
    subtype bool is char;
    function false return bool;
    function true return bool;
    function val(b bool) return
varchar2;
end bool;
/
show error

create or replace package body bool
as
    function false return bool
    is
    begin
        return 0;
    end false;
    --
    function true return bool
    is
    begin
        return 1;
    end true;
    --
    function val(b bool) return varchar2
    is
    begin
        if b = true
then
            return
'true';
        end if;
        return
'false';
    end val;
end bool;
/
show error

insert into tbool values(bool.false);
insert into tbool values(bool.true);

select bool.val(bool) from tbool where bool = bool.true;

Oracle Tip: Choosing an efficient design for Boolean column values的更多相关文章

  1. Digital design之Boolean Algebra

    1. 0 and 1 (duality: 0 -- 1, · -- +) X + 0 = X, X · 1 = X X + 1 = 1, X · 0 = 0 2. Idempotent X + X = ...

  2. Oracle Applications Multiple Organizations Access Control for Custom Code

    档 ID 420787.1 White Paper Oracle Applications Multiple Organizations Access Control for Custom Code ...

  3. oracle已知会导致错误结果的bug列表(Bug Issues Known to cause Wrong Results)

    LAST UPDATE:     1 Dec 15, 2016 APPLIES TO:     1 2 3 4 Oracle Database - Enterprise Edition - Versi ...

  4. [转]Using the Microsoft Connector for Oracle by Attunity with SQL Server 2008 Integration Services

    本文转自:http://technet.microsoft.com/en-us/library/ee470675(v=sql.100).aspx SQL Server Technical Articl ...

  5. Oracle EBS - Doc

    Oracle EBS spec.: http://vianet/IT/IT%20Dept/IT%20Project%20Update2/Active%20Projects%20%20Manufactu ...

  6. sql boolean类型

    关于 MySQL 的 boolean 和 tinyint(1) boolean类型MYSQL保存BOOLEAN值时用1代表TRUE,0代表FALSE,boolean在MySQL里的类型为tinyint ...

  7. Padding Oracle Attack的一些细节与实现

    Padding Oracle Attack还是颇具威力的,ASP.NET的Padding Oracle Attack被Pwnie评为2010年最佳服务端漏洞之一.还是看 Juliano Rizzo a ...

  8. Oracle corrupt block(坏块) 详解

    转自:http://blog.csdn.net/tianlesoftware/article/details/5024966 一. 坏块说明 1.1 相关链接 在看坏块之前,先看几个相关的链接,在后面 ...

  9. Oracle composite index column ordering

    Question:  I have a SQL with multiple columns in my where clause.  I know that Oracle can only choos ...

随机推荐

  1. 038——VUE中组件之WEB开发中组件使用场景与定义组件的方式

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  2. Python+Flask+MysqL的web建设技术过程

    一.前言(个人学期总结) 个人总结一下这学期对于Python+Flask+MysqL的web建设技术过程的学习体会,Flask小辣椒框架相对于其他框架而言,更加稳定,不会有莫名其妙的错误,容错性强,运 ...

  3. 如何从MTK机器的NVRAM中获取WIFI mac地址

    在MTK的机器中,如果不用特定的工具烧写MAC地址,在开机后打开WIFI后会显示: "NVRAM WARNING: Err=0x10" 这就是没有烧写mac地址的原因,所以每次打开 ...

  4. 微信逆向工程之远程操作Mac

    远程控制指令: (功能-指令-是否开启) macbook控制: 屏幕保护-ScreenSave-开启 锁屏-LockScreen-开启 休眠-Sleep-开启 关机-Shutdown-开启 重启-Re ...

  5. BZOJ4571: [Scoi2016]美味【主席树】【贪心】

    Description 一家餐厅有 n 道菜,编号 1...n ,大家对第 i 道菜的评价值为 ai(1≤i≤n).有 m 位顾客,第 i 位顾客的期 望值为 bi,而他的偏好值为 xi .因此,第 ...

  6. kudu yum 安装

    yum 源 http://archive.cloudera.com/kudu/redhat/7/x86_64/kudu/cloudera-kudu.repo [cloudera-kudu] # Pac ...

  7. apache伪静态设置

    在网站根目录下新建一个.htaccess文件即可,编辑如下 RewriteEngine On #游戏列表详细介绍 RewriteRule ^g-([0-9]+).html$ game.php?acti ...

  8. swing版网络爬虫-丑牛迷你采集器2.0

    swing版网络爬虫-丑牛迷你采集器2.0 http://www.javacoo.com/code/704.jhtml 整合JEECMS http://bbs.jeecms.com/fabu/3186 ...

  9. 锐捷 rg-S2026f 学习笔记

    1.通过串口连接交换机: http://support.ruijie.com.cn/forum.php?mod=viewthread&tid=32250&extra=page%3D1& ...

  10. thinkphp配置rewrite模式访问时不生效 出现No input file specified解决方法

    使用thinkphp配置rewire模式的路径访问网站时, 直接复制官网的.htaccess文件的代码复制过去 1 2 3 4 5 6 <IfModule mod_rewrite.c>   ...