PostgreSQL 7.2 Tutorial The PostgreSQL Global Development Group PostgreSQL 7.2 Tutorial by
- 格式:pdf
- 大小:234.88 KB
- 文档页数:35
PostgreSQL数据库培训PostgreSQL使用常见的客户端/服务器的模式。
一次PostgreSQL 会话由下列相关的进程(程序)组成:服务器进程它管理数据库文件,接受来自客户端应用与数据库的连接,并且代表客户端在数据库上执行操作。
数据库服务器程序叫postgres。
客户端应用客户端应用可能本身就是多种多样的:它们可以是一个字符界面的工具,也可以是一个图形界面的应用,或者是一个通过访问数据库来显示网页的web 服务器,或者是一个特殊的数据库管理工具。
一些客户端应用是和PostgreSQL发布一起提供的,但绝大部分是用户开发的。
PostgreSQL服务器可以处理来自客户端的多个并发连接。
因此,它为每个连接启动(“forks”)一个新的进程。
从这个时候开始,客户端和新服务器进程就不再经过最初的postgres进程进行通讯。
因此,主服务器总是在运行,等待客户端连接,而客户端及其相关联的服务器进程则是起起停停。
一、数据库连接例子:psql -h 192.168.100.160 -p 10000 -d bcstream_data-U stream -W Usage:psql[OPTION]... [DBNAME [USERNAME]]General options:-c, --command=COMMAND run only single command (SQL or internal) and exit-d, --dbname=DBNAME database name to connect to (default: "rdbdba")-f, --file=FILENAME execute commands from file, then exit -l, --list list available databases, then exit-?, --help show this help, then exitConnection options:-h, --host=HOSTNAME database server host or socket directory (default: "local socket")-p, --port=PORT database server port (default: "5432")-U, --username=USERNAME database user name (default: "rdbdba")-w, --no-password never prompt for password-W, --password force password prompt (should happen automatically)二、对象创建1、创建用户及数据库CREATE USER streamWITH PASSWORD '1qaz!QAZ';CREATE DATABASE bcstream_data WITH OWNER=stream TEMPLATE=template0 ENCODING='UTF8';说明:●用户与角色说明在PG数据库中用户与角色为同一概念。
postgresql教程PostgreSQL是一个开源的关系数据库管理系统(RDBMS),它的目标是成为最先进的开源数据库,并支持许多标准SQL 功能以及一些不同的高级功能。
本教程将向您介绍PostgreSQL的基本概念和用法。
我们将从安装和设置开始,然后逐步深入了解表、视图、索引、事务和查询等主题。
第一部分:安装和设置在本部分中,我们将向您介绍如何下载、安装和设置PostgreSQL数据库。
我们还将介绍一些基本概念和术语,如数据库、表和列。
1. 安装PostgreSQL:在本节中,我们将向您展示如何从官方网站或其他来源下载并安装PostgreSQL。
2. 设置数据库连接:在本节中,我们将介绍如何设置和配置数据库连接,包括创建用户、设置密码和分配权限等内容。
3. 创建数据库和表:在本节中,我们将介绍如何创建数据库和表,并向您展示一些常用的数据类型和约束。
第二部分:表和视图在本部分中,我们将更详细地介绍表格和视图的概念,并向您展示如何使用它们来存储和查询数据。
1. 创建和修改表格:在本节中,我们将介绍如何创建新的表格,并向您展示如何修改和删除现有的表格。
2. 数据类型和约束:在本节中,我们将深入了解不同的数据类型和约束,并向您展示如何使用它们来保证数据的完整性和一致性。
3. 视图和触发器:在本节中,我们将向您展示如何创建和使用视图和触发器,以及如何利用它们来简化复杂的查询和操作。
第三部分:索引和查询优化在本部分中,我们将介绍索引和查询优化的概念,并向您展示如何使用索引来提高查询性能。
1. 索引的概念和类型:在本节中,我们将介绍不同类型的索引,如B-tree、哈希和GiST索引,并向您展示如何创建和使用它们。
2. 查询优化和性能调优:在本节中,我们将介绍一些常见的查询优化技术,如查询计划、索引优化和统计信息收集等。
3. 复杂查询和连接:在本节中,我们将向您展示如何编写复杂的查询,包括多表连接、子查询和聚合等。
tgreSQL学习手册(五) 函数和操作符阿里云携手开源中国众包平台发布百万悬赏项目»一、逻辑操作符:常用的逻辑操作符有:AND、OR和NOT。
其语义与其它编程语言中的逻辑操作符完全相同。
二、比较操作符:下面是PostgreSQL中提供的比较操作符列表:操作符描述<小于>大于<=小于或等于>=大于或等于=等于!=不等于比较操作符可以用于所有可以比较的数据类型。
所有比较操作符都是双目操作符,且返回boolean类型。
除了比较操作符以外,我们还可以使用BETWEEN语句,如:a BETWEEN x AND y 等效于 a >= x AND a <= ya NOT BETWEEN x AND y 等效于 a < x OR a > y三、数学函数和操作符:下面是PostgreSQL中提供的数学操作符列表:操作符描述例子结果+加 2 + 35-减 2 - 3-1*乘 2 * 36/除 4 / 22%模 5 % 41^幂 2.0 ^ 3.08|/平方根|/ 25.05||/立方根||/ 27.03!阶乘 5 !120!!阶乘!! 5120@绝对值@ -5.05&按位AND91 & 1511|按位OR32 | 335#按位XOR17 # 520~按位NOT~1-2<<按位左移 1 << 416>>按位右移8 >> 22按位操作符只能用于整数类型,而其它的操作符可以用于全部数值数据类型。
按位操作符还可以用于位串类型bit和bit varying,下面是PostgreSQL中提供的数学函数列表,需要说明的是,这些函数中有许多都存在多种形式,区别只是参数类型不同。
除非特别指明,任何特定形式的函数都返回和它的参数相同的数据类型。
函数返回类型描述例子结果abs(x)绝对值abs(-17.4)17.4 cbrt(double)立方根cbrt(27.0)3ceil(double/numeric)不小于参数的最小的整数ceil(-42.8)-42degrees(double) 把弧度转为角度degrees(0.5)28.6478897565412 exp(double/numeric)自然指数exp(1.0) 2.71828182845905 floor(double/numeric)不大于参数的最大整数floor(-42.8)-43ln(double/numeric)自然对数ln(2.0)0.693147180559945 log(double/numeric)10为底的对数log(100.0)2log(b numeric,x numeric)numeric指定底数的对数log(2.0, 64.0) 6.0000000000mod(y, x)取余数mod(9,4)1pi() double"π"常量pi() 3.14159265358979 power(a double, b double)double求a的b次幂power(9.0, 3.0)729power(a numeric, bnumeric)numeric求a的b次幂power(9.0, 3.0)729radians(double)double把角度转为弧度radians(45.0)0.785398163397448random()double 0.0到1.0之间的随机数值random()round(double/numeric)圆整为最接近的整数round(42.4)42round(v numeric, s int)numeric圆整为s位小数数字round(42.438,2)42.44sign(double/numeric)参数的符号(-1,0,+1) sign(-8.4)-1sqrt(double/numeric)平方根sqrt(2.0) 1.4142135623731 trunc(double/numeric)截断(向零靠近)trunc(42.8)42trunc(v numeric, s int)numeric 截断为s小数位置的数字trunc(42.438,2)42.43三角函数列表:函数描述acos(x)反余弦asin(x)反正弦atan(x)反正切atan2(x, y)正切y/x 的反函数cos(x)余弦cot(x)余切sin(x)正弦tan(x)正切四、字符串函数和操作符:下面是PostgreSQL中提供的字符串操作符列表:函数返回类型描述例子结果string || string text字串连接'Post' || 'greSQL'PostgreSQL bit_length(string)int字串里二进制位的个数bit_length('jose')32char_length(string)int字串中的字符个数char_length('jose')4convert(string using conversion_name)text使用指定的转换名字改变编码。
PostgreSQL学习⼿册(⽬录)事实上之前有很长⼀段时间都在纠结是否有必要好好学习它,但是始终都没有⼀个很好的理由说服⾃⼰。
甚⾄是直到这个项⽬最终决定选⽤PostgreSQL时,我都没有真正意识到学习它的价值,当时只是想反正和其它数据库差不多,能⽤就⾏了。
然⽽有⼀天晚上,⾃⼰也不知道为什么,躺在床上开始回想整个项⽬的实施过程,想着想着就想到了数据库选型这⼀问题上了。
事情是这样的,最初客户将他们的产品⽬标定位为主打中型规模,同时也要在⼀定程度上⽀持⼩型规模。
鉴于此,我们为他们提供的⽅案是中型规模的数据库选⽤Oracle,⼩型规模的选定MySQL,在经过多轮商谈之后这个⽅案通过了。
然⽽随着项⽬的深⼊,客户突然有⼀天提出,由于成本和市场推⼴等问题,该产品的数据库部分需要进⾏⼀定的调整,调整的结果是中型规模可以同时⽀持Oracle和MySQL,⽽⼩型规模则要同时⽀持MySQL和PostgreSQL,原因⾮常简单,PostgreSQL是纯免费的数据库产品。
听到这个消息之后,我当时就⾮常恼⽕,因为当初为了保证运⾏时效率(国标),我们的数据库访问层是完全基于数据库供应商提供的原始C接⼝开发的,甚⾄都没有考虑ODBC提供的原始C接⼝,以防在转换中失去效率,或是ODBC本⾝为了强调通⽤性⽽不得不牺牲某些数据库的优化特征,如批量插⼊、批量读取等。
最后的结果显⽽易见,客户就是上帝,上帝的意见就是真理,这样我们就不得不基于现有的访问层接⼝⼜重新开发了⼀套⽀持PostgreSQL原⽣C接⼝的驱动。
然⽽随着对PostgreSQL的不断学习,对它的了解也在逐步加深,后来发现它的功能还是⾮常强⼤的,特别是对GIS空间数据的⽀持就更加的吸引我了。
于是就在脑⼦⾥为MySQL和PostgreSQL做了⼀个简单的对⽐和分析,最后得出⼀个结论,相⽐MySQL,PostgreSQL并没有什么刚性的缺点,但是它的纯免费特征确实是MySQL⽆法⽐拟的。
云数据库 PostgreSQL操作指南产品⽂档【版权声明】©2013-2023 腾讯云版权所有本⽂档著作权归腾讯云单独所有,未经腾讯云事先书⾯许可,任何主体不得以任何形式复制、修改、抄袭、传播全部或部分本⽂档内容。
【商标声明】及其它腾讯云服务相关的商标均为腾讯云计算(北京)有限责任公司及其关联公司所有。
本⽂档涉及的第三⽅主体的商标,依法由权利⼈所有。
【服务声明】本⽂档意在向客户介绍腾讯云全部或部分产品、服务的当时的整体概况,部分产品、服务的内容可能有所调整。
您所购买的腾讯云产品、服务的种类、服务标准等应由您与腾讯云之间的商业合同约定,除⾮双⽅另有约定,否则,腾讯云对本⽂档内容不做任何明⽰或模式的承诺或保证。
⽂档⽬录操作指南实例管理实例⽣命周期设置实例维护时间调整实例配置变更可⽤区设置销毁实例恢复实例下线实例重启实例升级实例升级内核⼩版本只读实例只读实例概述管理只读实例 RO 组剔除策略和负载均衡帐号管理数据库权限概述⽤户与权限操作数据库优化慢查询分析错误⽇志参数管理设置实例参数参数值限制备份与恢复备份数据下载备份克隆实例⾃动备份设置在云服务器上恢复 PostgreSQL 数据删除备份查看备份空间设置备份下载规则插件管理插件概述⽀持插件⽀持插件版本概览PostgreSQL 9.3 ⽀持插件PostgreSQL 9.5 ⽀持插件PostgreSQL 10 ⽀持插件PostgreSQL 11 ⽀持插件PostgreSQL 12 ⽀持插件PostgreSQL 13 ⽀持插件PostgreSQL 14 ⽀持插件pgAgent 插件跨库访问位图计算 pg_roaringbitmap 插件定时任务 pg_cron 插件⽹络管理⽹络管理概述修改⽹络开启外⽹地址访问管理访问管理概述授权策略语法可授权的资源类型控制台⽰例数据加密透明数据加密概述开启透明数据加密安全组管理安全组关联实例⾄安全组监控与告警监控功能告警功能标签标签概述编辑标签操作指南实例管理实例⽣命周期最近更新时间:2021-07-06 10:55:18云数据库 PostgreSQL 实例有诸多状态,不同状态下实例可执⾏的操作不同。
PostgreSQL基础教学与应用第一章:PostgreSQL简介1.1 PostgreSQL的定义和特点1.2 PostgreSQL在数据库领域的应用价值第二章:PostgreSQL的安装和配置2.1 安装PostgreSQL2.2 配置PostgreSQL第三章:PostgreSQL数据库的基本操作3.1 连接数据库3.2 创建数据库3.3 创建表3.4 插入数据3.5 查询数据3.6 更新数据3.7 删除数据第四章:PostgreSQL数据库的高级操作4.1 约束4.2 索引4.3 视图4.4 存储过程4.5 触发器第五章:PostgreSQL的高可用性5.1 水平扩展5.2 热备份5.3 流复制第六章:PostgreSQL与其他数据库的比较6.1 PostgreSQL与MySQL的比较6.2 PostgreSQL与Oracle的比较第七章:PostgreSQL的应用案例分析7.1 PostgreSQL在电子商务领域的应用7.2 PostgreSQL在大数据处理中的应用7.3 PostgreSQL在地理信息系统中的应用第八章:PostgreSQL的未来发展趋势8.1 PostgreSQL的发展历程8.2 PostgreSQL的未来发展方向第一章:PostgreSQL简介PostgreSQL是一个开源的关系型数据库管理系统,其具有可扩展性、稳定性和安全性等特点。
它被广泛应用于企业级数据库管理和大规模数据处理领域,成为了目前世界上发展最快的开源数据库之一。
第二章:PostgreSQL的安装和配置2.1 安装PostgreSQL要安装PostgreSQL,可以从官方网站上下载最新版本的安装包。
安装过程中需按照提示进行设置和配置,如选择安装路径、创建管理员用户等。
2.2 配置PostgreSQL配置文件中包含了数据库的参数设置,可以根据需求进行修改,如修改监听地址、设置最大连接数等。
第三章:PostgreSQL数据库的基本操作3.1 连接数据库使用命令行工具或可视化工具连接数据库,输入用户名和密码即可进行连接。
PostgreSQL是一个功能强大的开源关系型数据库管理系统,它支持标准SQL语言,同时还提供了丰富的扩展和插件,可以满足各种复杂的数据处理需求。
在PostgreSQL中,可以使用SQL语言进行数据的查询、更新、删除等操作,同时还可以通过创建函数来实现更加灵活和复杂的数据处理和计算。
在本文中,我们将重点介绍在PostgreSQL中创建查询函数的语法和步骤。
查询函数是一种用户定义的函数,它可以接受参数并返回查询结果集,可以在数据库中实现复杂的数据处理和计算逻辑。
下面将重点介绍在PostgreSQL中创建查询函数的语法和步骤。
1. 创建函数的基本语法在PostgreSQL中,创建查询函数的基本语法如下所示:```sqlCREATE OR REPLACE FUNCTION function_name (parameters) RETURNS return_type AS $$DECLAREdeclaration_statementsBEGINexecutable_statementsEND;$$ LANGUAGE plpgsql;```其中,关键字CREATE OR REPLACE FUNCTION表示创建或者替换一个函数,function_name表示函数的名称,parameters表示函数的参数列表,return_type表示函数的返回值类型,DECLARE和BEGIN之间是变量的声明和函数体的开始,$$和$$之间是函数体的具体实现,LANGUAGE plpgsql表示函数使用PL/pgSQL语言实现。
下面我们将逐步解释每个部分的含义和使用方法。
2. 函数名称和参数列表首先是函数的名称和参数列表,函数名称是唯一的标识符,用于标识函数的身份,参数列表定义了函数可以接受的输入参数。
我们可以创建一个名为calculate_salary的函数,它接受员工编号和工资增加比例作为输入参数:```sqlCREATE OR REPLACE FUNCTION calculate_salary(emp_id integer, increase numeric)```在这个例子中,calculate_salary是函数的名称,它接受两个参数emp_id和increase,分别表示员工编号和工资增加比例。
PostgreSQL从入门到精通目录引言 (6)第一章 POSTGRESQL介绍 (7)基于数据编程 (7)静态数据 (7)用于数据存储的扁平文件 (7)重复单元和其他问题 (8)什么是数据库管理系统 (8)数据模型 (9)查询语言 (11)数据库管理系统的责任 (12)什么是P OSTGRE SQL? (13)PostgreSQL历史简介 (13)PostgreSQL架构 (13)通过PostgreSQL访问数据 (14)什么是开源? (15)相关资源 (15)第二章关系数据库原理 (16)电子表格的局限性 (16)将数据存入数据库 (18)选择列 (18)为每个列选择数据类型 (18)标记行的唯一性 (19)在数据库中访问数据 (19)通过网络访问数据 (20)处理多用户访问 (21)数据分片和分块 (21)增加信息 (23)设计表 (25)基本数据类型 (30)处理未知的值:空值(NULL) (31)回顾示例数据库 (31)摘要 (31)第三章初步使用POSTGRESQL (33)在L INUX和U NIX系统中安装P OSTGRE SQL (33)在Linux中使用二进制文件安装PostgreSQL (33)通过源码安装PostgreSQL (37)在Linux和Unix上配置PostgreSQL (40)在W INDOWS中安装P OSTGRE SQL (45)使用Windows安装程序 (45)配置客户机访问 (51)建立示例数据库 (52)添加用户记录 (52)建立数据库 (53)建表 (54)移除表 (55)填充表 (56)摘要 (59)第四章访问你的数据 (60)在Linux系统中启动 (60)在Windows系统中启动 (61)解决启动问题 (61)使用一些基本的psql命令 (63)使用SELECT语句 (64)覆盖列名 (66)控制行的顺序 (66)消除重复数据 (69)执行计算 (71)选择行 (72)使用更复杂的条件 (74)模式匹配 (76)限制结果集 (76)检查空值(NULL) (78)检查时间和日期 (78)设置时间和日期的风格 (79)使用日期和时间函数 (82)多个表协同工作 (84)关联两个表 (84)给表赋予别名 (88)关联三个或更多的表 (89)SQL92的SELECT语法 (93)摘要 (94)第五章 POSTGRESQL的命令行和图形界面工具 (95)PSQL (95)启动psql (95)在psql中输入命令 (96)使用命令历史 (96)在psql中执行脚本文件 (97)检查数据库 (98)psql命令行快速参考 (99)psql内部命令快速参考 (100)设置ODBC (101)在Windows中安装ODBC驱动程序 (102)在Windows中建立一个数据源 (104)在Linux/Unix中安装ODBC驱动程序 (106)在Linux/Unix中建立一个数据源 (106)PG A DMIN III (106)安装pgAdmin III (106)使用pgAdmin III (107)PHP P G A DMIN (110)安装phpPgAdmin (110)使用phpPgAdmin (111)M ICROSOFT A CCESS (113)使用链接表 (114)输入数据及建立报表 (116)M ICROSOFT E XCEL (118)P OSTGRE SQL相关工具的资源 (122)摘要 (122)第六章数据交互 (123)添加数据到数据库中 (123)使用更安全的插入语句 (126)插入数据到serial类型的列中 (127)插入空值 (130)使用\copy命令 (131)T R Y IT OU T:L O AD DA TA U SIN G\COPY ................................................................ 错误!未定义书签。
postgres sql交叉查询命令下载提示:该文档是本店铺精心编制而成的,希望大家下载后,能够帮助大家解决实际问题。
文档下载后可定制修改,请根据实际需要进行调整和使用,谢谢!本店铺为大家提供各种类型的实用资料,如教育随笔、日记赏析、句子摘抄、古诗大全、经典美文、话题作文、工作总结、词语解析、文案摘录、其他资料等等,想了解不同资料格式和写法,敬请关注!Download tips: This document is carefully compiled by this editor. I hope that after you download it, it can help you solve practical problems. The document can be customized and modified after downloading, please adjust and use it according to actual needs, thank you! In addition, this shop provides you with various types of practical materials, such as educational essays, diary appreciation, sentence excerpts, ancient poems, classic articles, topic composition, work summary, word parsing, copy excerpts, other materials and so on, want to know different data formats and writing methods, please pay attention!PostgreSQL SQL交叉查询命令详解简介PostgreSQL是一款功能强大的开源关系型数据库管理系统,其支持多种查询方式,包括交叉查询。
postgresql安装及配置超详细教程⽬录1. 安装初始化数据库2. PostgrepSQL的简单配置2.1 修改监听的ip和端⼝2.2 修改数据库log相关的参数2.3 内存参数3. 数据库的基础操作3.1 连接数据库控制台3.3 SQL控制台操作语句4. 认证登录4.1 认证⽅式4.2 远程登录4.3 本地登录1. 安装根据业务需求选择版本,yum install https:///pub/repos/yum/9.6/redhat/rhel-7-x86_64/pgdg-centos96-9.6-3.noarch.rpmyum install postgresql96 postgresql96-serverrpm -qa|grep postgre初始化数据库执⾏完初始化任务之后,postgresql 会⾃动创建和⽣成两个⽤户和⼀个数据库:linux 系统⽤户 postgres:管理数据库的系统⽤户;密码由于是默认⽣成的,需要在系统中修改⼀下,$passwd postgres数据库⽤户 postgres:数据库超级管理员此⽤户默认数据库为postgres/usr/pgsql-9.6/bin/postgresql96-setup initdb设置成 centos7 开机启动服务systemctl enable postgresql-9.6启动 postgresql 服务systemctl start postgresql-9.6systemctl status postgresql-9.62. PostgrepSQL的简单配置pgsql9.6配置⽂件位置默认在:/var/lib/pgsql/9.6/data/postgresql.conf2.1 修改监听的ip和端⼝监听IP使⽤localhost时,只能通过127.0.0.1访问数据库;如果需要通过其他远程地址访问PostgreSQL,可以使⽤“,”作为分隔符,把IP地址添加到listen_addresses后,或者使⽤“*”,让所有IP都可以访问数据库。
PostgreSQL7.2TutorialThe PostgreSQL Global Development GroupPostgreSQL7.2Tutorialby The PostgreSQL Global Development GroupCopyright©1996-2001by The PostgreSQL Global Development GroupLegal NoticePostgreSQL is Copyright©1996-2001by the PostgreSQL Global Development Group and is distributed under the terms of the license of the University of California below.Postgres95is Copyright©1994-5by the Regents of the University of California.Permission to use,copy,modify,and distribute this software and its documentation for any purpose,without fee,and without a written agreement is hereby granted,provided that the above copyright notice and this paragraph and the following two paragraphs appear in all copies.IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT,INDIRECT,SPECIAL, INCIDENTAL,OR CONSEQUENTIAL DAMAGES,INCLUDING LOST PROFITS,ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,INCLUDING,BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.THE SOFTWARE PRO-VIDED HEREUNDER IS ON AN“AS-IS”BASIS,AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE,SUPPORT,UPDATES,ENHANCEMENTS,OR MODIFICATIONS.Table of ContentsWelcome (iv)Preface (v)1.What is PostgreSQL? (v)2.A Short History of PostgreSQL (v)2.1.The Berkeley POSTGRES Project (vi)2.2.Postgres95 (vi)2.3.PostgreSQL (vii)3.Documentation Resources (vii)4.Terminology and Notation (viii)5.Bug Reporting Guidelines (ix)5.1.Identifying Bugs (ix)5.2.What to report (x)5.3.Where to report bugs (xi)6.Y2K Statement (xii)1.Getting Started (1)1.1.Installation (1)1.2.Architectural Fundamentals (1)1.3.Creating a Database (2)1.4.Accessing a Database (3)2.The SQL Language (5)2.1.Introduction (5)2.2.Concepts (5)2.3.Creating a New Table (5)2.4.Populating a Table With Rows (6)2.5.Querying a Table (7)2.6.Joins Between Tables (8)2.7.Aggregate Functions (10)2.8.Updates (12)2.9.Deletions (12)3.Advanced Features (14)3.1.Introduction (14)3.2.Views (14)3.3.Foreign Keys (14)3.4.Transactions (15)3.5.Inheritance (16)3.6.Conclusion (18)Bibliography (19)Index (21)WelcomeWelcome to PostgreSQL and the PostgreSQL Tutorial.The following few chapters are intended togive a simple introduction to PostgreSQL,relational database concepts,and the SQL language tothose who are new to any one of these aspects.We only assume some general knowledge about howto use computers.No particular Unix or programming experience is required.After you have worked through this tutorial you might want to move on to reading the User’s Guideto gain a more formal knowledge of the SQL language,or the Programmer’s Guide for informationabout developing applications for PostgreSQL.We hope you have a pleasant experience with PostgreSQL.Preface1.What is PostgreSQL?PostgreSQL is an object-relational database management system(ORDBMS)based on POSTGRES,Version4.21,developed at the University of California at Berkeley Computer Science Department.The POSTGRES project,led by Professor Michael Stonebraker,was sponsored by the Defense Ad-vanced Research Projects Agency(DARPA),the Army Research Office(ARO),the National ScienceFoundation(NSF),and ESL,Inc.PostgreSQL is an open-source descendant of this original Berkeley code.It provides SQL92/SQL99language support and other modern features.POSTGRES pioneered many of the object-relational concepts now becoming available in some com-mercial databases.Traditional relational database management systems(RDBMS)support a datamodel consisting of a collection of named relations,containing attributes of a specific type.In currentcommercial systems,possible types includefloating point numbers,integers,character strings,money,and dates.It is commonly recognized that this model is inadequate for future data-processing appli-cations.The relational model successfully replaced previous models in part because of its“Spartansimplicity”.However,this simplicity makes the implementation of certain applications very difficult.PostgreSQL offers substantial additional power by incorporating the following additional concepts insuch a way that users can easily extend the system:•inheritance•data types•functionsOther features provide additional power andflexibility:•constraints•triggers•rules•transactional integrityThese features put PostgreSQL into the category of databases referred to as object-relational.Notethat this is distinct from those referred to as object-oriented,which in general are not as well suitedto supporting traditional relational database languages.So,although PostgreSQL has some object-oriented features,it isfirmly in the relational database world.In fact,some commercial databaseshave recently incorporated features pioneered by PostgreSQL.2.A Short History of PostgreSQLThe object-relational database management system now known as PostgreSQL(and briefly calledPostgres95)is derived from the POSTGRES package written at the University of California at Berke-ley.With over a decade of development behind it,PostgreSQL is the most advanced open-sourcedatabase available anywhere,offering multiversion concurrency control,supporting almost all SQL 1.:8000/postgres/postgres.htmlconstructs(including subselects,transactions,and user-defined types and functions),and having awide range of language bindings available(including C,C++,Java,Perl,Tcl,and Python).2.1.The Berkeley POSTGRES ProjectImplementation of the POSTGRES DBMS began in1986.The initial concepts for the system werepresented in The design of POSTGRES and the definition of the initial data model appeared in ThePOSTGRES data model.The design of the rule system at that time was described in The design of thePOSTGRES rules system.The rationale and architecture of the storage manager were detailed in Thedesign of the POSTGRES storage system.Postgres has undergone several major releases since then.Thefirst“demoware”system became op-erational in1987and was shown at the1988ACM-SIGMOD Conference.Version1,described inThe implementation of POSTGRES,was released to a few external users in June1989.In responseto a critique of thefirst rule system(A commentary on the POSTGRES rules system),the rule systemwas redesigned(On Rules,Procedures,Caching and Views in Database Systems)and Version2wasreleased in June1990with the new rule system.Version3appeared in1991and added support formultiple storage managers,an improved query executor,and a rewritten rewrite rule system.For themost part,subsequent releases until Postgres95(see below)focused on portability and reliability.POSTGRES has been used to implement many different research and production applications.Theseinclude:afinancial data analysis system,a jet engine performance monitoring package,an aster-oid tracking database,a medical information database,and several geographic information systems.POSTGRES has also been used as an educational tool at several universities.Finally,Illustra Infor-mation Technologies(later merged into Informix2,which is now owned by IBM3.)picked up the codeand commercialized it.POSTGRES became the primary data manager for the Sequoia20004scientificcomputing project in late1992.The size of the external user community nearly doubled during1993.It became increasingly obviousthat maintenance of the prototype code and support was taking up large amounts of time that shouldhave been devoted to database research.In an effort to reduce this support burden,the BerkeleyPOSTGRES project officially ended with Version4.2.2.2.Postgres95In1994,Andrew Yu and Jolly Chen added a SQL language interpreter to POSTGRES.Postgres95was subsequently released to the Web tofind its own way in the world as an open-source descendantof the original POSTGRES Berkeley code.Postgres95code was completely ANSI C and trimmed in size by25%.Many internal changes im-proved performance and maintainability.Postgres95release1.0.x ran about30-50%faster on theWisconsin Benchmark compared to POSTGRES,Version4.2.Apart from bugfixes,the followingwere the major enhancements:•The query language PostQUEL was replaced with SQL(implemented in the server).Subquerieswere not supported until PostgreSQL(see below),but they could be imitated in Postgres95withuser-defined SQL functions.Aggregates were re-implemented.Support for the GROUP BY queryclause was also added.The libpq interface remained available for C programs.•In addition to the monitor program,a new program(psql)was provided for interactive SQL queriesusing GNU Readline.2./3./4./s2k/s2k_home.html•A new front-end library,libpgtcl,supported Tcl-based clients.A sample shell,pgtclsh,providednew Tcl commands to interface Tcl programs with the Postgres95backend.•The large-object interface was overhauled.The Inversion large objects were the only mechanismfor storing large objects.(The Inversionfile system was removed.)•The instance-level rule system was removed.Rules were still available as rewrite rules.•A short tutorial introducing regular SQL features as well as those of Postgres95was distributedwith the source code•GNU make(instead of BSD make)was used for the build.Also,Postgres95could be compiledwith an unpatched GCC(data alignment of doubles wasfixed).2.3.PostgreSQLBy1996,it became clear that the name“Postgres95”would not stand the test of time.We chose a newname,PostgreSQL,to reflect the relationship between the original POSTGRES and the more recentversions with SQL capability.At the same time,we set the version numbering to start at6.0,puttingthe numbers back into the sequence originally begun by the Berkeley POSTGRES project.The emphasis during development of Postgres95was on identifying and understanding existing prob-lems in the backend code.With PostgreSQL,the emphasis has shifted to augmenting features andcapabilities,although work continues in all areas.Major enhancements in PostgreSQL include:•Table-level locking has been replaced by multiversion concurrency control,which allows readersto continue reading consistent data during writer activity and enables hot backups from pg_dumpwhile the database stays available for queries.•Important backend features,including subselects,defaults,constraints,and triggers,have been im-plemented.•Additional SQL92-compliant language features have been added,including primary keys,quotedidentifiers,literal string type coercion,type casting,and binary and hexadecimal integer input.•Built-in types have been improved,including new wide-range date/time types and additional geo-metric type support.•Overall backend code speed has been increased by approximately20-40%,and backend start-uptime has decreased by80%since version6.0was released.3.Documentation ResourcesThis manual set is organized into several parts:TutorialAn informal introduction for new usersUser’s GuideDocuments the SQL query language environment,including data types and functions.Programmer’s GuideAdvanced information for application programmers.Topics include type and function extensi-bility,library interfaces,and application design issues.Administrator’s GuideInstallation and server management informationReference ManualReference pages for SQL command syntax and client and server programsDeveloper’s GuideInformation for PostgreSQL developers.This is intended for those who are contributing to thePostgreSQL project;application development information appears in the Programmer’s Guide.In addition to this manual set,there are other resources to help you with PostgreSQL installation anduse:man pagesThe Reference Manual’s pages in the traditional Unix man format.FAQsFrequently Asked Questions(FAQ)lists document both general issues and someplatform-specific issues.READMEsREADMEfiles are available for some contributed packages.Web SiteThe PostgreSQL web site5carries details on the latest release,upcoming features,and otherinformation to make your work or play with PostgreSQL more productive.Mailing ListsThe mailing lists are a good place to have your questions answered,to share experiences withother users,and to contact the developers.Consult the User’s Lounge6section of the PostgreSQLweb site for details.Yourself!PostgreSQL is an open-source effort.As such,it depends on the user community for ongoingsupport.As you begin to use PostgreSQL,you will rely on others for help,either through thedocumentation or through the mailing lists.Consider contributing your knowledge back.If youlearn something which is not in the documentation,write it up and contribute it.If you addfeatures to the code,contribute them.Even those without a lot of experience can provide corrections and minor changes in the docu-mentation,and that is a good way to start.The<pgsql-docs@>mailing listis the place to get going.5.6./users-lounge/4.Terminology and NotationThe terms“PostgreSQL”and“Postgres”will be used interchangeably to refer to the software thataccompanies this documentation.An administrator is generally a person who is in charge of installing and running the server.A usercould be anyone who is using,or wants to use,any part of the PostgreSQL system.These terms shouldnot be interpreted too narrowly;this documentation set does not havefixed presumptions about systemadministration procedures.We use/usr/local/pgsql/as the root directory of the installation and/usr/local/pgsql/data as the directory with the databasefiles.These directories may vary onyour site,details can be derived in the Administrator’s Guide.In a command synopsis,brackets([and])indicate an optional phrase or keyword.Anything in braces({and})and containing vertical bars(|)indicates that you must choose one alternative.Examples will show commands executed from various accounts and mands executedfrom a Unix shell may be preceded with a dollar sign(“$”).Commands executed from particularuser accounts such as root or postgres are speciallyflagged and explained.SQL commands may bepreceded with“=>”or will have no leading prompt,depending on the context.Note:The notation forflagging commands is not universally consistent throughoutthe documentation set.Please report problems to the documentation mailing list<pgsql-docs@>.5.Bug Reporting GuidelinesWhen youfind a bug in PostgreSQL we want to hear about it.Your bug reports play an important partin making PostgreSQL more reliable because even the utmost care cannot guarantee that every partof PostgreSQL will work on every platform under every circumstance.The following suggestions are intended to assist you in forming bug reports that can be handled in aneffective fashion.No one is required to follow them but it tends to be to everyone’s advantage.We cannot promise tofix every bug right away.If the bug is obvious,critical,or affects a lot of users,chances are good that someone will look into it.It could also happen that we tell you to update to anewer version to see if the bug happens there.Or we might decide that the bug cannot befixed beforesome major rewrite we might be planning is done.Or perhaps it is simply too hard and there aremore important things on the agenda.If you need help immediately,consider obtaining a commercialsupport contract.5.1.Identifying BugsBefore you report a bug,please read and re-read the documentation to verify that you can really dowhatever it is you are trying.If it is not clear from the documentation whether you can do somethingor not,please report that too;it is a bug in the documentation.If it turns out that the program doessomething different from what the documentation says,that is a bug.That might include,but is notlimited to,the following circumstances:•A program terminates with a fatal signal or an operating system error message that would point toa problem in the program.(A counterexample might be a“disk full”message,since you have tofixthat yourself.)•A program produces the wrong output for any given input.•A program refuses to accept valid input(as defined in the documentation).•A program accepts invalid input without a notice or error message.But keep in mind that your idea of invalid input might be our idea of an extension or compatibility with traditional practice.•PostgreSQL fails to compile,build,or install according to the instructions on supported platforms. Here“program”refers to any executable,not only the backend server.Being slow or resource-hogging is not necessarily a bug.Read the documentation or ask on one of the mailing lists for help in tuning your applications.Failing to comply to the SQL standard is not necessarily a bug either,unless compliance for the specific feature is explicitly claimed.Before you continue,check on the TODO list and in the FAQ to see if your bug is already known. If you cannot decode the information on the TODO list,report your problem.The least we can do is make the TODO list clearer.5.2.What to reportThe most important thing to remember about bug reporting is to state all the facts and only facts.Do not speculate what you think went wrong,what“it seemed to do”,or which part of the program has a fault.If you are not familiar with the implementation you would probably guess wrong and not help us a bit.And even if you are,educated explanations are a great supplement to but no substitute for facts.If we are going tofix the bug we still have to see it happen for ourselvesfirst.Reporting the bare facts is relatively straightforward(you can probably copy and paste them from the screen)but all too often important details are left out because someone thought it does not matter or the report would be understood anyway.The following items should be contained in every bug report:•The exact sequence of steps from program start-up necessary to reproduce the problem.This should be self-contained;it is not enough to send in a bare select statement without the preceding create table and insert statements,if the output should depend on the data in the tables.We do not have the time to reverse-engineer your database schema,and if we are supposed to make up our own data we would probably miss the problem.The best format for a test case for query-language related problems is afile that can be run through the psql frontend that shows the problem.(Be sure to not have anything in your~/.psqlrc start-upfile.)An easy start at thisfile is to use pg_dump to dump out the table declarations and data needed to set the scene,then add the problem query.You are encouraged to minimize the size of your example,but this is not absolutely necessary.If the bug is reproducible,we willfind it either way.If your application uses some other client interface,such as PHP,then please try to isolate the offending queries.We will probably not set up a web server to reproduce your problem.In any case remember to provide the exact inputfiles,do not guess that the problem happens for“largefiles”or“mid-size databases”,etc.since this information is too inexact to be of use.•The output you got.Please do not say that it“didn’t work”or“crashed”.If there is an error message, show it,even if you do not understand it.If the program terminates with an operating system error, say which.If nothing at all happens,say so.Even if the result of your test case is a program crash or otherwise obvious it might not happen on our platform.The easiest thing is to copy the output from the terminal,if possible.Note:In case of fatal errors,the error message reported by the client might not contain all the information available.Please also look at the log output of the database server.If you do not keep your server’s log output,this would be a good time to start doing so.•The output you expected is very important to state.If you just write“This command gives me that output.”or“This is not what I expected.”,we might run it ourselves,scan the output,and think it looks OK and is exactly what we expected.We should not have to spend the time to decode the exact semantics behind your commands.Especially refrain from merely saying that“This is not what SQL says/Oracle does.”Digging out the correct behavior from SQL is not a fun undertaking, nor do we all know how all the other relational databases out there behave.(If your problem is a program crash,you can obviously omit this item.)•Any command line options and other start-up options,including concerned environment variables or configurationfiles that you changed from the default.Again,be exact.If you are using a prepack-aged distribution that starts the database server at boot time,you should try tofind out how that is done.•Anything you did at all differently from the installation instructions.•The PostgreSQL version.You can run the command SELECT version();tofind out the version of the server you are connected to.Most executable programs also support a--version option;at least postmaster--version and psql--version should work.If the function or the options do not exist then your version is more than old enough to warrant an upgrade.You can also look into the READMEfile in the source directory or at the name of your distributionfile or package name. If you run a prepackaged version,such as RPMs,say so,including any subversion the package may have.If you are talking about a CVS snapshot,mention that,including its date and time.If your version is older than7.2we will almost certainly tell you to upgrade.There are tons of bug fixes in each new release,that is why we make new releases.•Platform information.This includes the kernel name and version,C library,processor,memory information.In most cases it is sufficient to report the vendor and version,but do not assume everyone knows what exactly“Debian”contains or that everyone runs on Pentiums.If you have installation problems then information about compilers,make,etc.is also necessary.Do not be afraid if your bug report becomes rather lengthy.That is a fact of life.It is better to report everything thefirst time than us having to squeeze the facts out of you.On the other hand,if your inputfiles are huge,it is fair to askfirst whether somebody is interested in looking into it.Do not spend all your time tofigure out which changes in the input make the problem go away.This will probably not help solving it.If it turns out that the bug cannot befixed right away,you will still have time tofind and share your work-around.Also,once again,do not waste your time guessing why the bug exists.We willfind that out soon enough.When writing a bug report,please choose non-confusing terminology.The software package in to-tal is called“PostgreSQL”,sometimes“Postgres”for short.If you are specifically talking about the backend server,mention that,do not just say“PostgreSQL crashes”.A crash of a single backend server process is quite different from crash of the parent“postmaster”process;please don’t say“the postmaster crashed”when you mean a single backend went down,nor vice versa.Also,client pro-grams such as the interactive frontend“psql”are completely separate from the backend.Please try to be specific about whether the problem is on the client or server side.5.3.Where to report bugsIn general,send bug reports to the bug report mailing list at<pgsql-bugs@>.Youare requested to use a descriptive subject for your email message,perhaps parts of the error message.Another method is tofill in the bug report web-form available at the project’s web site/.Entering a bug report this way causes it to be mailed to the<pgsql-bugs@>mailing list.Do not send bug reports to any of the user mailing lists,such as<pgsql-sql@>or<pgsql-general@>.These mailing lists are for answering user questions andtheir subscribers normally do not wish to receive bug reports.More importantly,they are unlikely tofix them.Also,please do not send reports to the developers’mailing list<pgsql-hackers@>.This list is for discussing the development of PostgreSQL and itwould be nice if we could keep the bug reports separate.We might choose to take up a discussionabout your bug report on pgsql-hackers,if the problem needs more review.If you have a problem with the documentation,the best place to report it is the documentation mailinglist<pgsql-docs@>.Please be specific about what part of the documentation youare unhappy with.If your bug is a portability problem on a non-supported platform,send mail to<pgsql-ports@>,so we(and you)can work on porting PostgreSQL to yourplatform.Note:Due to the unfortunate amount of spam going around,all of the above email addressesare closed mailing lists.That is,you need to be subscribed to a list to be allowed to post on it.(Y ou need not be subscribed to use the bug report web-form,however.)If you would like to sendmail but do not want to receive list traffic,you can subscribe and set your subscription option tonomail.For more information send mail to<majordomo@>with the single wordhelp in the body of the message.6.Y2K StatementAuthor:Written by Thomas Lockhart(<lockhart@>)on1998-10-22.Updated2000-03-31.The PostgreSQL Global Development Group provides the PostgreSQL software code tree as a publicservice,without warranty and without liability for its behavior or performance.However,at the timeof writing:•The author of this statement,a volunteer on the PostgreSQL support team since November,1996,is not aware of any problems in the PostgreSQL code base related to time transitions around Jan1,2000(Y2K).•The author of this statement is not aware of any reports of Y2K problems uncovered in regressiontesting or in otherfield use of recent or current versions of PostgreSQL.We might have expectedto hear about problems if they existed,given the installed base and the active participation of userson the support mailing lists.•To the best of the author’s knowledge,the assumptions PostgreSQL makes about dates specifiedwith a two-digit year are documented in the current User’s Guide in the chapter on data types.Fortwo-digit years,the significant transition year is1970,not2000;e.g.70-01-01is interpreted as1970-01-01,whereas69-01-01is interpreted as2069-01-01.•Any Y2K problems in the underlying OS related to obtaining the“current time”may propagateinto apparent Y2K problems in PostgreSQL.Refer to The GNU Project8and The Perl Institute9for further discussion of Y2K issues,particularlyas it relates to open source,no fee software.8./software/year2000.html9./news/y2k.htmlChapter1.Getting Started1.1.InstallationBefore you can use PostgreSQL you need to install it,of course.It is possible that PostgreSQL isalready installed at your site,either because it was included in your operating system distributionor because the system administrator already installed it.If that is the case,you should obtain infor-mation from the operating system documentation or your system administrator about how to accessPostgreSQL.If you are not sure whether PostgreSQL is already available or whether you can use it for your ex-perimentation then you can install it yourself.Doing so is not hard and it can be a good exercise.PostgreSQL can be installed by any unprivileged user,no superuser(root)access is required.If you are installing PostgreSQL yourself,then refer to the Administrator’s Guide for instructions oninstallation,and return to this guide when the installation is complete.Be sure to follow closely thesection about setting up the appropriate environment variables.If your site administrator has not set things up in the default way,you may have some more workto do.For example,if the database server machine is a remote machine,you will need to set thePGHOST environment variable to the name of the database server machine.The environment variablePGPORT may also have to be set.The bottom line is this:if you try to start an application program andit complains that it cannot connect to the database,you should consult your site administrator or,ifthat is you,the documentation to make sure that your environment is properly set up.If you did notunderstand the preceding paragraph then read the next section.1.2.Architectural FundamentalsBefore we proceed,you should understand the basic PostgreSQL system architecture.Understandinghow the parts of PostgreSQL interact will make this chapter somewhat clearer.In database jargon,PostgreSQL uses a client/server model.A PostgreSQL session consists of thefollowing cooperating processes(programs):•A server process,which manages the databasefiles,accepts connections to the database from clientapplications,and performs actions on the database on behalf of the clients.The database serverprogram is called postmaster.•The user’s client(frontend)application that wants to perform database operations.Client applica-tions can be very diverse in nature:They could be a text-oriented tool,a graphical application,aweb server that accesses the database to display web pages,or a specialized database maintenancetool.Some client applications are supplied with the PostgreSQL distribution,most are developedby users.As is typical of client/server applications,the client and the server can be on different hosts.In thatcase they communicate over a TCP/IP network connection.You should keep this in mind,becausethefiles that can be accessed on a client machine might not be accessible(or might only be accessibleusing a differentfile name)on the database server machine.The PostgreSQL server can handle multiple concurrent connections from clients.For that purposeit starts(“forks”)a new process for each connection.From that point on,the client and the newserver process communicate without intervention by the original postmaster process.Thus,the。