PostgreSQL 工具的相关介绍

news2025/2/23 15:06:12

1.1 psql工具

psql是PostgreSQL中的一个命令行交互式客户端工具,类似 Oracle中的命令行工具sqlplus,它允许用户交互地键入SQL语句或命 令,然后将其发送给PostgreSQL服务器,再显示SQL语句或命令的结 果。

1.2 psql的简单使用

使用“psql -l”命 令可以查看数据库:

[postgres@postgres data]$ psql -l
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-----------+----------+----------+-------------+-------------+-----------------------
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
(3 rows)

[postgres@postgres data]$ 

 也可以进入psql的命令交互输入模式使用“\l”命令查看有哪些 数据库,与使用上面的“psql -l”命令得到的结果是相同的,示例如 下:

[postgres@postgres data]$ 
[postgres@postgres data]$ su - postgres
Password: 
[postgres@postgres ~]$ psql
psql (13.9)
Type "help" for help.

postgres=# \l
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-----------+----------+----------+-------------+-------------+-----------------------
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
(3 rows)

postgres=# 

 使用“\d”命令查看表的示例如下:

postgres=# 
postgres=# create table t(id int primary key,name
postgres(# varchar(40));
CREATE TABLE
postgres=# \d
            List of relations
 Schema |    Name     | Type  |  Owner   
--------+-------------+-------+----------
 public | class       | table | postgres
 public | score       | table | postgres
 public | student     | table | postgres
 public | student_bak | table | postgres
 public | t           | table | postgres
 public | test1       | table | postgres
(6 rows)

postgres=# 

 还可以使用SQL语句“CREATE DATABASE×××”创建用户数据 库,下面是创建testdb数据库的SQL语句:

postgres=# CREATE DATABASE testdb;
CREATE DATABASE
postgres=

然后使用“\c testdb”命令连接到testdb数据库上:

postgres=# CREATE DATABASE testdb;
CREATE DATABASE
postgres=# \c testdb;
You are now connected to database "testdb" as user "postgres".
testdb=# 

下面介绍psql连接数据库的常用的方法,命令格式如下:

psql -h <hostname or ip> -p <端口> [数据库名称] [用户名称]
[postgres@postgres ~]$ psql -h 192.168.8.133 -p 5432 testdb postgres
Password for user postgres: 
psql (13.9)
Type "help" for help.

testdb=#

其中-h指定要连接的数据库所在的主机名或IP地址,-p指定连接 的数据库端口,最后两个参数分别是数据库名和用户名。

这些连接参数也可以通过环境变量指定,示例如下:

export PGDATABASE=testdb

export PGHOST=192.168.56.11

export PGPORT=5432

export PGUSER=postgres

然后运行psql,其运行结果与“psql -h 192.168.56.11 -p 5432 testdb postgres”的运行结果相同。

testdb=# exit
[postgres@postgres ~]$ export PGDATABASE=testdb
[postgres@postgres ~]$ export PGHOST=192.168.8.133
[postgres@postgres ~]$ export PGPORT=5432
[postgres@postgres ~]$ export PGUSER=postgres
[postgres@postgres ~]$ psql
Password for user postgres: 
psql (13.9)
Type "help" for help.

testdb=# 

1.3 psql 常用命令

1.3.1 “\h”命令

使用psql工具需要记住的第一个命令是“\h”,该命令用于查询 SQL语句的语法,如我们不知道如何用SQL语句创建用户,就可以执行 “\h create user”命令来查询:

testdb-# \c postgres
You are now connected to database "postgres" as user "postgres".
postgres-# 
postgres-# \h create user
Command:     CREATE USER
Description: define a new database role
Syntax:
CREATE USER name [ [ WITH ] option [ ... ] ]

where option can be:

      SUPERUSER | NOSUPERUSER
    | CREATEDB | NOCREATEDB
    | CREATEROLE | NOCREATEROLE
    | INHERIT | NOINHERIT
    | LOGIN | NOLOGIN
    | REPLICATION | NOREPLICATION
    | BYPASSRLS | NOBYPASSRLS
    | CONNECTION LIMIT connlimit
    | [ ENCRYPTED ] PASSWORD 'password' | PASSWORD NULL
    | VALID UNTIL 'timestamp'
    | IN ROLE role_name [, ...]
    | IN GROUP role_name [, ...]
    | ROLE role_name [, ...]
    | ADMIN role_name [, ...]
    | USER role_name [, ...]
    | SYSID uid

URL: https://www.postgresql.org/docs/13/sql-createuser.html

postgres-# 

使用“\h”命令可以查看各种SQL语句的语法,非常方便.

1.3.2 “\d”命令

“\d”命令的格式如下:

\d [ pattern ]
\d [ pattern ]+

该命令将显示每个匹配“pattern”(表、视图、索引、序列)的 信息,包括对象中所有的列、各列的数据类型、表空间(如果不是默 认的)和所有特殊属性(诸如“NOT NULL”或默认值等)等。唯一约 束相关的索引、规则、约束、触发器也同样会显示出来。如果关系是 一个视图,还会显示视图的定义(“匹配模式”将在下面定义)。下 面来看看该命令的具体用法。

1)如果“\d”命令后什么都不带,将列出当前数据库中的所有 表,示例如下:
postgres-# 
postgres-# \d
            List of relations
 Schema |    Name     | Type  |  Owner   
--------+-------------+-------+----------
 public | class       | table | postgres
 public | score       | table | postgres
 public | student     | table | postgres
 public | student_bak | table | postgres
 public | t           | table | postgres
 public | test1       | table | postgres
(6 rows)

postgres-# 
2)“\d”命令后面跟一个表名,表示显示这个表的结构定义,示 例如下:
postgres-# \d t
                        Table "public.t"
 Column |         Type          | Collation | Nullable | Default 
--------+-----------------------+-----------+----------+---------
 id     | integer               |           | not null | 
 name   | character varying(40) |           |          | 
Indexes:
    "t_pkey" PRIMARY KEY, btree (id)

postgres-# 
3)“\d”命令也可以用于显示索引信息,示例如下:
postgres-# \d t_pkey
        Index "public.t_pkey"
 Column |  Type   | Key? | Definition 
--------+---------+------+------------
 id     | integer | yes  | id
primary key, btree, for table "public.t"

postgres-# 
4)“\d”命令后面的表名或索引名中也可以使用通配符,如 “*”或“?”等,示例如下:
postgres-# 
postgres-# \d test?
                         Table "public.test1"
   Column   |          Type          | Collation | Nullable | Default 
------------+------------------------+-----------+----------+---------
 sidno      | integer                |           |          | 
 serialname | character varying(100) |           |          | 
Tablespace: "hrd"

postgres-# \d stu*
                        Table "public.student"
    Column    |         Type          | Collation | Nullable | Default 
--------------+-----------------------+-----------+----------+---------
 no           | integer               |           | not null | 
 student_name | character varying(40) |           |          | 
 age          | integer               |           |          | 
 class_no     | integer               |           |          | 
Indexes:
    "student_pkey" PRIMARY KEY, btree (no)

                      Table "public.student_bak"
    Column    |         Type          | Collation | Nullable | Default 
--------------+-----------------------+-----------+----------+---------
 no           | integer               |           | not null | 
 student_name | character varying(40) |           |          | 
 age          | integer               |           |          | 
 class_no     | integer               |           |          | 
Indexes:
    "student_bak_pkey" PRIMARY KEY, btree (no)

   Index "public.student_bak_pkey"
 Column |  Type   | Key? | Definition 
--------+---------+------+------------
 no     | integer | yes  | no
primary key, btree, for table "public.student_bak"

     Index "public.student_pkey"
 Column |  Type   | Key? | Definition 
--------+---------+------+------------
 no     | integer | yes  | no
primary key, btree, for table "public.student"

postgres-# 
5)使用“\d+”命令可以显示比“\d”命令的执行结果更详细的 信息,除了前面介绍的信息,还会显示所有与表的列关联的注释,以 及表中出现的OID。示例如下:
postgres-# \d+ t
                                            Table "public.t"
 Column |         Type          | Collation | Nullable | Default | Storage  | Stats target | Description 
--------+-----------------------+-----------+----------+---------+----------+--------------+-------------
 id     | integer               |           | not null |         | plain    |              | 
 name   | character varying(40) |           |          |         | extended |              | 
Indexes:
    "t_pkey" PRIMARY KEY, btree (id)
Access method: heap

postgres-#
6)匹配不同对象类型的“\d”命令如下:

·如果只想显示匹配的表,可以使用“\dt”命令。

·如果只想显示索引,可以使用“\di”命令。

·如果只想显示序列,可以使用“\ds”命令。

·如果只想显示视图,可以使用“\dv”命令。

·如果想显示函数,可以使用“\df”命令。

7)如果想显示执行SQL语句的时间,可以用“\timing”命令,示 例如下:
postgres-# \timing on
Timing is on.
postgres-#
postgres=# \d
            List of relations
 Schema |    Name     | Type  |  Owner   
--------+-------------+-------+----------
 public | class       | table | postgres
 public | score       | table | postgres
 public | student     | table | postgres
 public | student_bak | table | postgres
 public | t           | table | postgres
 public | test1       | table | postgres
(6 rows)

postgres=# select count(*) from t;
 count 
-------
     0
(1 row)

Time: 0.928 ms
postgres=# 
8)要想列出所有的schema,可以使用“\dn”命令,示例如下:

postgres=# \dn
  List of schemas
  Name  |  Owner   
--------+----------
 public | postgres
(1 row)

postgres=#

9)要想显示所有的表空间,可以用“\db”命令,示例如下:
postgres=# 
postgres=# \db
             List of tablespaces
    Name    |  Owner   |       Location       
------------+----------+----------------------
 hrd        | postgres | /opt/user_tablespace
 pg_default | postgres | 
 pg_global  | postgres | 
(3 rows)

postgres=# 

实际上,PostgreSQL中的表空间对应一个目录,放在这个表空间 中的表,就是把表的数据文件放到该表空间下。

10)要想列出数据库中的所有角色或用户,可以使用“\du”或 “\dg”命令,示例如下
postgres=# \dg
                                   List of roles
 Role name |                         Attributes                         | Member of 
-----------+------------------------------------------------------------+-----------
 malcolm   |                                                            | {}
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 test1     |                                                            | {}

postgres=# \du
                                   List of roles
 Role name |                         Attributes                         | Member of 
-----------+------------------------------------------------------------+-----------
 malcolm   |                                                            | {}
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 test1     |                                                            | {}

postgres=# 

“\du”和“\dg”命令等价。原因是,在PostgreSQL数据库中, 用户和角色是不分的。

11)“\dp”或“\z”命令用于显示表的权限分配情况,示例如 下:
postgres=# 
postgres=# \dp t
                            Access privileges
 Schema | Name | Type  | Access privileges | Column privileges | Policies 
--------+------+-------+-------------------+-------------------+----------
 public | t    | table |                   |                   | 
(1 row)

postgres=#

1.3.3 指定客户端字符集的命令

当客户端的字符编码与服务器不一致时,可能会出现乱码,可以 使用“\encoding”命令指定客户端的字符编码,如使用“\encoding gbk;”命令设置客户端的字符编码为“gbk”;使用“\encoding utf8;”命令设置客户端的字符编码为“utf8”。

1.3.4 格式化输出的\pset命令

“\pset”命令的语法如下:

\pset [option [value] ]

根据命令后面“option”和“value”的不同可以设置很多种不同 的输出格式,这里只介绍一些常用的用法。

默认情况下,psql中执行SQL语句后输出的内容是只有内边框的表 格:

postgres=# select * from class;
 no | class_name 
----+------------
  1 | 初二(1)班
  2 | 初二(2)班
  3 | 初二(3)班
  4 | 初二(4)班
(4 rows)

postgres=#

如果要像MySQL中一样输出带有内外边框的表格内容,可以用命令 “\pset boder 2”来实现,示例如下:

postgres=# \pset border 2 
Border style is 2.
postgres=# select * from class;
+----+------------+
| no | class_name |
+----+------------+
|  1 | 初二(1)班  |
|  2 | 初二(2)班  |
|  3 | 初二(3)班  |
|  4 | 初二(4)班  |
+----+------------+
(4 rows)

postgres=#

当然也可以用“\pset boder 0”命令输出不带任何边框的内容, 示例如下:

postgres=# \pset border 0
Border style is 0.
postgres=# select * from class;
no class_name 
-- ----------
 1 初二(1)班
 2 初二(2)班
 3 初二(3)班
 4 初二(4)班
(4 rows)

postgres=# 

综上所述,“\pset”命令设置边框的用法如下。

·\pset border 0:表示输出内容无边框。

·\pset border 1:表示输出内容只有内边框。

·\pset border 2:表示输出内容内外都有边框。

psql中默认的输出格式是“\pset border 1”。

不管输出的内容加不加边框,内容本身都是对齐的,是为增强数 据的可读性而专门格式化过的,而有时我们需要把命令的结果输出为 其他程序可以读取的文件,如以逗号分隔或以Tab分隔的文本文件,这 时就需要用到“\pset format unaligned”命令了,示例如下:

postgres=# 
postgres=# \pset format unaligned
Output format is unaligned.
postgres=# select * from class;  
no|class_name
1|初二(1)班
2|初二(2)班
3|初二(3)班
4|初二(4)班
(4 rows)
postgres=# 

默认分隔符是“|”,我们可以用命令“\pset fieldsep”来设置 分隔符,如改成Tab分隔符的方法如下:

postgres=# 
postgres=# \pset fieldsep '\t'
Field separator is "    ".
postgres=# select * from class;
no      class_name
1       初二(1)班
2       初二(2)班
3       初二(3)班
4       初二(4)班
(4 rows)
postgres=#

实际使用时,我们需要把SQL命令输出到一个文件中,而不是屏幕 上,这时可以用“\o”命令指定一个文件,然后再执行上面的SQL命 令,执行结果就会输出到这个文件中,示例如下:

1.3.5 "\x"命令

[pgadmin@postgres ~]$ su - postgres
Password: 
[postgres@postgres ~]$ psql
psql (13.9)
Type "help" for help.

postgres=# 
postgres=# \x
Expanded display is on.
postgres=# select * from pg_stat_activity;
-[ RECORD 1 ]----+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------
datid            | 
datname          | 
pid              | 114863
leader_pid       | 
usesysid         | 
usename          | 
application_name | 
client_addr      | 
client_hostname  | 
client_port      | 
backend_start    | 2023-04-28 15:43:58.433282+08
xact_start       | 
query_start      | 
state_change     | 
wait_event_type  | Activity
wait_event       | AutoVacuumMain
state            | 
backend_xid      | 
backend_xmin     | 
query            | 
backend_type     | autovacuum launcher
-[ RECORD 2 ]----+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------
datid            | 
datname          | 
pid              | 114865
leader_pid       | 
usesysid         | 10
usename          | postgres
application_name | 
client_addr      | 
client_hostname  | 
client_port      | 
backend_start    | 2023-04-28 15:43:58.434019+08
xact_start       | 
query_start      | 
state_change     | 
wait_event_type  | Activity
wait_event       | LogicalLauncherMain
state            | 
backend_xid      | 
backend_xmin     | 
query            | 
backend_type     | logical replication launcher
-[ RECORD 3 ]----+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------
datid            | 14386
datname          | postgres
pid              | 114868
leader_pid       | 
usesysid         | 10
usename          | postgres
application_name | psql
client_addr      | 
--More--

如果数据行太长出现折行,就可以使用这里介绍的“\x”命令将 其拆分为多行显示。这与MySQL中命令后加“\G”的功能类似。

1.3.6 执行存储在外部文件中的SQL命令

1.3.7 编辑命令

编辑命令“\e”可以用于编辑文件,也可用于编辑系统中已存在 的函数或视图定义,下面来举例说明此命令的使用方法。 输入“\e”命令后会调用一个编辑器,在Linux下通常是Vi,当 “\e”命令不带任何参数时则是生成一个临时文件,前面执行的最后 一条命令会出现在临时文件中,当编辑完成后退出编辑器并回到psql 中时会立即执行该命令:

如果“\ef”后面跟一个函数名,则函数定义的内容会出现在Vi编 辑器中,当编辑完成后按“wq:”保存并退出,再输入“;”就会执行 所创建函数的SQL语句。

同样输入“\ev”且后面不跟任何参数时,在Vi中会出现一个创建 视图的模板:

也可以编辑已存在的视图的定义,只需在“\ev”命令后面跟视图 的名称即可。 “\ef”和“\ev”命令可以用于查看函数或视图的定义,当然用 户需要注意,退出Vi后,要在psql中输入“\reset”来清除psql的命 令缓冲区,防止误执行创建函数和视图的SQL语句,

1.3.8  输出信息的“\echo”命令

“\echo”命令用于输出一行信息,示例如下:

此命令通常用于在使用.sql脚本的文件中输出提示信息。 比如,某文件“a.sql”有如下内容:

\echo =========================================

select * from class;

\echo =========================================

运行a.sql脚本:

postgres=# \i a.sql
==================================================================
-[ RECORD 1 ]---------
no         | 1
class_name | 初二(1)班
-[ RECORD 2 ]---------
no         | 2
class_name | 初二(2)班
-[ RECORD 3 ]---------
no         | 3
class_name | 初二(3)班
-[ RECORD 4 ]---------
no         | 4
class_name | 初二(4)班

==================================================================
postgres=# 

 1.3.9 更多其他的命令可以用“\?”命令来显示,示例如下:

postgres=# 
postgres=# \?
General
  \copyright             show PostgreSQL usage and distribution terms
  \crosstabview [COLUMNS] execute query and display results in crosstab
  \errverbose            show most recent error message at maximum verbosity
  \g [(OPTIONS)] [FILE]  execute query (and send results to file or |pipe);
                         \g with no arguments is equivalent to a semicolon
  \gdesc                 describe result of query, without executing it
  \gexec                 execute query, then execute each value in its result
  \gset [PREFIX]         execute query and store results in psql variables
  \gx [(OPTIONS)] [FILE] as \g, but forces expanded output mode
  \q                     quit psql
  \watch [SEC]           execute query every SEC seconds

Help
  \? [commands]          show help on backslash commands
  \? options             show help on psql command-line options
  \? variables           show help on special variables
  \h [NAME]              help on syntax of SQL commands, * for all commands

Query Buffer
  \e [FILE] [LINE]       edit the query buffer (or file) with external editor
  \ef [FUNCNAME [LINE]]  edit function definition with external editor
  \ev [VIEWNAME [LINE]]  edit view definition with external editor
  \p                     show the contents of the query buffer
  \r                     reset (clear) the query buffer
  \s [FILE]              display history or save it to file
  \w FILE                write query buffer to file

Input/Output
  \copy ...              perform SQL COPY with data stream to the client host
  \echo [-n] [STRING]    write string to standard output (-n for no newline)
  \i FILE                execute commands from file
  \ir FILE               as \i, but relative to location of current script
  \o [FILE]              send all query results to file or |pipe
  \qecho [-n] [STRING]   write string to \o output stream (-n for no newline)
  \warn [-n] [STRING]    write string to standard error (-n for no newline)

Conditional
  \if EXPR               begin conditional block
  \elif EXPR             alternative within current conditional block
  \else                  final alternative within current conditional block
  \endif                 end conditional block

Informational
  (options: S = show system objects, + = additional detail)
  \d[S+]                 list tables, views, and sequences
  \d[S+]  NAME           describe table, view, sequence, or index
  \da[S]  [PATTERN]      list aggregates
  \dA[+]  [PATTERN]      list access methods
  \dAc[+] [AMPTRN [TYPEPTRN]]  list operator classes
  \dAf[+] [AMPTRN [TYPEPTRN]]  list operator families
  \dAo[+] [AMPTRN [OPFPTRN]]   list operators of operator families
  \dAp[+] [AMPTRN [OPFPTRN]]   list support functions of operator families
  \db[+]  [PATTERN]      list tablespaces
  \dc[S+] [PATTERN]      list conversions
  \dC[+]  [PATTERN]      list casts
--More--

1.4 psql的使用技巧

psql最常用的使用技巧,如历史命令和补全技巧、关 闭自动提交功能、获得快捷命令实际的SQL,以便学习数据库的系统表 等

1.4.1 历史命令与补全功能

可以使用上下方向键把以前使用过的命令或SQL语句调出来,连续 单击两次Tab键表示把命令补全或给出输入提示:

postgres=# 
postgres=# \d
\d     \dA    \dAf   \dAp   \dc    \dd    \ddp   \des   \deu   \df    \dFd   \dFt   \di    \dL    \dn    \dO    \dP    \dPt   \dRp   \ds    \dt    \du    \dx    
\da    \dAc   \dAo   \db    \dC    \dD    \dE    \det   \dew   \dF    \dFp   \dg    \dl    \dm    \do    \dp    \dPi   \drds  \dRs   \dS    \dT    \dv    \dy    
postgres=# 
postgres=# \d t
t       test1   t_pkey  
postgres=# \d x

postgres=# \d s
score             student           student_bak       student_bak_pkey  student_pkey      
postgres=#

如果在已运行的psql中显示了某个命令实际执行的SQL语句后又想 关闭此功能,该怎么办?这时可以使用“\set ECHO_HIDDEN on|off” 命令,示例如下:

[postgres@postgres ~]$ 
[postgres@postgres ~]$ psql postgres
psql (13.9)
Type "help" for help.

postgres=# \dn
  List of schemas
  Name  |  Owner   
--------+----------
 public | postgres
(1 row)

postgres=#  \set ECHO_HIDDEN on
postgres=# \dn
********* QUERY **********
SELECT n.nspname AS "Name",
  pg_catalog.pg_get_userbyid(n.nspowner) AS "Owner"
FROM pg_catalog.pg_namespace n
WHERE n.nspname !~ '^pg_' AND n.nspname <> 'information_schema'
ORDER BY 1;
**************************

  List of schemas
  Name  |  Owner   
--------+----------
 public | postgres
(1 row)

postgres=#

1.5  本章将详细讲解PostgreSQL数据库支持的各种数据类型及其与其 他数据库的差异。

1.5.1 数据类型的分类

为了提高SQL的兼容性,部分数据类型还有很多别名,如integer 类型,可以用int、int4表示,smallint也可以用int2表示;char varying(n)可以用varchar(n)表示,numeric(m,n)也可以用 decimal(m,n)表示,等等。

1.5.2 数据类型的输入与转换

对于一些简单的数据类型,如数字或字符串,使用一般的方法输 入就可以了,示例如下:

postgres=# 
postgres=# select 1, 1.1421, 'hello world';
 ?column? | ?column? |  ?column?   
----------+----------+-------------
        1 |   1.1421 | hello world
(1 row)

postgres=#

对于复杂的数据类型,可以按照“类型名”加上单引号括起来的 类型值格式来输入,示例如下:

postgres=# select bit '11110011';
   bit    
----------
 11110011
(1 row)

postgres=#

实际上所有的数据类型(包括简单的数据类型)都可以使用上面 的输入方法,示例如下:

postgres=# select int '1' + int '2';
 ?column? 
----------
        3
(1 row)

postgres=#

PostgreSQL支持用标准SQL的数据类型转换函数CAST来进行数据类 型转换,示例如下:

postgres=# select CAST('5' as int),CAST('2014-07-17' as date);
 int4 |    date    
------+------------
    5 | 2014-07-17
(1 row)

postgres=#

此外,PostgreSQL中还有一种更简捷的类型转换方式,即双冒号 方式,示例如下:

postgres=# select '5'::int,'2014-07-17'::date;
 int4 |    date    
------+------------
    5 | 2014-07-17
(1 row)

postgres=#

在PostgreSQL中可以使用上面介绍的这两种数据类型转换方式输 入各种类型的数据。

1.5.3 布尔类型介绍

postgres=# CREATE TABLE t (id int, col1 boolean, col2 text);
ERROR:  relation "t" already exists
postgres=# drop table t;
DROP TABLE
postgres=# CREATE TABLE t (id int, col1 boolean, col2 text);
CREATE TABLE
postgres=# INSERT INTO t VALUES (1,TRUE, 'TRUE');
INSERT 0 1
postgres=# INSERT INTO t VALUES (2,FALSE, 'FALSE');
INSERT 0 1
postgres=# INSERT INTO t VALUES (3,tRue, 'tRue');
INSERT 0 1
postgres=# INSERT INTO t VALUES (4,fAlse, 'fAlse');
INSERT 0 1
postgres=# INSERT INTO t VALUES (5,'tRuE', '''tRuE''');
INSERT 0 1
postgres=# INSERT INTO t VALUES (6,'fALsE', '''fALsE''');
INSERT 0 1
postgres=# INSERT INTO t VALUES (7,'true', '''true''');
INSERT 0 1
postgres=# INSERT INTO t VALUES (8,'false', '''false''');
INSERT 0 1
postgres=# INSERT INTO t VALUES (9,'t', '''t''');
INSERT 0 1
postgres=# INSERT INTO t VALUES (10,'f', '''f''');
INSERT 0 1
postgres=# INSERT INTO t VALUES (11,'y', '''y''');
INSERT 0 1
postgres=# INSERT INTO t VALUES (12,'n', '''n''');
INSERT 0 1
postgres=# INSERT INTO t VALUES (13,'yes', '''yes''');
INSERT 0 1
postgres=# INSERT INTO t VALUES (14,'no', '''no''');
INSERT 0 1
postgres=# INSERT INTO t VALUES (15,'1', '''1''');
INSERT 0 1
postgres=# INSERT INTO t VALUES (16,'0', '''0''');
INSERT 0 1
postgres=# select * from t;
 id | col1 |  col2   
----+------+---------
  1 | t    | TRUE
  2 | f    | FALSE
  3 | t    | tRue
  4 | f    | fAlse
  5 | t    | 'tRuE'
  6 | f    | 'fALsE'
  7 | t    | 'true'
  8 | f    | 'false'
  9 | t    | 't'
 10 | f    | 'f'
 11 | t    | 'y'
 12 | f    | 'n'
 13 | t    | 'yes'
 14 | f    | 'no'
 15 | t    | '1'
 16 | f    | '0'
(16 rows)

postgres=# select * from t where col1;
 id | col1 |  col2  
----+------+--------
  1 | t    | TRUE
  3 | t    | tRue
  5 | t    | 'tRuE'
  7 | t    | 'true'
  9 | t    | 't'
 11 | t    | 'y'
 13 | t    | 'yes'
 15 | t    | '1'
(8 rows)

postgres=# select * from t where not col1;
 id | col1 |  col2   
----+------+---------
  2 | f    | FALSE
  4 | f    | fAlse
  6 | f    | 'fALsE'
  8 | f    | 'false'
 10 | f    | 'f'
 12 | f    | 'n'
 14 | f    | 'no'
 16 | f    | '0'
(8 rows)

postgres=# 

1.5.4 布尔类型的操作符

SQL使用三值的布尔逻辑:TRUE、FALSE和NULL,其中NULL代表 “未知”。

操作符AND和OR左右两边的操作是可以互相交换的,也就是说, “a AND b”结果与“b AND a”的结果是相同的。

布尔类型可以使用“IS”这个比较运算符,具体如下:

·expression IS TRUE。

·expression IS NOT TRUE。

·expression IS FALSE。

·expression IS NOT FALSE。

·expression IS UNKNOWN。

·expression IS NOT UNKNOWN。

1.5.5 数值类型

数值类型是最常用的几种数据类型之一,分为整型、浮点型、精 确小数等类型,

整数类型有3种:smallint、int、bigint,注意,PostgreSQL中 没有MySQL中的tinyint(1字节)、mediumint(3字节)这两种类型, 也没有MySQL中的unsigned类型。 常用的数据类型是int(或integer),因为它提供了在范围、存 储空间、性能之间的最佳平衡。一般只有在磁盘空间紧张的时候才使 用smallint类型。通常,只有integer类型的取值范围不够时才使用 bigint类型,因为前者的执行速度绝对快得多。 SQL只声明了整数类型integer(或int)和smallint。int与 integer和int4是等效的,int2与smallint是等效的,bigint与int8是 等效的。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1159296.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Django之FBV和CBV

一、FBV与CBV 在我们日常学习Django中&#xff0c;都是用的FBV&#xff08;function base views&#xff09;方式&#xff0c;就是在视图中用函数处理各种请求。而CBV&#xff08;class base view&#xff09;则是通过类来处理请求。 Python是一个面向对象的编程语言&#xff0…

LLM增强

从公众号转载&#xff0c;关注微信公众号掌握更多技术动态 --------------------------------------------------------------- 一、增强语言大模型基础 1.大语言模型存在的不足 存 在 “ 幻 觉 ” &#xff0c; 容 易 一 本 正 经 胡 说 八 道提 示 直 接 决 定 回 复 质 量…

Django实战项目-学习任务系统-自定义URL拦截器

接着上期代码框架&#xff0c;6个主要功能基本实现&#xff0c;剩下的就是细节点的完善优化了。 首先增加URL拦截器&#xff0c;你不会希望没有登录用户就可以进入用户主页各种功能的&#xff0c;所以增加URL拦截器可以解决这个问题。 Django框架本身也有URL拦截器&#xff0…

链表的引入

什么是链表 链表一种线性的数据结构&#xff0c;通过指针将一个个零散的内存块连接起来&#xff0c;链表的每个内存块称为结点。结构体指针在这里得到了充分的利用。 为什么要使用链表 链表可以动态的进行存储分配&#xff0c;也就是说&#xff0c;链表是一个功能极为强大的数…

3.13每日一题(分部积分求不定积分)

关键在于看出两类不同类型函数的乘积&#xff0c;要把三角和对数以外的凑到dx上&#xff0c;然后分部积分 注&#xff1a; arctan根号x 的求导为复合求导 根号x分之一的原函数为2*根号x

纳米银线 纳米银纳米线 平均直径: 50-100nm

&#xff08;西&#xff09;纳米银线 &#xff08;安&#xff09;含量&#xff08;%&#xff09;&#xff1a;99.9 &#xff08;瑞&#xff09;平均直径: 50-100nm &#xff08;20nm 30nm 60nm &#xff09; &#xff08;禧&#xff09;长度&#xff1a;10um …

VBA技术资料MF77:组合所选范围中的所有形状

我给VBA的定义&#xff1a;VBA是个人小型自动化处理的有效工具。利用好了&#xff0c;可以大大提高自己的工作效率&#xff0c;而且可以提高数据的准确度。我的教程一共九套&#xff0c;分为初级、中级、高级三大部分。是对VBA的系统讲解&#xff0c;从简单的入门&#xff0c;到…

照片如何打包?三个方法轻松搞定!

照片打包是一种有效的管理方式&#xff0c;可以提高工作效率、保护照片安全、节省存储空间等。那么如何简单快速地打包照片呢&#xff1f;下面介绍了三种方法~ 方法一&#xff1a;使用嗨格式压缩大师 1、在电脑上打开【嗨格式压缩大师】&#xff0c;点击软件首界面的【图片压缩…

知了汇智为成都理工大学物联网专业学子开展项目实训

随着数字化产业的发展以及产业数字化转型的深入&#xff0c;产业对数字人才的需求也在发生变化。为了培养适应市场需求的高素质物联网专业人才&#xff0c;11月14日&#xff0c;知了汇智携手成都理工大学&#xff0c;为2021级物联网专业学生带来一场别开生面的校内项目实训。 成…

python文件的操作以及简易shadow文件密码破解器

python文件对象以及简易shadow文件密码破解器 文章目录 python文件对象以及简易shadow文件密码破解器文件对象的方法 打开文件关闭文件文件读取文件指针的刷新文件迭代写入文件write()writelines() 案例shawod密码破解脚本 文件对象的方法 常用函数功能f open(‘PATH’)打…

golang工程——opentelemetry简介、架构、概念、追踪原理

opentelemetry 简介 OpenTelemetry&#xff0c;简称OTel&#xff0c;是一个与供应商无关的开源可观测性框架&#xff0c;用于检测、生成、收集和导出 遥测数据&#xff0c;如轨迹、度量、日志。OTel的目标是提供一套标准化的供应商无关SDK、API和工具&#xff0c;用于接 收、…

有哪些项目适合程序员业余时间做,并且短期内能赚点小钱?

要我说&#xff0c;程序员赚点小钱就别指望着自己搞个大项目了。 这几年的市场环境不好&#xff0c;如果你没点家底的话&#xff0c;打工攒的那点积蓄让你创业&#xff0c;一不小心就会血本无归。 对于程序员来说&#xff0c;最合适的还是给别人打工&#xff01;低风险稳定回款…

盗版gpt去广告

一. 内容简介 盗版gpt去广告 二. 软件环境 2.1 Tampermonkey 三.主要流程 3.1 创建javascript脚本 点击添加新脚本 就是在 (function() {use strict;// 在这编写自己的脚本 })();脚本&#xff0c;含解析 // UserScript // name 盗版gpt去广告 // namespace …

亿咖通·天穹Pro行泊一体智能驾驶计算平台正式量产

全球出行科技公司亿咖通科技宣布&#xff0c;旗下首款智能驾驶计算平台——亿咖通•天穹Pro行泊一体智能驾驶计算平台&#xff08;以下简称“该平台”&#xff09;已向车企正式量产交付。作为亿咖通科技在智能驾驶领域的全新突破&#xff0c;亿咖通•天穹Pro智能驾驶计算平台以…

Centos7安装Docker,安装DockerCompose(集群化部署),Docker私服镜像仓库

0.安装Docker Docker 分为 CE 和 EE 两大版本。CE 即社区版&#xff08;免费&#xff0c;支持周期 7 个月&#xff09;&#xff0c;EE 即企业版&#xff0c;强调安全&#xff0c;付费使用&#xff0c;支持周期 24 个月。 Docker CE 分为 stable test 和 nightly 三个更新频道…

element-plus的el-tag标签关闭标签时的高亮显示逻辑

1.tag 实战步骤 首页的tag一开始就会存在&#xff0c;而且是不能进行删除的 当点击左侧栏的时候,如果tag没有该菜单名称则新增&#xff0c;如果已经有了那么当前tag背景为蓝色。 删除当前tag&#xff0c;如果是最后一个&#xff0c;那么路由调整到它前面那个标签并且背景变蓝…

LV.12 D13 UART实验 学习笔记

一、UART帧格式详解 UART Universal Asynchronous Receiver Transmitter 即 通用异步收发器&#xff0c;是一种通用的串行、异步通信总线 该总线有两条数据线&#xff0c;可以实现全双工的发送和接收&#xff0c;在嵌入式系统中常用于主机与辅助设备之间的通信。 通…

奇淫技巧系列之第四篇:如何搜索Jar包中的xml文件

大神链接&#xff1a;作者有幸结识技术大神孙哥为好友&#xff0c;获益匪浅。现在把孙哥视频分享给大家。 孙哥链接&#xff1a;孙哥个人主页 作者简介&#xff1a;一个颜值99分&#xff0c;只比孙哥差一点的程序员 本专栏简介&#xff1a;话不多说&#xff0c;让我们一起干翻J…

索引创建的原则

索引的创建是数据库优化中非常重要的一部分&#xff0c;正确创建索引可以大大提高查询效率。以下是一些创建索引时需要考虑的原则&#xff1a; 根据查询频率创建索引&#xff1a; 频繁用于检索的列&#xff1a; 那些频繁用于查询的列或经常出现在 WHERE、JOIN、ORDER BY 和 GR…

A股风格因子看板(2023.10 第14期)

该因子看板跟踪A股风格因子&#xff0c;该因子主要解释沪深两市的市场收益、刻画市场风格趋势的系列风格因子&#xff0c;用以分析市场风格切换、组合风格暴露等。 今日为该因子跟踪第14期&#xff0c;指数组合数据截止日2023-09-30&#xff0c;要点如下 近1年A股风格因子检验统…