Home
Postgres Book
Contents
1. Mike Nichols Tampa FL 19 Cindy Anderson Denver co 23 Sam Jackson Allentown PA 22 3 rows Figure 3 5 My first SELECT on one line That s fine As queries get longer breaking them into multiple lines helps make things clearer Let s look at this in detail First we have the word SELECT followed by an asterisk then the word FROM and our table name friend and a semicolon to execute the query The SELECT starts our command and tells the database server what is coming next The tells the server we want all the columns from the table The FROM friend tells which table we want to see So we have said we want all columns from our table friend and indeed that is what is displayed It should have the same data as table 3 1 on page 10 As I mentioned SELECT has a large number of variations and we will look at a few of them now First suppose you want to retrieve only one of the columns from the friend table You might already suspect that the asterisk has to be changed in the query If you replace the asterisk with one of the column names you will see only that column Try SELECT city FROM friend You can choose any of the columns You can even choose multiple columns by separating the names with a comma For example to see first and last names only use SELECT firstname lastname FROM friend Try a few more SELECT commands until you get comfortable If you specify a name that is no
2. 52 Te GAL Joining Customer and mpl yee dz lt s reer r RAE RE aa ea S E 53 1154 0 12 Joining part and employee sa cs bbe cde ende AA 53 1155 6 13 Statename table kw ice ARA AR dn O AAA 54 ie 6 14 Usinga customer Code sa kope sor oen me Ghar Stee Awe oe Awe Boud dhl ks Bad arn Be ie 55 1158 6 15 One tomany DO rn a AA A ELS LES Ye wd 56 1159 6 16 Unomedtaples 2454458859544 SSK He SoS EERE HER EREE EE mes Eaa 57 ae G17 Using IS USOS y eho ky Ah dean ee A A Me Be AW de ewe Ow ey 57 1162 6 18 Examples of self joins using table aliases o o o eee 58 1163 6 19 DOPCUMIOME lt A AA A A AAA A 59 ie 6 20 New salesorder table for multiple parts per order 0en 59 1166 OLE aw owe 2 eee ee Sw PES Oe eS ee he eee 59 e 6 22 Queries involving orderpart table 61 1169 1170 A A A 64 1171 TE COME WUD oh he eee eee ehehe AAA ed 64 en Zo Examples of sequence function USO 246 2 ceo ener asa a sd 66 1174 7 4 Numbering customer rows using a sequence 1 0 o ee ee 67 1175 i 1176 TO Customer CANIS using SERIAL lt a AS Ba E 68 1177 1178 8 1 Combining two columns with UNION ss 446568 252645844488 e RG ROR eS 71 1179 62 Combining two tables with UNION 4 s 52044544 8020444848405 e ed ods 72 a 83 UNION Wath duplicates ses seats a a we ee ae oe 73 1182 OA UNION ALL Wires os RARER SEH Ri A ERED ES 73 1183 65 EXCEPT restricts output from the first SELECT c44 6228
3. 3 1 Relational Databases As I mentioned in section 1 1 the purpose of a database is rapid data storage and retrieval Today most database systems are relational databases While the term relational database has a mathematical foundation in practice 1t means that all data stored in the database is arranged in a uniform structure In figure 3 1 you see the database server with access to three databases test demo and finance You la m Database Server E me Figure 3 1 Databases could issue the command psql finance and be connected to the finance database You have already dealt with this in chapter 2 Using psq1 you chose to connect to database test with the command psql test To see a list of databases available at your site type psql 1 The first column lists the database names However you may not have permission to connect to them You might ask What are those black rectangles in the databases Those are tables Tables are the foundation of a relational database management system RDBMS As I mentioned earlier databases store data 9 10 CHAPTER 3 BASIC SQL COMMANDS Those tables are where data is stored in a database Each table has a name defined by the person who created it Let s look at a single table called friend in table 3 1 You can easily see how tables are used to store data FirstName LastName City State Age Mike 19 Cindy 23 Sam Jackson Allentown 22 Table 3 1
4. square root sqrt 1 4142135624 1 row Figure 4 22 Function examples 35 36 CHAPTER 4 CUSTOMIZING QUERIES 3895 3896 3897 3898 3899 3900 test gt Ido 3901 List of operators Be Left arg Right arg Result 3904 Recs Poa Bibs Sete eee ee ed 3905 B 3906 int4 int4 3907 int4 int4 3908 3909 3910 3911 3912 testes 3913 es do Soil List of operators 3915 Op Left arg Right arg Result 3916 3917 3918 box point box 3919 char char char 3920 3921 3922 3923 test gt do oe List of operators 3926 Op Left arg Right arg Result 3927 A ee le te EAE Proa 3928 p 3929 float8 float8 float8 3930 1 row 3931 3932 lt 3933 test gt dd 3934 Object descriptions 3935 ode 3936 Name What Description 3937 t 3938 8 operator exponentiation 3939 3940 1 row 3941 3942 test gt SELECT 2 3 4 oen 3944 column 3045 Peas es sss 3946 83 3947 3948 1 row 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 Figure 4 23 Operator examples 4 15 SUMMARY 37 DATESTYLE controls the appearance of dates when printed in psql as seen in table 4 8 It controls the format slashes dashes or year first and the display of the month first US or day first European The command SET DATESTYLE TO SQL US would most likely be used by users in the USA while Europeans might
5. 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 18 2 SQL FUNCTIONS test gt test gt test gt test gt CREATE test gt tax CREATE RETURNS AS SELECT 1 0 06 numeric 8 2 numeric 8 2 LANGUAG SELECT FUNCTION tax numeric numeric E sql tax 100 Figure 18 2 SQL tax function 169 because the result of the computation must be rounded to two decimal places This function uses the more compact double colon form of type casting rather than CAST See section 9 3 for more information about type casting SELECT tax 100 performs a simple computation similar to ftoc One powerful use of server side functions is their use in SQL queries Figure 18 3 shows the use of tax with the part table from figure 6 3 In this figure three rows are inserted into the table then a SELECT test gt test gt test gt test gt test gt test gt CREATE test gt INSERT test gt INSERT test gt INSERT test gt test gt test gt test gt test gt test gt test gt 638 sticker
6. Figure 8 12 IN query rewritten using ANY and EXISTS tables Figure 8 13 shows the NOT IN query from figure 8 11 and the query rewritten using ALL and NOT EXISTS Summary A subquery can represent a fixed value a correlated value or a list of values An unlimited number of subqueries can be used Subqueries can be nested inside other subqueries 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 8 3 OUTER JOINS 81 SELECT name FROM customer WHERE customer id NOT IN SELECT customer id FROM salesorder SELECT name FROM customer WHERE customer id lt gt ALL SELECT customer id FROM salesorder SELECT name FROM customer WHERE NOT EXISTS SELECT customer id FROM salesorder WHERE salesorder
7. My long string test gt SELECT str var column My long string 1 row test gt set date var date test gt lecho date var Thu Aug 11 20 54 21 EDT 1994 test gt set date var2 date M test gt lecho date_var2 Thu Aug 11 20 54 24 EDT 1994 test gt SELECT date var2 column Thu Aug 11 20 54 24 EDT 1994 1 row Figure 16 2 psql variables 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 16 1 PSQL 149 placed into a variable In this case the output of the UNIX date command is captured and placed into the variable The assignment to date_var2 combine
8. lt lt coll lt lt col2 BOOLEAN indicating if coll is equal or a subnet of col2 gt gt coll gt gt col2 BOOLEAN indicating if coll is a supernet of col2 gt gt coll gt gt col2 BOOLEAN indicating if coll is equal or a supernet of col2 Table 9 4 Common operators 94 CHAPTER 9 DATA TYPES test gt SELECT CAST 1 1 1992 AS DATE CAST 1 1 1993 AS DATE ERROR Unable to identify an operator for types date and date You will have to retype this query using an explicit cast test gt SELECT CAST 1 1 1992 AS DATE CAST 1 year AS INTERVAL column 1993 01 01 00 00 00 05 1 row test gt SELECT CAST 1 1 1992 AS TIMESTAMP 1 year s column 1993 01 01 00 00 00 05 1 row Figure 9 3 Error generated by undefined operator type combination 9 6 Support Variables There are several defined variables These are shown in table 9 5 Meaning Meaning CURRENT_DATE current date CURRENT_TIME current time CURRENT_TIMESTAMP current date and time CURRENT_USER user connected to the database Table 9 5 Common variables 9 7 Arrays Arrays allow a column to store several simple data values You can store one dimensional arrays two dimensional arrays or arrays with any number of dimensions An array column is created like an ordinary column except brackets are used to specify the dimensions of the array The number of dimensions and size of each dimension are for documentation purposes o
9. nextval functest_seq Figure 7 3 Examples of sequence function use 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 7 5 USING SEQUENCES TO NUMBER ROWS 67 Currval returns the sequence number assigned by a prior nextval call in the current session It is not affected by nextval calls of other users This allows reliable retrieval of nextval assigned values in later queries 7 5 Using Sequences to Number Rows Configuring a sequence to uniquely number rows involves several steps e Create the sequence e Create the table defining nextval as the column default e During INSERT do not supply a value for the sequenced column or use nextval Figure 7 4 shows the use of a sequence for unique row numbering in the customer table The first state test gt CREATE SEQUENCE customer_seq CREATE test gt CREATE TABLE customer test gt customer id INTEGER DEFAULT nextval customer_seq test gt name CHAR 30 test gt CREATE test gt INSERT INTO customer VALUES nextval customer_seq Bread Makers INSERT 19004 1 test gt INSERT INTO customer name VALUES Wa
10. test gt quantity INTEGER DEFAULT 1 test gt CREATE Figure 6 21 Orderpart table hold only one part number per order Instead of putting the part_1d in the salesorder table the orderpart table 60 CHAPTER 6 JOINING TABLES will hold one row for each part number ordered If five part numbers are in order number 15398 there will be five rows in the orderpart table with order_1d equal to 15398 We have also added a quantity column If someone orders seven of the same part number we put only one row in the orderpart table but set the quantity field equal to 7 We have used DEFAULT to set the quantity to one if no quantity is supplied Notice there is no price field in the orderpart table This is because the price is stored in the part table Anytime the price is needed a join is performed to get the price This allows a part s price to be changed in one place and all references to it automatically updated This new table layout illustrates the master detail use of tables The salesorder table is the master table because it holds information common to each order such as customer and employee identifiers and order date The orderpart table is the detail table because it contains the specific parts making up the order Master detail tables are a common use of multiple tables Figure 6 22 shows a variety of queries using the new orderpart table The queries are of increasing complexity The first query already contains the order
11. 12956 i i 12957 test gt i integer 12958 test gt len integer 12959 12960 test gt 12961 test gt BEGIN 12962 test gt str upper 1 12963 a NN i 12964 test gt ret start with zero length 12965 test gt i 15 12966 test gt len length str 12967 12969 test gt ret ret substr str i 1 12970 test gt issis i 12971 12972 test gt END LOOP 12973 test gt RETURN ret 12974 ki 12975 test gt END 12976 test gt LANGUAGE plpgsql 12977 CREATE De test gt SELECT spread Major Financial Report 12980 spread 12981 12982 12983 MAJOR FINANCIAL REPORT 12984 1 row 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 Figure 18 8 PL PGSQL spread function 174 CHAPTER 18 FUNCTIONS AND TRIGGERS test gt CREATE FUNCTION getstatecode text test gt RETURNS text test gt AS DECLARE test gt state str statename namesTYPE test gt statename_rec record test gt 1 integer test gt len integer test gt matches record test gt search_str text test gt test gt BEGIN test gt state str initcap 1 capitalization match column test gt len length trim 1 test gt 1 2 test gt test gt SELECT INTO statename_rec first try for an exact match test gt FROM statename test gt WHERE name state str test gt IF FOUND
12. COMMIT Figure 10 7 Serializable isolation level SERIALIZABLE isolation provides a stable view of the database for SELECT transactions For transactions containing UPDATE and DELETE queries SERIALIZABLE mode is more complicated SERIALIZABLE isolation forces the database to execute all transactions as though they were run serially one after another even if they are run concurrently If two concurrent transactions attempt to update the same row serializability is impossible When this happens POSTGRESQL forces one transaction to roll back For SELECT only transactions SERIALIZABLE isolation level should be used when you don t want to see other transaction commits during your transaction For UPDATE and DELETE transactions SERIALIZABLE isolation prevents concurrent modification of the same data row and should be used with caution 10 5 Locking Exclusive locks also called write locks prevent other users from modifying a row or an entire table Rows modified by UPDATE and DELETE are exclusively locked automatically for the duration of the transaction This prevents other users from making changes to the row until the transaction is either committed or rolled back For example table 10 3 shows two simultaneous UPDATE transactions affecting the same row One trans 102 CHAPTER 10 TRANSACTIONS AND LOCKS Transaction 1 Transaction 2 Notes BEGIN WORK BEGIN WORK Start both transactions UPDATE row 64 Transaction 1 exclusively locks
13. Jim WHERE name James 1 COMMIT WORK Figure 10 9 SELECT FOR UPDATE 10 6 Deadlocks 103 It is possible to create an unrecoverable lock condition called a deadlock Figure 10 4 illustrates how two transactions become deadlocked In this example each transaction holds a lock and is waiting for the other Transaction 1 Transaction2 Notes BEGIN WORK BEGIN WORK UPDATE row 64 UPDATE row 83 UPDATE row 83 COMMIT WORK Table 10 4 Deadlock Start both transactions Independent rows write locked Holds waiting for transaction 2 to release write lock UPDATE row 64 Attempt to get write lock held by transaction 1 auto ROLLBACK WORK Deadlock detected transaction 2 automatically rolled back Transaction 1 returns from UPDATE and commits transaction s lock to be released One transaction must be rolled back by POSTGRESQL because the two transactions will wait forever Obviously if they had acquired locks in the same order no deadlock would occur 10 7 Summary Single user database queries are concerned with getting the job done Multi user queries must be designed to gracefully handle multiple users accessing the data Multi user interaction can be very confusing The database is constantly changing In a multi user envi ronment improperly constructed queries can randomly fail when users perform simultaneously operations 104 CHAPTER 10 TRANSACTIONS AND LOCKS Queries cannot assume that rows from pre
14. The JAVA interface source code is located in pgsql src interfaces jdbc Once the interface is compiled the file postgresql jar should be copied to the directory containing the other jar files The full path name of postgresql jar must then be added to the CLASSPATH environment variable JAVA programs are compiled using javac and run using java JAVA is both a compiled and interpreted language It is compiled for speed but interpreted when executed so any computer can run the compiled program 17 9 Scripting Languages The previous interfaces used compiled languages Compiled languages require user programs to be compiled into CPU instructions The remaining interfaces are scripting languages Scripting languages execute slower than compiled languages but have several advantages e No compile required e More powerful commands e Automatic creation of variables e Variables can hold any type of data 17 10 PERL Figure 17 9 shows the same application in PERL PERLis good for writing scripts and small applications It is popular for processing text files and generating dynamic web pages using CGI Common Gateway Interface A PERL DBI interface is also available 17 11 TCL TK PGTCLSH PGTKSH Figure 17 10 shows a TCL version of the same application TCL s specialty is accessing other toolkits and applications The TK graphical interface toolkit is one example It is used by TCL when writing graphical applications The TK toolkit has bec
15. The join key is the value used to link entries between tables For example in figure 6 4 648 is the customer key appearing in the customer table to uniquely identify the row and in the salesorder table to refer to that specific customer row Some people might question whether an identification number is needed Should the customer name be used as a join key Using the customer name as the join key is not good because e Numbers are less likely to be entered incorrectly e Two customers with the same name would be impossible to distinguish in a join e Ifthe customer name changes all references to that name would have to change e Numeric joins are more efficient than long character string joins e Numbers require less storage than characters strings In the statename table the two letter state code is probably a good join key because e Two letter codes are easy for users to remember and enter e State codes are always unique e State codes do not change 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5
16. employee_name part_name A waa socececeeoccecec A aacieean ELENE NER EENE R RA A ANELA Fleer Gearworks Inc Lee Meyers Garage Door Spring 1 row Figure 6 9 Four table join Joins can be performed among tables that are only indirectly related Suppose you wish to find employees who have taken orders for each customer Figure 6 10 shows such a query Notice that the query displays just test gt SELECT DISTINCT customer name employee name test gt FROM customer employee salesorder test gt WHERE customer customer_id salesorder customer_id and test gt salesorder employee_id employee employee_id test gt ORDER BY customer name employee name name name A AAA LH Sie eee eo o a a eee Fleer Gearworks Inc Lee Meyers 1 row test gt SELECT DISTINCT customer name employee name COUNT test gt FROM customer employee salesorder test gt WHERE customer customer id salesorder customer_id and test gt salesorder employee id employee employee id test gt GROUP BY customer name employee name test gt ORDER BY customer name employee name name name count Fleer Gearworks Inc Lee Meyers 1 1 row Figure 6 10 Employees who have taken orders for customers the customer and employee tables The salesorder table is used to join the two tables but is not displayed The DISTINCT keyword is used because multiple orders taken by the same employee for the same customer would make that employee appear
17. object oriented PHP HTML interpreted dynamic web pages Table 17 1 Interface summary allow applications to pass queries to POSTGRESQL and receive results The compiled languages execute faster but are harder to program than the interpreted ones This chapter will show the same application using each interface The application is a very simple one that prompts the user for a United States state code and outputs the state name that goes with the code Figure 17 1 shows the sample application being run For clarity the text typed by the user is in bold The Enter a state code AL Alabama Figure 17 1 Sample application being run program displays a prompt the user types AL and the program displays Alabama Though state codes are unique the application is written to allow multiple query return values The application uses the statename table which is recreated in figure 17 2 Additional information about POSTGRESQL interfaces is available in the Programmer s Manual mentioned in section A 3 153 154 CHAPTER 17 PROGRAMMING INTERFACES test gt CREATE TABLE statename code CHAR 2 PRIMARY KEY test gt name CHAR 30 test gt CREATE test gt INSERT INTO statename VALUES AL Alabama INSERT 18934 1 test gt INSERT INTO statename VALUES AK Alaska INSERT 18934 1 Figure 17 2 Statename table 17 1 C Language Interface LIBPQ Libpq is the native C interface to POSTGRESQL Psql and most oth
18. psql test all Welcome to psql the PostgreSQL interactive terminal 13815 13816 B R A 13817 Type copyright for distribution terms 13818 h for help with SQL commands 13819 for help on internal slash commands a g or terminate with semicolon to execute query ae q to quit 13823 13824 13825 test gt CREATE USER demouser2 Boe CREATE USER 13827 13828 test gt ALTER USER demouser2 CREATEDB es ALTER USER 13830 test gt CREATE GROUP demogroup WITH USER demouserl demouser2 13831 13832 CREATE GROUP 13833 test gt CREATE TABLE grouptest col INTEGER 13834 CREATE pce test gt GRANT ALL on grouptest TO GROUP demogroup ae CHANGE 13838 test gt connect test demouser2 En You are now connected to database test as user demouser2 Dn test gt q 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 Figure 20 1 Examples of user administration 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 20 3 CREATING DATABASES 187 group
19. statename code 12840 test gt ORDER BY customer name 12841 dame 12842 128437 A Eren een Eene EA O a ASA 12844 Fleer Gearworks Inc Alabama 12845 j ai Mark Middleton Indiana 12847 Mike Nichols Florida 12848 3 rows 12849 12850 12851 test gt SELECT customer name getstatename customer state pene test gt FROM customer es test gt ORDER BY customer name 12855 name 128561 OO kde AAA Se 12857 12858 Fleer Gearworks Inc Alabama 12859 Mark Middleton Indiana al Mike Nichols Florida 12861 12862 3 rows 12863 12864 oe Figure 18 6 Getting state name using join and function 12867 12868 12869 12870 getstatename 172 CHAPTER 18 FUNCTIONS AND TRIGGERS 18 3 PL PGSQL Functions PL PGSQL is another language for server side functions It is a true programming language While SQL functions only allow argument substitution PL PGSQL has features like variables conditional evaluation and looping PL PGSQL is not installed in each database by default To use it in database test it must be installed by running createlang plpgsql test from the operating system prompt Figure 18 7 shows a PL PGSQL version of the SQL function getstatename from figure 18 5 The only differences are the addition of BEGIN END and the language definition as PL PGSQL test gt CREATE FUNCTION getstatename2 text test gt RETURNS text test gt AS BEGIN test gt SELECT CAST name AS TEXT test gt FROM
20. test gt EXPLAIN SELECT customer_id FROM customer WHERE customer_id 55 ee NOTICE QUERY PLAN 8667 8668 8669 8670 8671 EXPLAIN 8672 test gt CREATE UNIQUE INDEX customer custid idx ON customer customer_id ey CREATE 8675 test gt EXPLAIN SELECT customer_id FROM customer WHERE customer_id 55 9676 8677 NOTICE QUERY PLAN 8678 8679 Index Scan using customer_custid_idx on customer cost 0 00 2 01 rows 1 width 4 ie 8682 EXPLAIN 8683 test gt EXPLAIN SELECT customer_id FROM customer e NOTICE QUERY PLAN 8686 8687 8688 8689 8690 EXPLAIN 8031 test gt EXPLAIN SELECT FROM customer ORDER BY customer_id ae NOTICE QUERY PLAN 8694 8695 ne 8696 Index Scan using customer_custid_idx on customer cost 0 00 42 00 rows 1000 width 4 8697 8698 EXPLAIN 3033 8700 8701 8702 Figure 11 4 More complex EXPLAIN examples 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 Seq Scan on customer cost 0 00 17 50 rows 1 width 4 Seq Scan on customer cost 0 00 15 00 rows 1000 width 4 11 7 SUMMARY 109 is used allowing POSTGRESQL to go directly to the rows where customer_id equals 55 The next one shows a query with no WHERE restriction POSTGRESQL realizes the index is of no use and performs a sequential scan The last query has an ORDER BY that matches an index so POSTGRESQL uses an index scan Even more complex queries can be studied using EXPLAIN as shown in figure 11 5 In this examp
21. test gt INSERT INTO statename VALUES al al ERROR State name must longer than two characters test gt INSERT INTO statename VALUES al alabama INSERT 292898 1 test gt SELECT FROM statename code name AL Alabama 1 row Figure 18 13 Trigger creation 180 CHAPTER 18 FUNCTIONS AND TRIGGERS 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 Chapter 19 Extending POSTGRESQL Using C While POSTGRESQL has a large number of functions operators data types and aggregates there are cases when users need to create their own The previous chapter already showed how
22. 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 Chapter 16 Database Query Tools This chapter covers two popular POSTGRESQL database query tools psql and pgaccess 16 1 PSQL The following sections summarize the capabilities of psq1 The psq manual has detailed information about each item See chapter 2 for an introduction to psql Query Buffer Commands Table 16 1 shows the commands used to control the psql query buffer There is one item of particular Function Command Argument Print p Execute g or file or command Quit q Clear r Edit e file Backslash help SQL help h topic Include file l file Output to file command o file or command Write buffer to file w file Show save query history s file Run subshell command Table 16 1 psql query buffer commands interest edit e This allows editing of the query buffer The e command loads the contents of the query buffer into the default editor When th
23. 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 Chapter 17 Programming Interfaces Psql is ideal for interactively entering SQL commands and for running automated scripts However psql is not ideal for writing applications Fortunately POSTGRESQL has interfaces for many programming languages Programming languages have variables functions conditional evaluation looping and complex input output routines These are required for writing good applications Table 17 1 shows the programming interfaces supported by POSTGRESQL These language interfaces Interface Language Processing Advantages LIBPQ C compiled native interface LIBPGEASY C compiled simplified C ECPG C compiled ANSI embedded SQL C LIBPQ C compiled object oriented C ODBC ODBC compiled application connectivity JDBC JAVA both portability PERL PERL interpreted text processing PGTCLSH TCL TK interpreted interfacing windowing PYTHON PYTHON interpreted
24. 12306 12307 12308 12309 Figure 17 9 PERL sample program 12310 12311 usr local pgsql bin pgtclsh 12312 12313 12314 12315 12316 12317 set conn pg_connect test sf connect to the database 12318 oo puts nonewline Enter a state code s prompt user for a state code 12321 flush Staout 12322 gets stdin state_code 12323 3 send the query 12324 set res pg_exec conn RELA SELECT name 12326 12327 FROM statename 12328 WHERE code state_code 12329 12330 set ntups pg result res numTuples 12331 z pee for set i 0 i lt ntups incr i sf loop through all rows returned 12334 puts stdout lindex pg result res getTuple i 0 sf print the value returned 12335 12336 12337 12338 12339 12340 12341 Figure 17 10 TCL sample program 12342 use Pg load database routines did the query fail die conn gt errorMessage unless PGRES TUPLES OK eq result gt resultStatus pgtclsh sample program pg disconnect conn s disconnect from the database 164 CHAPTER 17 PROGRAMMING INTERFACES usr local bin python python sample program import sys from pg import DB load database routines conn DB test connect to the database sys stdout write Enter a state code prompt user for a state code state_code sys stdin readline state_code state code 1 for name in conn query send the query SELECT name FROM statename WHERE code sta
25. 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 19 4 OPTIONALLY CREATE OPERATORS TYPES AND AGGREGATES 183 test gt SELECT ctof 20 ctof Figure 19 3 Calling function ctof 19 4 Optionally Create Operators Types and Aggregates Operators types and aggregates are built using functions CREATE OPERATOR CREATE TYPE and CREATE AGGREGATE register that a set of functions should behave as an operator type or aggregate They name the new operator type or aggregate and call the supplied functions whenever that name is accessed See CREATE_OPERATOR CREATE_TYPE and CREATE_AGGREGATE for more information 19 5 Summary Extending POSTGRESQL is a complicated process This chapter has covered only the basic concepts As mentioned earlier the Programmer s Manual mentioned in section A 3 has more detailed information 184 CHAPTER 19 EXTENDING POSTGRESQL USING C 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13
26. 1789 test gt 18 39 4790 test gt 4791 INSERT 18840 1 pos test gt INSERT INTO salesorder VALUES 4794 test gt 14673 ee test gt 648 4797 test gt 24 4798 test gt 153 oe test gt 7 19 1994 4801 test gt 7 28 1994 4802 test gt 18 39 4803 4804 test gt da 4805 INSERT 18841 1 4806 4807 pa Figure 6 4 Insertion into company tables 4810 4811 4812 4813 4814 4815 4816 4817 4818 50 CHAPTER 6 JOINING TABLES 6 4 Performing Joins With data spread across multiple tables an important issue is how to retrieve the data Figure 6 5 shows how to find the customer name for a given order number It uses two queries The first gets the customer_id for test gt SELECT customer id FROM salesorder WHERE order id 14673 customer_id test gt SELECT name FROM customer WHERE customer id 648 name Fleer Gearworks Inc 1 row Figure 6 5 Finding customer name using two queries order number 14673 The user then uses the returned customer identification number of 648 in the WHERE clause of the next query That query finds the customer name record where the customer_1d equals 648 We can call this two query approach a manual join because the user manually took the result from the first query and placed that number into the WHERE clause of the second query Fortunately relational databases can perform this join automatically Figure 6 6 shows the same join as figure 6 5 but in
27. 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 2 3 GETTING HELP 7 when you enter a semicolon or backslash g g Here s a good example Let s do SELECT 1 3 but in a different way See figure 2 3 2 Notice the query is spread over three lines Notice the prompt changed test gt SELECT test gt 1 3 test gt column Figure 2 3 Multi line query from gt on the first line to gt on the second line to indicate the query was being continued The semicolon told psql to send the query to the server We could easily have replaced the semicolon with backslash g I don t recommend you type queries as ugly as this one but longer queries will benefit from the ability to spread them over multiple lines You might notice the query is in uppercase Unless you are typing a string in quotes the POSTGRESQL server doesn t care whether words are uppercase or lowercase For stylistic reasons I recommend you enter words special to POSTGRESQL in uppercase Try some queries on your own involving arithmetic Each computation must start with the word SELECT then your computation and finally a semicolon o
28. 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 3 9 DESTROYING TABLES 17 3 9 Destroying Tables This chapter would not be complete without showing how to delete tables It is accomplished using the DROP TABLE command The command DROP TABLE friend will remove the friend table Both the table structure and the data contained in the table will be erased We will be using the friend table in the next chapter so I don t recommend you remove the table at this time Remember to remove only the data in the table without removing the table structure itself use DELETE 3 10 Summary This chapter has have shown the basic operations of any database e Table creation CREATE TABLE e Table destruction DROP TABLE e Displaying SELECT e Adding INSERT e Replacing UPDATE e Removing DELETE This chapter has shown these commands in their simplest forms Real world queries are much more complex The next chapters will show how these simple commands can be used to handle some very complicated tasks 18 CHAPTER 3 BASIC SQL COMMANDS 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 275
29. 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 4 10 REGULAR EXPRESSIONS Test Operation begins with D ZD contains D eh D in second position AD begins with D and contains e 7 D e begins with D contains e and then f D e f contains A B C or D TA D or ABCD contains A or a 1a or Aa does not contain D Ip does not begin with D I D or 7 p begins with D with one optional leading space a ea begins with D with optional leading spaces Sep begins with D with at least one leading space 71 4p ends with G with optional trailing spaces G Table 4 6 Regular expression examples test gt firstname ends with n test gt SELECT FROM friend test gt WHERE firstname n test gt ORDER BY firstname firstname lastname city state age Dean Yeager Plymouth MA 24 1 row test gt firstname contains a non S character test gt SELECT FROM friend test gt WHERE firstname S test gt ORDER BY firstname firstname lastname city state age Hen nono Dean Yeager Plymouth MA 24 Dick Gleason Ocean City NJ 19 Ned Mi11stone Cedar Creek MD 27
30. 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 6 5 THREE AND FOUR TABLE JOINS 51 e salesorder order id 14673 Find that row in the salesorder table e salesorder customer id customer customer_id From the row just found get the customer id Find the equal customer id in the customer table customer name Return name from the customer table You can see the database is performing the same steps as our manual join but much faster Notice that figure 6 6 qualifies each column name by prefixing it with the table name as discussed in section 6 1 While such prefixing is optional in many cases in this example it is required because the column customer_id exists in both tables mentioned in the FROM clause customer and salesorder If this were not done the query would generate an error ERROR Column customer_id is ambiguous You can perform the join in the opposite direction too In the previous query the order number is supplied and the customer name is returned In figure 6 7 the customer name is supplied and the order number returned I have switched the order of items in the FROM clause and in the WHERE clause The ordering of test gt SELECT salesorder order_id test gt FROM salesorder customer test gt WHERE customer name Fleer Gearwor
31. 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 6 12 ORDERING MULTIPLE PARTS test gt SELECT c2 name test gt FROM customer c customer c2 test gt WHERE c customer id 648 AND test gt c country lt gt c2 country test gt ORDER BY c2 name test gt SELECT e2 name e2 hire date test gt FROM employee e employee e2 test gt WHERE e employee id 24 AND test gt e hire date lt e2 hire date test gt ORDER BY e2 hire date e2 name test gt SELECT p2 name p2 cost test gt FROM part p part p2 test gt WHERE p part id 153 AND test gt p cost gt p2 cost test gt ORDER BY p2 cost 59 Figure 6 19 Non equijoins Figure 6 20 shows a new version of the salesorder table Notice that the part id column has been removed test gt CREATE TABLE salesorder test gt test gt test gt test gt test gt test gt test gt CREATE order_id customer_id employee id order_date ship_date payment The customer employee and part tables remain unchanged INTEGER INTEGER joins to customer customer_id INTEGER joins to employee employee id DATE DATE NUMERIC 8 2 Figure 6 20 New salesorder table for multiple parts per order Figure 6 21 shows a new table orderpart This table is needed because the original salesorder table could test gt CREATE TABLE orderpart test gt order id INTEGER test gt part id INTEGER
32. 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 6 14 SUMMARY test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt test gt first query SELECT part name FROM WHERE orderpart part orderpart part_id part part_id AND orderpart order_id 15398 second query SELECT part name orderpart quantity FROM salesorder orderpart part WHERE salesorder customer_id 648 AND salesorder order_date 7 19 1994 AND salesorder order_id orderpart order_id AND orderpart part_id part part_id third query SELECT part name part cost orderpart quantity FROM WHERE customer salesorder orderpart part customer name Fleer Gearworks Inc AND salesorder order_date 7 19 1994 AND salesorder customer_id customer customer_id AND salesorder order_id orderpart order_id AND orderpart part_id part part_id fourth query SELECT SUM part cost orderpart quantity FROM WHERE customer salesorder orderpart part customer name Fleer Gearworks Inc AND salesorder order_date 7 19 1994 AND salesorder customer_id customer customer_id AND salesorder order_id orderpart order_id AND orderpart p
33. 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 7 8 SUMMARY 69 choose the same next available highest number Of course if this happens the number would not be unique Such concurrency problems do not occur when using OIDs or sequences Third it is more reliable to use database supplied unique number generation than to generate unique numbers manually 7 8 Summary Both OIDs and sequences allow the automatic unique numbering of rows OIDs are always created and numbered while sequences require more work to configure Both are valuable tools for uniquely numbering rows 70 CHAPTER 7 NUMBERING ROWS 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196
34. 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 9 2 INSTALLED TYPES 89 Character String Character string types are the most commonly used data types They can hold any sequence of letters digits punctuation and other valid characters Typical character strings are names descriptions and mailing addresses Any value can be stored in a character string However character strings should be used only when other data types are inappropriate The other types provide data validation more compact storage and better performance There are three character string data types TEXT VARCHAR length and CHAR length TEXT does not limit the number of characters stored VARCHAR ength limits the length of the field to length characters Both TEXT and VARCHAR store only the number of characters in the string CHAR length is similar to VARCHAR except it always stores exactly length characters It pads the value with trailing spaces to the specified length It provides slightly faster access than TEXT or VARCHAR Understanding why character string types are different from other data types can be difficult For example you can store 763 as a character string In this case you are storing the symbols 7 6 and 3 not the numeric value 763 You can t add a number to the character string 763 because 1t doe
35. 8994 0 e is 8995 2 8996 8997 1 row 8998 8999 9000 test gt FETCH 2 FROM customer cursor 9001 customer_id 9002 eneen 9003 9004 9005 4 9006 2 rows 9007 9008 9009 test gt FETCH 1 FROM customer_cursor 9010 ona customer_id RL OO TG 9013 3 9014 9015 9016 9017 test gt FETCH 1 FROM customer cursor 9018 f 9019 customer_id 0 aan 2002 2 9023 1 row 9024 ee test gt MOVE 10 FROM customer_cursor 9027 MOVE 9028 test gt FETCH 1 FROM customer_cursor 9029 9030 customer_id 90381 RRSP Eatestne 9032 13 9033 9034 1 row 9035 test gt CLOSE customer_cursor 2036 CLOSE 9037 see test gt COMMIT WORK 9039 COMMIT 9040 9041 9042 1 row Figure 12 2 Cursor usage 114 CHAPTER 12 CONTROLLING RESULTS 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 91
36. BASIC SQL COMMANDS are char columns so you have to put the comparison value in single quotes You also have to match the capitalization exactly See figure 3 10 If you had compared the firstname column to SAM or sam it would have returned no rows Try a few more until you are comfortable test gt SELECT FROM friend WHERE firstname Sam firstname lastname city state age Sam Jackson Allentown PA 22 1 row Figure 3 10 Comparing string fields 3 6 Removing Data with DELETE We know how to add data to the database Now we learn how to remove it Removal is quite simple The DELETE command can quickly remove any or all rows from a table The command DELETE FROM friend will delete all rows from the table friend The query DELETE FROM friend WHERE age 19 will remove only those rows that have an age column equal to 19 Here is a good exercise INSERT a row into the friend table use SELECT to verify the row has been properly added then use DELETE to remove the row This combines the things you learned in the previous sections Figure 3 11 shows an example 3 7 Modifying Data with UPDATE How do you modify data already in the database You could use DELETE to remove the row then INSERT to insert a new row but that is quite inefficient The UPDATE command allows you to update data already in the database It follows a format similar to the p
37. Breaking up the information into separate tables allows us to keep detailed information about customers employees and parts It also allows us to refer to those specific entries as many times as needed by using a unique number This is illustrated in figure 6 2 Customer Employee Part Salesorder Figure 6 2 Joining tables People might question whether it is necessary to use separate tables While not necessary it is often a good idea Without having a separate customer table every piece of information about a customer would have to be stored in the salesorder table every time a salesorder row was added The customer s name telephone number address and other information would have to be repeated Any change in customer information like a change in telephone number would have to be performed in all places that information is stored With a customer table the information is stored in one place and each salesorder points to the customer table This 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 46
38. Insertion of a NULL value or an INSERT that would set col2 to NULL will test gt CREATE TABLE not null test test gt coll INTEGER test gt col2 INTEGER NOT NULL test gt CREATE test gt INSERT INTO not null test test gt VALUES 1 NULL ERROR ExecAppend Fail to add null value in not null attribute col2 test gt INSERT INTO not null test coll test gt VALUES 1 ERROR ExecAppend Fail to add null value in not null attribute col2 test gt INSERT INTO not null test VALUES 1 1 INSERT 174368 1 test gt UPDATE not null test SET col2 NULL ERROR ExecReplace Fail to add null value in not null attribute col2 Figure 14 1 NOT NULL constraint cause the INSERT to fail The figure shows UPDATE of a NULL value also fails Figure 14 2 adds a DEFAULT value for col2 This allows INSERTs that do not specify a value for col2 as illustrated in the figure 127 128 CHAPTER 14 CONSTRAINTS test gt CREATE TABLE not_null_with_default_test test gt coll INTEGER test gt col2 INTEGER NOT NULL DEFAULT 5 test gt CREATE test gt INSERT INTO not_null_with_default_test col1 test gt VALUES 1 INSERT 148520 1 test gt SELECT test gt FROM not_null_with_default_test coll col2 Se E AR EEE 1 5 1 row Figure 14 2 NOT NULL with DEFAULT constraint 14 2 UNIQUE The UNIQUE constraint prevents duplicate values from appearing in the column UNIQUE columns can contain
39. ORDER BY firstname lastname 6620 firstname lastname age 6621 6622 i 6623 Ned Millstone 27 6624 Sandy Gleason 25 6625 6626 Sandy Weber 33 6627 Victor Tabor 22 6628 4 rows 6629 6630 6631 test gt SELECT fl firstname fl lastname fl age 6632 test gt FROM friend fl 6633 6635 test gt SELECT MAX f2 age 6636 8 Bn test gt FROM friend f2 6638 test gt WHERE fl state f2 state 6639 test gt en test gt ORDER BY firstname lastname 6642 firstname lastname age 6643 eee ene qe ores see cpre calas Fonos 6644 6645 Ned Millstone 27 6646 Sandy Gleason 25 ee Sandy Weber 33 6649 Victor Tabor 22 6650 4 rows 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 Figure 8 9 Correlated subquery 78 CHAPTER 8 COMBINING SELECTS Subqueries as List of Values The previous subqueries returned one row of data to the upper query If any of the previous subqueries returned more than one row an error would be generated ERROR More than one tuple returned by a subselect used as an expression However it is possible to use subqueries returning multiple rows Normal comparison operators like equal and less than expect a single value on the left and on the right For example equality expects one value on the left of the and one on the right i e col 3 Two special comparisons IN and NOT IN allow multiple values to appear on the right h
40. Remember if you are making comparisons on columns that could contain NULL values you must test for them specifically Figure 4 4 shows an example We have inserted Jack but the city and state were not known so they are set to NULL The next query s WHERE comparison is contrived but illustrative Because city and state are both NULL you might suspect that the Jack row would be returned However because NULL means unknown there is no way to know if the two NULL values are equal Again POSTGRESQL doesn t guess and refuses to print it 3That is not a double qoute between the O and D Those are two single quotes The lt gt means not equal 22 CHAPTER 4 test gt SELECT FROM friend ORDER BY age DESC firstname lastname city state age Cindy Anderson Denver co 23 Sam Jackson Allentown PA 22 Mike Nichols Tampa FL 20 Mark Middleton Indianapolis IN 4 rows test gt SELECT FROM friend WHERE age gt 0 ORDER BY age DESC firstname lastname city state age Cindy Anderson Denver co 23 Sam Jackson Allentown PA 22 Mike Nichols Tampa FL 20 3 rows test gt SELECT FROM friend WHERE age lt gt 99 ORDER BY age DESC firstname lastname city state age Cindy Anderson Denver
41. co authors of POSTGRES95 vi FOREWORD 0331 0332 0333 0334 0335 0336 0337 0338 0339 0340 0341 0342 0343 0344 0345 0346 0347 0348 0349 0350 0351 0352 0353 0354 0355 0356 0357 0358 0359 0360 0361 0362 0363 0364 0365 0366 0367 0368 0369 0370 0371 0372 0373 0374 0375 0376 0377 0378 0379 0380 0381 0382 0383 0384 0385 0386 0387 0388 0389 0390 0391 0392 0393 0394 0395 0396 0397 0398 0399 0400 0401 0402 0403 0404 0405 0406 0407 0408 0409 0410 0411 0412 0413 0414 0415 0416 0417 0418 0419 0420 0421 0422 0423 0424 0425 0426 0427 0428 0429 0430 0431 0432 0433 0434 0435 0436 0437 0438 0439 0440 0441 0442 0443 0444 0445 0446 0447 0448 0449 0450 0451 0452 0453 0454 0455 0456 0457 0458 0459 0460 0461 0462 Preface This book is about POSTGRESQL the most advanced open source database From its origins in academia POSTGRESQL has moved to the Internet with explosive growth It is hard to believe the advances during the past four years under the guidance of a team of world wide Internet developers This book is a testament to their vision and to the success POSTGRESQL has become The book is designed to lead the reader from their first database query through the complex queries needed to solve real world problems No knowledge of database theory or practice is required Basic knowledge of operating system capabilities is expected like the ab
42. cost tax subtotal shipping total 637 cable 14 29 0 86 15 15 6 00 21 15 638 sticker 0 84 0 05 0 89 3 00 3 89 639 bulb 3 68 0 22 3 90 5 00 8 90 3 rows Figure 18 4 SQL shipping function compute shipping charges based on weight The figure calls shipping to generate a detailed analysis of the tax and shipping charges associated with each part It prints the part number name cost tax subtotal of cost plus tax shipping charge and total of cost tax and shipping charge The SELECT uses trim to remove trailing spaces and narrow the displayed result If tax rate or shipping charges change it is easy to change the function to reflect the new rates Simply use DROP FUNCTION to remove the function and recreate it with new values All user applications will automatically start using the new version because the computations are embedded in the database not in user applications Server side functions can also access database tables Figure 18 5 shows an SQL function that internally accesses the statename table It looks up the proper state name for the state code supplied to the function Figure 18 6 shows two queries which yield identical results The first query joins the customer and statename tables The second query does a SELECT on customer and for each row getstatename is called to find the customer s state name These two quer
43. multiple NULL values however UNIQUE is implemented by creating a unique index on the column Figure 14 3 shows that UNIQUE prevents duplicates CREATE TABLE displays the name of the unique index it creates The test gt CREATE TABLE uniquetest coll INTEGER UNIQUE NOTICE CREATE TABLE UNIQUE will create implicit index uniquetest coll key for table uniquetest CREATE test gt d uniquetest Table uniquetest Attribute Type Modifier desa sia as IS A oa coll integer Index uniquetest coll key test gt INSERT INTO uniquetest VALUES 1 INSERT 148620 1 test gt INSERT INTO uniquetest VALUES 1 ERROR Cannot insert a duplicate key into unique index uniquetest coll key test gt INSERT INTO uniquetest VALUES NULL INSERT 148622 1 test gt INSERT INTO uniquetest VALUES NULL INSERT Figure 14 3 Unique column constraint figure also shows multiple NULL values can be inserted into a UNIQUE column If a UNIQUE constraint is made up of more than one column UNIQUE cannot be used as a column constraint 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10
44. test gt test gt test gt test gt CREATE test gt CHAPTER 13 TABLE MANAGEMENT CREATE TABLE service request customer id INTEGER description text cre user text DEFAULT CURRENT USER cre timestamp timestamp DEFAULT CURRENT TIMESTAMP CREATE TABLE service_request_log test gt customer_id INTEGER test gt description text test gt mod_type char 1 test gt mod_user text DEFAULT CURRENT_USER test gt mod_timestamp timestamp DEFAULT CURRENT_ TIMESTAMP CREATE test gt CREATE RULE service request update AS UPDATE rule test gt ON UPDATE TO service request test gt DO test gt INSERT INTO service request log customer id description mod type test gt VALUES old customer id old description U CREATE 19670 1 test gt CREATE RULE service request delete AS DELETE rule test gt ON DELETE TO service request test gt DO test gt INSERT INTO service request log customer id description mod type test gt VALUES old customer id old description D CREATE 19671 1 Figure 13 10 Rules to log table changes 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 963
45. the constants to be inserted However there is a second form of the INSERT statement It allows the output of a SELECT to be used to insert values into a table Suppose we wish to add all our friends from the friend table to the customer table Figure 8 17 shows that instead of a VALUES clause INSERT can use the output of SELECT to insert data into the table Each column test gt INSERT INTO customer name city state country test gt SELECT trim firstname lastname city state USA test gt FROM friend INSERT 0 6 Figure 8 17 Using SELECT with INSERT of the SELECT matches a receiving column in the INSERT Column names and character string constants can be used in the SELECT output The line INSERT 0 6 shows six rows were inserted into the customer table A zero object identifier is returned because more than one row was inserted Inserting into the customer name column presents an interesting challenge The friend table stores first and last names in separate columns The customer table has a single name column The only solution is to combine the firstname and lastname columns with a space between them For example a firstname of Dean and lastname of Yeager must be inserted into customername as Dean Yeager This is possible using trim and the operator Trim removes trailing spaces Two pipe symbols allow character strings to be joined together to form a single string a process called concatenation In
46. 1 The backslash removes any special meaning from the character that follows it To test for a literal backslash use two backslashes like This is different from LIKE special character literal handling where was used to test for a literal percent sign Because regular expressions have a powerful special character command set creating them can be difficult Try some queries on the friend table until you are comfortable with regular expression comparisons S Actually POSTGRESQL regular expressions are like egrep extended regular expressions 30 CHAPTER 4 CUSTOMIZING QUERIES test gt SELECT FROM friend test gt ORDER BY firstname firstname lastname city state age t t t Dean Yeager Plymouth MA 24 Dick Gleason Ocean City NJ 19 Ned Millstone Cedar Creek MD 27 Sandy Gleason Ocean City NJ 25 Sandy Weber Boston MA 33 Victor Tabor Williamsport PA 22 6 rows test gt firstname begins with S test gt SELECT FROM friend test gt WHERE firstname test gt ORDER BY firstname firstname lastname Ss nnn nn i Sandy Gleason Sandy Weber 2 rows test gt firstname has mes city state age Ocean City INJ 25 Boston MA 33 an e in the second position test gt SELECT FROM friend test gt WHERE firstname e test gt ORDER BY firstname firstname las
47. 11760 11761 11762 char state code 3 holds state code entered by user 11763 char query string 256 holds constructed SQL query 11764 PGconn conn holds database connection 11765 PGresult res holds query result 11766 f E int 155 11767 11768 11769 conn PQconnectdb dbname test connect to the database 11770 11771 if PQstatus conn CONNECTION BAD did the database connection fail 11772 11773 A E A 11774 fprintf stderr Connection to database failed n 11775 fprintf stderr s PQerrorMessage conn 11776 exit 1 11777 11778 11779 er i 11780 printf Enter a state code prompt user for a state code 11781 scanf 2s state_code 11782 11783 sprintf query string create an SQL query string nies SELECT name 11785 11786 FROM statename 11787 WHERE code s state code 11788 11789 res PQexec conn query string send the query 11790 11791 E 11792 if PQresultStatus res PGRES TUPLES OK did the query fail 11793 11794 fprintf stderr SELECT query failed n 11795 PQclear res 11796 PQfinish comn 11797 11798 exit 1 11799 11800 11801 for i 0 i lt PQntuples res i loop through all rows returned o printf s n PQgetvalue res i 0 print the value returned 11804 11805 PQclear res free result 11806 Tur PQfinish conn disconnect fro
48. 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 17 5 COMPILING PROGRAMS JX libpgeasy sample program include lt stdio h gt include lt libpq fe h gt include lt libpgeasy h gt int main char state_code 3 char query string 256 char state name 31 connectdb dbname test printf Enter a state code scanf 2s state code sprintf query string SELECT name FROM statename WHERE code s state code doquery query string while fetch state name END OF TUPLES printf s n state name disconnectdb return 0 E A d fe libpgeasy header file holds state code entered by user holds constructed SQL query holds returned state name connect to the database prompt user for a state code create an SQL query string send the query loop through all rows returned print the value returned disconnect from the database Figure 17 5 libpgeasy sample program 157 158 CHAPTER 17 PROGRAMMING INTERFACES Je ecpg sample program of include lt stdio h gt EXEC SQL INCLUDE sqlca ecpg header file EXEC SQL WHENEVER SQLERROR sqlprint int main EXEC SQL BEGIN DECLARE SECTION char
49. 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 20 5 BACKUP AND RESTORE 189 uses indent on the remote machine to verify the users connecting to database sales from host 192 168 7 12 Connections are rejected from hosts and networks not appearing the file For more information see the file data pg_hba conf and the Administrator s Guide mentioned in appendix A 3 For database client applications the environment variables PGHOST PGPORT PGUSER PGPASSWORD PG DATESTYLE PGTZ PGCLIENTENCODING and PGDATABASE are helpful for setting default connection parameters and options The POSTGRESQL documentation has more information about these 20 5 Backup and Restore Database backups allow databases to be restored if a disk drive fails a table is accidentally dropped or a database file is accidentally deleted If the databases are idle a standard file system backup is suf
50. 14 on page 33 TIME allows storage of hour minute and second separated by colons TIMESTAMP represents storage of both date and time i e 2000 7 12 17 34 29 INTERVAL represents an interval of time like 5 hours or 7 days INTERVAL values are often generated by subtracting two TIMESTAMP values to find the elapsed time For example 1996 12 15 19 00 40 minus 1996 12 8 14 00 10 results in an INTERVAL value of 7 05 00 30 which is seven days five hours and thirty seconds Temporal types can also handle timezone designations Logical The only logical type is BOOLEAN A BOOLEAN field can store only true or false and of course NULL too You can input true as true t yes y or 1 False can be input as false f no n or 0 While true and false can be input in a variety of ways true is always output as t and false as f Geometric The geometric types allow storage of geometric primitives The geometric types are POINT LSEG PATH BOX CIRCLE and POLYGON Table 9 2 shows the geometric types and typical values Types Example Notes POINT 2 7 x y coordinates LSEG 0 0 1 3 start and stop points of line segment PATH 0 0 3 0 4 5 1 6 O is a closed path is an open path Box 1 1 3 opposite corner points of a rectangle CIRCLE lt 1 2 60 gt center point and radius POLYGON 3 1 3 3 1 0 points form closed polygon Table 9 2 Geometric types Network The network types are INET CIDR and MACADDR INET all
51. 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 Appendix C PostgreSQL Non Standard Features by Chapter This section outlines the non standard features covered in this book Chapter 1 None Chapter 2 Psql is a unique feature of POSTGRESQL Chapter 3 None Chapter 4 Use of regular expressions SET SHOW and RESET are features unique to POSTGRESQL Chapter 5 None Chapter 6 None Chapter 7 OID s sequences and SERIAL are unique features of POSTGRESQL Chapter 8 FROM in UPDATE is a unique features of POSTGRESQL Some databases support the creation of tables by SELECT Chapter 9 Most databases support only a few of the many datatypes functions and operators included in POSTGRESQL Arrays are a unque features of POSTGRESQL Large objects are implemented differently by other database systems Chapter 10 None Chapter 11 CLUSTER VACUUM and EXPLAIN are features unique to POSTGRESQL Chapter 12 LIMIT is implemented by a few other database systems Chapter 13 Inheritance RULES LISTEN and NOTIFY
52. 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 6 9 UNJOINED TABLES 97 vegetable table the rabbit row is duplicated three times in the output This is a one to many join There is no join for the 508 cat row in vegetable table so the 508 cat row does not appear in the output This is an example of a one to none join 6 9 Unjoined Tables When joining tables it is necessary to join each table mentioned in the FROM clause by specifying joins in the WHERE clause If you list a table name in the FROM clause but fail to join 1t in the WHERE clause the effect is to mark that table as unjoined This causes it to be paired with every row in the query result Figure 6 16 illustrates this effect using tables from figure 6 15 The SELECT does not join any column from animal to any test gt SELECT test gt FROM animal vegetable animal_id name animal_id name 507 rabbit 507 lettuce 508 cat 507 lettuce 507 rabbit 507 carrot 508 cat 507 carrot 507 rabbi
53. 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 Chapter 8 Combining SELECTS This book has covered various topics like regular expressions aggregates and joins These are powerful SQL features that allow the construction of complex queries However in some cases even these tools are not enough This chapter shows how SELECTs can be combined to create even more powerful queries 8 1 UNION EXCEPT INTERSECT Clauses Sometimes a single SELECT statement cannot produce the desired result UNION EXCEPT and INTERSECT allow SELECT statements to be chained together allowing more complex queries to be constructed For example suppose we want to output the friend table s firstname and lastname in the same column Normally two queries would be required one for each column However with UNION the output of two SELECTs can be combined in a single query as shown in figure 8 1 The query combines two columns into a test gt SELECT firstname test gt FROM friend test gt UNION test gt SELECT lastname test gt FROM friend test gt ORDER BY 1 firstna
54. 639 bulb CREATE INSERT 20867 1 INSERT 20868 1 INSERT 20869 1 SELECT FROM pa TABLE part part_id INTEGER name CHAR 30 cost NUMERIC 8 2 weight FLOAT INTO part VALUES 637 cable 14 29 5 INTO part VALUES 638 sticker 0 84 1 INTO part VALUES 639 bulb 3 68 3 part_id name cost tax cost cost tax cost AS total rt ORDER BY part_id part_id 3 rows name cost tax total 0 84 0 05 3 68 0 22 637 cable 14 29 0 86 15 15 0 89 3 90 Figure 18 3 Recreation of the part table 170 CHAPTER 18 FUNCTIONS AND TRIGGERS displays columns from the part table with additional computed columns showing tax and cost plus tax Figure 18 4 shows a more complex function that computes shipping charges The function uses CASE to test gt CREATE FUNCTION shipping numeric test gt RETURNS numeric test gt AS SELECT CASE test gt WHEN 1 lt 2 THEN CAST 3 00 AS numeric 8 2 test gt WHEN 1 gt 2 AND 1 lt 4 THEN CAST 5 00 AS numeric 8 2 test gt WHEN 1 gt 4 THEN CAST 6 00 AS numeric 8 2 test gt END test gt LANGUAGE sql CREATE test gt SELECT part_id test gt trim name AS name test gt cost test gt tax cost test gt cost tax cost AS subtotal test gt shipping weight test gt cost tax cost shipping weight AS total test gt FROM part test gt ORDER BY part_id part id name
55. 7 9 returns true if col is less than all three values IN is the same as ANY and NOT IN is the same as lt gt ALL Normally you can use operators like equal and greater than only with subqueries returning one row With ANY and ALL comparisons can be made with subqueries returning multiple rows They allow you to specify whether any or all of the subquery values must compare as true EXISTS returns true if the subquery returns any rows and NOT EXISTS returns true if the subquery returns no rows By using a correlated subquery EXISTS allows complex comparisons of upper query values inside the subquery For example two upper query variables can be compared in the subquery s WHERE clause EXISTS and NOT EXISTS do not compare anything in the upper query so it does not matter which columns are returned by the subquery For example figure 8 12 shows the IN subquery from figure 8 10 and the query rewritten using ANY and EXISTS Notice the EXISTS subquery uses a correlated subquery to join the employee id columns of the two SELECT name FROM employee WHERE employee id IN SELECT FROM employee id salesorder WHERE order date 7 19 1994 SELECT name FROM employee WHERE employee id ANY SELECT employee id FROM salesorder WHERE order date 7 19 1994 SELECT name FROM employee WHERE EXISTS SELECT employee id FROM salesorder WHERE salesorder employee id employee employee id AND order_date 7 19 1994
56. 9 5 SUPPORT OPERATORS 93 test gt SELECT date part year 5 8 1971 ERROR Function date part unknown unknown does not exist Unable to identify a function that satisfies the given argument types You may need to add explicit typecasts test gt SELECT date part year CAST 5 8 1971 AS DATE date_part 1971 1 row Figure 9 2 Error generated by undefined function type combination Type Function Example Returns Character coll col2 append col on to the end of coll String col pattern BOOLEAN col matches regular expression pattern col pattern BOOLEAN col does not match regular expression pattern pa col pattern same as but case insensitive 13 col pattern same as but case insensitive J col pattern BOOLEAN col matches LIKE pattern LIKE col LIKE pattern same as ms col pattern BOOLEAN col does not match LIKE pattern NOT LIKE col NOT LIKE pattern same as Number Icol factorial coll col2 addition coll col2 subtraction coll col2 multiplication coll col2 division coll col2 remainder modulo coll col2 coll raised to the power of col2 Temporal coll col2 addition of temporal values OVERLAPS Geomeno Network coll col2 cl c2 OVERLAPS c3 c4 subtraction of temporal values BOOLEAN indicating col s overlap in time see psql s do for a list of geometric operators lt lt coll lt lt col2 BOOLEAN indicating if coll is a subnet of col2
57. All rights reserved I have completed my first draft except chapter 20 The appendix also needs to be completed You are seeing it as it is being written I am interested in any comments you may have including typographic errors places with not enough detail or too much detail missing topics extraneous topics confusing sentences poor word choice etc The PDF version has numbers appearing in the margins to allow you to easily refer to specific lines in the book People reading the web version may refer to specific URLS Please mention the date of May 30 2000 when referring to this document You may contact me at mailto pgman candle pha pa us A current copy may be retrieved from http ww postgresql org docs awbook html Also it is available from the POSTGRESQL FAQ s and Documentation page http www postgresql org docs It is updated automatically every night This book is set in Bitstream Century Old Style 11 point Keep in mind that this is to be printed as a book In the PDF version diagrams may not appear on the same pages that refer to them They will appear on the facing page when printed in book format A ADDISON WESLEY iii iv NOTE TO REVIEWERS 0199 0200 0201 0202 0203 0204 0205 0206 0207 0208 0209 0210 0211 0212 0213 0214 0215 0216 0217 0218 0219 0220 0221 0222 0223 0224 0225 0226 0227 0228 0229 0230 0231 0232 0233 0234 0235 0236 0237 0238 0239 0240 0241 0242 0243 0244 0245 02
58. BDUDQUED S caca amps aikana Aa A tierde ARR RGR A 63 Outer Jon 2 4 ie aar a ad a ene ke Bee Re a B ed o Rc 8 4 Subqueries in Non SELECT Queries 6 ee en UPDATE WEEROM na ARA EEN RR AA BNR ATEA A 8 6 Herne Data Using SRLECT eps mnd RE en EG OR hk ae ne SU amp 87 Creating Tables Using SELECT cerro RIA ARA eds 8S UU nen EERDER ELEN Re EE 9 Data Types 9 1 Purposeof Data Types sca eek Oa haa Hehe ee eke ED WEE a 92 TSE Types si bbe a an hae a Pe he ae Shae a a 9 3 Type Conversion using CAST criar eee ed ba HEE OEE Eee OES DA DUDE PGC es eh ae RES eR A R S ER EARS ROE 4 oS Sapport Operators ec c cs tal Sed add Wht ede dwha doe obs eS a ed SZ 96 Support MIOS ese cee Ras tar we Een ws A B ee Save ea E OE cca eG an Bere Goa eer pte oa ent es Spo ee GO Ge Ge 98 Lape ieee BLOBS 216 08 44 2ee a RAR SAS Se ee SRS A lt ese EN 10 Transactions and Locks 101 WarisachiOns annen aod AAA BO ed ee Pw ea 10 2 Multi Statement Transactions 0 0 4 6 ae aen he ER ER ae 10 3 Visibility of Committed Transactions 1 2 ee te ee es 10 4 Read Committed and Serializable Isolation Levels E 244645 265 emia CoRR RR III 10 6 Deadlocks cc sara ta Oe eee ws Ed BOR SR Aw seeden PW oS wid oe a IAS x on RA A a RA A Rn Od eee as 11 Performance 11 1 Indexes 11 2 Unique 11 3 Cluster 11 4 Vacuum 11 5 Vacuum TA o a ae 0 a rd O ae se a RP a RP o a eed A dare Did TLG ERPLAIN eee dae ere EW EEE B BER eH Ee BN
59. FROM customer c customer c2 salesorder s test gt WHERE c customer_id 648 AND test gt c zipcode c2 zipcode AND test gt c2 customer_id s customer_id AND test gt c2 customer_id lt gt 648 test gt SELECT c2 name s order_id p name test gt FROM customer c customer c2 salesorder s part p test gt WHERE c customer_id 648 AND test gt c zipcode c2 zipcode AND test gt c2 customer_id s customer_id AND test gt s part_id p part_id AND test gt c2 customer_id lt gt 648 Figure 6 18 Examples of self joins using table aliases The first figure uses c as an alias for the customer table and c2 as a secondary alias for customer It finds all customers in the same zipcode as customer number 648 The second query finds all customers in the same zipcode as customer number 648 It then finds the order numbers placed by those customers We have restricted the c2 table s customer identification number to not equal 648 because we don t want customer 648 to appear in the result The third query goes farther by retrieving the part numbers associated with those orders 6 11 Non Equijoins Equijoins are the most common type of join They use equality comparisons to join tables Figure 6 19 shows our first non equijoin The first query is a non equijoin because it uses a not equal lt gt comparison to perform the join It returns all customers not in the same country as customer number 648 The second query uses
60. FROM o oeoa aoon ON ede ae el Hee ee An 140 15 2 Example of COPY FROM 0 cba a Bm A ed 140 15 3 Exampleof COPY TO USING DELIMITERS 4 44 a an a eene do 141 15 4 Example of COPY FROM USING DELIMITERS eee ee ee eee 141 15 5 COPY usine sidon and sldOUE ae aa aanne emaa a na Oe a a A 142 UNO CO backslash ROME eren eene de ea AICA A 142 16 1 Exampleof II 147 16 2 BET Variables iee o e be oe e a da e ad r ee ad a 148 16 3 Pgaccess op nming WINQOW s ea deccal ea aa 151 16 4 Pgaccess table Window soe stea a be aa B Ae Beed a ae 152 17 1 Sample application being run saosaoa AA 153 TAA SRAME Es ee a n d ea aa A 154 17 3 Libpg data NOW s es nen wanne eee ew ee Oe a wee a Hae we 154 17 4 Libby sample program lt i coce ceada eRe ee e a aa e ARAS 155 17 9 MODE sample propro zene RRA AAA AAA 157 17 6 Echg sample program eee eee eee eee ee eee 158 L77 ADD ES sample programi peci cco RS weeen Wenen Wid 159 17 8 JAVA Sample programi ss s ees aak Eee B en B ds a Ee 162 17 9 PERL sample progra 14 4 0 aon ader mate RAR GEE EERE OES ee ed 163 POV CL Sample PORTA occa a ee aa a a B a ee 163 17 11 PYTHON Sample Droa shear ik Gok Sw Bay Re oe ae De ome Bee a gh e 164 17 12PHP sample program Input eee eee ee eee 164 17 13PHP sample program Output ck ee ee hh hea eee wae PRR ESE REDS 165 18 1 SOE II 168 INE SOL far MACO ee oe ERA ne ee A ARA 169 18 3 Recreation of the pay ta
61. INTEGER test gt col2 INTEGER test gt PRIMARY KEY coll col2 test gt NOTICE CREATE TABLE PRIMARY KEY will create implicit index primarytest2 pkey for table primarytest2 CREATE test gt CREATE TABLE foreigntest2 col3 INTEGER test gt col4 INTEGER test gt FOREIGN KEY col3 col4 REFERENCES primarytest2 test gt E NOTICE CREATE TABLE will create implicit trigger s for FOREIGN KEY check s CREATE Figure 14 12 Example of a multi column foreign key Handling of NULL Values in the Foreign Key A NULL value cannot reference a primary key A single column foreign key is either NULL or matches a primary key In a multi column foreign key there are cases where only part of a foreign key can be NULL The default behavior allows some columns in a multi column foreign key to be NULL and some not NULL Using MATCH FULL in a multi column foreign key constraint requires all columns in the key to be NULL or all columns to be not NULL Figure 14 13 illustrates this First the tables from previous figure 14 12 are used to show that the default allows one column of a foreign key to be set to NULL Table matchtest is created with the MATCH FULL foreign key constraint option MATCH FULL allows all key columns to be set to NULL but rejects the setting of only some multi column key values to NULL Frequency of Foreign Key Checking By default foreign key constraints are checked at the end of each INSERT UPDATE and DE
62. OF POSTGRESQL software that rivals commercial database offerings By allowing everyone to see the source code and con tribute POSTGRESQL continues to improve every day The remainder of this book shows how to use this amazing piece of software 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 Chapter 2 Issuing Database Commands At this point the book assumes you have e POSTGRESQL installed e POSTGRESQL server running e You are a configured POSTGRESQL user e You have created a database called test If not please see appendix B In this chapter you will learn how to connect to the database server and issue simple commands to the POSTGRESQL server 2 1 Starting a Database Session POSTGRESQL uses a client s
63. Sandy Gleason Ocean City INJ 25 Sandy Weber Boston MA 33 Victor Tabor Williamsport PA 22 6 rows Figure 4 18 Complex regular expression queries 31 32 CHAPTER 4 CUSTOMIZING QUERIES 4 11 CASE Clause Many programming languages have conditional statements stating if condition is true then do something else do something else This allows execution of statements based on some condition While SQL is not a procedural programming language it does allow conditional control over what data is returned from a query The WHERE clause uses comparisons to control row selection The CASE statement allows comparisons in column output Figure 4 19 shows a query using CASE to create a new output column showing adult or minor as appropriate based on the age field Of course the values adult and minor do not appear in the table friend test gt SELECT firstname test gt age test gt CASE test gt WHEN age gt 21 THEN adult test gt ELSE minor test gt END test gt FROM friend test gt ORDER BY firstname firstname age case Ee A PEA Dean 24 adult Dick 19 minor Ned 27 adult Sandy 25 adult Sandy 33 adult Victor 22 adult 6 rows Figure 4 19 CASE example The CASE clause allows the creation of those conditional strings A more complex example is shown in figure 4 20 In this example there are multiple WHEN clauses The AS clause is used to label the column with the word distance Though I
64. Table friend Each friend is listed as a separate row in the table The table records five pieces of information about each friend firstname lastname city state and age Each friend is on a separate row Each column contains the same type of information This is the type of structure that makes relational databases successful Relational databases allow you to select certain rows of data certain columns of data or certain cells You could select the entire row for Mike the entire column for City or a specific cell like Denver There are synonyms for the terms table row and column Table is more formally referred to as a relation or class row as record or tuple and column as field or attribute 3 2 Creating Tables Let s create our own table and call it friend The psql statement to create the table is shown in figure 3 2 You don t have to type it exactly like that You could have used all lowercase or you could have written it in test gt CREATE TABLE friend test gt firstname CHAR 15 test gt lastname CHAR 20 test gt city CHAR 15 test gt state CHAR 2 test gt age INTEGER test gt CREATE Figure 3 2 Create table friend one long line and it would have worked just the same Let s look at it from the top down The words CREATE TABLE have special meaning to the database server They indicate that the next request from the user is to create a table You will find most SQL requests can be quickly i
65. We could have put the animals in the same table but it was clearer to keep them separate In most cases we deal with the animal types separately However suppose we need to list all the animals both aquatic and terrestrial There is no single SELECT that will show animals from both tables We cannot join the tables because there is no join key Joining is not desired We want rows from the terrestrial_animal table and the aquatic_animal table output together in a single column Figure 8 2 shows how these two tables can be combined with UNION test gt INSERT INTO terrestrial_animal name VALUES tiger INSERT 19122 1 test gt INSERT INTO aquatic_animal name VALUES swordfish INSERT 19123 1 test gt SELECT name test gt FROM aquatic_animal test gt UNION test gt SELECT name test gt FROM terrestrial_animal name swordfish tiger 2 rows Figure 8 2 Combining two tables with UNION By default UNION prevents duplicate rows from being displayed For example figure 8 3 inserts penguin into both tables However penguin is not duplicated in the output To preserve duplicates you must use UNION ALL as shown in figure 8 4 You can do more complex things when chaining SELECTs EXCEPT allows all rows to be returned from the first SELECT except rows that also appear in the second SELECT Figure 8 5 shows an EXCEPT query While the aquatic_animal table contains swordfish and penguin the query returns only swordfish Penguin is
66. a single query This query shows all the elements necessary to perform the join of two test gt SELECT customer name query result test gt FROM customer salesorder query tables test gt WHERE customer customer_id salesorder customer id AND table join test gt salesorder order_id 14673 query restriction name Fleer Gearworks Inc 1 row Figure 6 6 Finding customer name using one query tables e The two tables involved in the join are specified in the FROM clause e The two columns needed to perform the join are specified as equal in the WHERE clause e The salesorder table s order number is tested in the WHERE clause e The customer table s customer name is returned from the SELECT Internally the database performs the join by salesorder customer_id is a foreign key because it points to another table s primary key This is covered in more detail in section 6 13 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911
67. as needed by the client Figure 12 2 shows an example of cursor usage Notice cursor activity must take place inside a transaction Cursors are declared using DECLARE CURSOR FOR SELECT Result rows are retrieved using FETCH MOVE allows the user to move the cursor position CLOSE releases all rows stored in the cursor See the DECLARE FETCH MOVE and CLOSE manual pages for more information 12 3 Summary LIMIT specifies which rows to return Cursors allow dynamic row retrieval The difference between LIMIT and cursors is that LIMIT specifies the rows as part of the SELECT while cursors allow dynamic fetching of rows LIMIT and cursors offer new ways to tailor your queries so you get exactly the results you desire 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 12 3 SUMMARY 113 test gt BEGIN WORK 8977 8979 test gt DECLARE customer_cursor CURSOR FOR nie test gt SELECT customer_id FROM customer 8982 SELECT 8983 test gt FETCH 1 FROM customer_cursor 939 customer id 8985 EE i Re 8987 1 8988 8989 1 row 8990 Ke test gt FETCH 1 FROM customer_cursor 8993 customer_id
68. called triggers which are called automatically when a table is modified 18 1 Functions Server side functions can be written in several languages SQL e PL PGSQL e PL TCL PL PERL C SQL and PL PGSQL functions will be covered in this chapter C functions are more complex and will be covered in chapter 19 18 2 SQL Functions SQL functions allow queries to be named and stored in the database for later access This section shows a variety of SQL functions of increasing complexity Functions are created using the CREATE FUNCTION command and removed with DROP FUNCTION CREATE FUNCTION requires the following information 167 168 CHAPTER 18 FUNCTIONS AND TRIGGERS e Function name Number of function arguments e Data type of each argument e Function return type e Function action e Language used by function action Figure 18 1 shows the creation of a simple SQL function to convert from Fahrenheit to centigrade It supplies test gt CREATE FUNCTION ftoc float test gt RETURNS float test gt AS SELECT 1 32 0 5 0 9 0 test gt LANGUAGE sql CREATE test gt SELECT ftoc 68 ftoc Figure 18 1 SQL ftoc function the following information to CREATE FUNCTION e Function name is ftoc e Function takes one argument of type float e Function returns a float e Function action is SELECT 1 32 0 5 0 9 0 e Function language is SQL Most functions only return one value SQL functions can return mul
69. circumstances where you need to explicitly convert one type to another you can use CAST to perform the conversion To convert val to an INTEGER use CAST val AS INTEGER To convert a column date_col of type DATE to type TEXT use CAST date col AS TEXT You can also perform type casting using double colons i e date_col text or num_val numeric 10 2 9 4 Support Functions Functions allows access to specialized routines from SQL Functions take one or more arguments and return a result Suppose you want to uppercase a value or column There is no command for uppercase but there is a function that will do it POSTGRESQL has a function called upper Upper takes a single string argument and returns the argument in uppercase The function call upper col calls the function upper with col as its argument and returns col in uppercase Figure 9 1 shows an example of the use of the upper function test gt SELECT FROM functest name upper Figure 9 1 Example of a function call There are many functions available Table 9 3 shows the most common ones organized by the data types they support Psql s df shows all defined functions and their arguments Section 16 1 has information about all psql commands If you call a function with a type for which it is not defined you will get an error as shown in the first query of figure 9 2 In the first query 5 8 1971 is a character string not a date The second query converts 5 8 1971 to a date
70. coding Wieck Jan in Hamburg Germany wieck debis com overhauled the query rewrite rule system wrote our procedural languages PL pgSQL and PL Tcl and added the NUMERIC DECIMAL type Major Developers Cain D Arcy J M in Toronto Ontario Canada darcy druid net worked on the Tel interface Py GreSQL and the INET type Dal Zotto Massimo near Trento Italy dz cs unitn it has done locking code and other improvements Elphick Oliver in Newport Isle of Wight UK olly lfix co uk maintains the PostgreSQL package for Debian GNU Linux Horak Daniel near Pilzen Czech Republic dan horak email cz did the WinNT port of PostgreSQL using the Cygwin environment Inoue Hiroshi in Fukui Japan Inoue tpf co jp improved btree index access IX X ACKNOWLEDGEMENTS e Ishii Tatsuo in Zushi Kanagawa Japan t ishii sra co jp handles multi byte foreign language support 0595 and porting issues de e Martin Dr Andrew C R in London England martin biochem ucl ac uk helped in the Linux and Irix nies FAQ s including some patches to the PostgreSQL code 0600 0601 Mergl Edmund in Stuttgart Germany E Mergl bawue de created and maintains pgsql perl5 He 0602 also created DBD Pg which is available via CPAN ee e Meskes Michael in Dusseldorf Germany meskes postgresql org handles multi byte foreign lan oe guage support and maintains ecpg 0607 0608 e Mount Peter in Maidstone Kent United Kingdom peter retep org uk ha
71. connection information SQL queries and detailed performance statistics When the postmaster is started its output should be sent to a file in the POSTGRESQL home directory That file can then be used to monitor database activity See the postmaster and postgres manual pages for a complete list of output options To specify flags to be passed to each postgres process use the postmaster 0 flag Another way to monitor the database is by using ps The ps operating system command displays information about system processes including information about the postmaster and postgres processes It is a good tool for analyzing POSTGRESQL activity particularly for diagnosing problems The ps command can display information about a process s e Current CPU usage e Total CPU usage e Start time e Memory usage e Disk operations on some operating systems Each operating system uses different ps flags to output these values A typical display is USER PID CPU TIME STARTED VSZ INBLK OUBLK COMMAND postgres 18923 45 4 0 27 79 1 15PM 2140 34 1 usr local postgres In this case process 18923 is using 45 4 of the CPU has used 27 79 seconds of CPU time was started at 1 15PM has read 34 blocks and has written 1 block To identify who is using each postgres process most operating systems allow ps to display connection information e Username e User s network address 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14
72. fruit lo_unlink Figure 9 6 Using large images usr images peach jpg into the database The function call returns an OID which is used to refer to the imported large object The OID value is stored in fruit image Lo_export uses the OID value to find the large object stored in the database and places the image into the new file tmp outimage jpg The 1 returned by lo_export indicates a successful export Lo_unlink removes large objects Full pathnames must be used with large objects because the database server is running in a different directory than the psql client Files are imported and exported by the postgres user so postgres must have permission to read the file for lo_import and directory write permission for lo export Because large objects use the local filesystem users connecting over a network cannot use lo_import and lo_export They can use psql s lo_import and lo_export commands 9 9 Summary Care should be used when choosing data types The many data types give users great flexibility Wise decisions about column names and types give the database structure and consistency It also improves performance and allows efficient data storage Don t choose types hastily you will regret it later Chapter 10 Transactions and Locks Up to this point we have used POSTGRESQL as a sophisticated filing cabinet However a database is much more It allows users to view and modify information simultaneously It helps e
73. gt SELECT change statename AL Bermuda 13227 change_statename 132987 2 ae eee a a 13229 13230 13231 1 row 13232 13233 13234 test gt SELECT FROM statename 13235 code name 13236 ______ NN 13237 13238 AL Bermuda 13239 1 row 13240 13241 13242 test gt SELECT change statename AL 13243 change statename 13244 13245 13246 t 13247 1 row 13248 13249 13250 test gt SELECT change statename AL row was already deleted 13251 change statename 13252 13258 GIES RSS 13254 f 13255 13256 a 13257 13258 13259 Figure 18 12 Example of change_statename 13260 13261 13262 13263 13264 13265 13266 178 CHAPTER 18 FUNCTIONS AND TRIGGERS 18 4 Triggers Rules allow SQL queries to be executed when a table is accessed They are covered in section 13 6 Triggers offer another way to perform actions on INSERT UPDATE or DELETE Triggers are ideal for checking or modifying a column value before it is added to the database Triggers and rules are implemented differently Triggers call server side functions for each modified row while rules rewrite user queries or add additional queries Triggers are ideal for checking or modifying a row before it is added to the database Rules are ideal when the action affects other tables Triggers allow special server side functions to be called every time a row is modified These special functions can be written in any server si
74. have shown only SELECT examples CASE can be used in UPDATE and other complex situations CASE allows the creation of conditional values which can be used for output or for further processing in the same query CASE values only exist inside a single query so they can t be used outside the query that defines them 4 12 Distinct Rows It is often desirable to return the results of a query with no duplicates The keyword DISTINCT prevents duplicates from being returned Figure 4 21 shows the use of the DISTINCT keyword to prevent duplicate states and duplicate city and state combinations Notice DISTINCT operates only on the columns selected in the query It does not compare non selected columns when determining uniqueness Section 5 2 shows how counts can be generated for each of the distinct values 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 37
75. inserts increment the object counter If the OID is not visible to users this is not a problem Non sequential numbering does not affect query processing However if users see and enter these numbers 1t might seem strange customer identification numbers are not sequential and have large gaps in numbering Non Modifiable An OID is assigned to every row during INSERT UPDATE cannot modify the system generated OID of a row Not backed up by default When performing database backups the system generated OID of each row is normally not backed up A flag must be added to enable the backup of OIDs See section 20 5 for details 7 3 Sequences POSTGRESQL has another way of uniquely numbering rows They are called sequences Sequences are named counters created by users After creation the sequence can be assigned to a table as a column default Using sequences unique numbers can be automatically assigned during INSERT The advantage of sequences is that there are no gaps in numeric assignment as happens with OIDs Sequences are ideal as user visible identification numbers If a customer is created today and another tomorrow the two customers will have sequential numbers This is because no other table shares the sequence counter Sequence numbers are usually unique only within a single table For example if a table has a unique row numbered 937 another table might have a row numbered 937 also assigned by a different sequence counter 7
76. issue with NULLs that needs clarification In character columns a NULL is not the same as a zero length field That means that the string and NULL are different Figure 4 5 shows an example of this There are no valid numeric and date blank values but a character string can be blank When viewed test gt CREATE TABLE nulltest name CHAR 20 spouse CHAR 20 CREATE test gt INSERT INTO nulltest VALUES Andy INSERT 18986 1 test gt INSERT INTO nulltest VALUES Tom NULL INSERT 18987 1 test gt SELECT FROM nulltest ORDER BY name name spouse 2 rows test gt SELECT FROM nulltest WHERE spouse name spouse test gt SELECT FROM nulltest WHERE spouse IS NULL name spouse Figure 4 5 NULLs and blank strings in psql any numeric field that is blank has to contain a NULL because there is no blank number However there are blank strings so blank strings and NULLs are displayed the same in psq1 However they are not the same so be careful not to confuse the meaning of NULLs in character fields 44 Controlling DEFAULT Values As we learned in the previous section columns not specified in an INSERT statement are given NULL values This can be changed using the DEFAULT keyword When creating a table next to each column type you can use the keyword DEFAULT and then a value The value will be used anytime the column value is not supplied in an INSERT If no DEFAULT is defined a NULL is used for the colu
77. less than lt to perform the join Instead of finding equal values to join all rows greater than the column s value are joined The query returns all the employees hired after employee number 24 The third query uses greater than gt in a similar way The query returns all parts that cost less than part number 153 Non equijoins are not used very often but there are certain queries that can only be performed using non equijoins 6 12 Ordering Multiple Parts Our customer employee part and salesorder example has a serious limitation It allows only one part id per salesorder In the real world this would never be acceptable Having covered many complex join topics in this chapter a more complete database layout can be created to allow multiple parts per order 5347 5348 5349 5350 5351 5352 5353 5354 9355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463
78. makes little sense However in cases where we must record information about a variety of things multiple tables have benefits Consider a company that sells parts to customers through the mail The database has to record information about many things customers employees sales orders and parts It is obvious a single table cannot hold the different types of information in an organized manner Therefore we create four tables customer employee salesordex and part However putting information in different tables causes problems How do we record which sales orders belong to which customers How do we record the parts for the sales orders How do we record which employee received the sales order The answer is to assign unique numbers to every customer employee and part When we want to record the customer in the salesorder table we put the customer s number in the salesorder table When we want to record which employee took the order we put the employee s number in the salesorder table When we want to record which part has been ordered we put the part number in the salesorder table 45 46 CHAPTER 6 JOINING TABLES test gt SELECT firstname FROM friend WHERE state PA firstname Victor 1 row test gt SELECT friend firstname FROM friend WHERE friend state PA firstname Victor 1 row test gt SELECT f firstname FROM friend f WHERE f state PA firstname Victor 1 row Figure 6 1 Qualified column names
79. more than once which was not desired The second query uses an aggregate to return a count for each unique customer employee pair Up to this point we have had only a single row in each table As an exercise add additional customer employee and part rows and add salesorder rows that join to these new entries You can use figure 6 4 as an 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 6 6 ADDITIONAL JOIN POSSIBILITIES 53 example You can use any identification numbers you wish Try the queries already shown in this chapter with your new data 6 6 Additional Join Possibilities At this point all joins have involved the salesorder table in some form Suppose we wanted to assign an employee to manage each customer accou
80. need for a separate column to hold the row s unique number For example in the previous chapter there was a column called customer customer_id This column held the customer number It uniquely identified each row However we could have used the row s object 1See section B for a description of initdb Values less than this are reserved for internal use 3Technically OID S are unique among all databases sharing a common data directory tree There are several other invisible columns The POSTGRESQL manuals cover their meaning and use 63 64 CHAPTER 7 NUMBERING ROWS test gt CREATE TABLE oidtest age INTEGER CREATE test gt INSERT INTO oidtest VALUES 7 INSERT 18697 1 test gt SELECT oid age from oidtest oid age Ee Fadi 18697 7 1 row Figure 7 1 OID test identification number as the unique number for each row Then there would be no need to create the column customercustomer_td Customer oid would be the unique customer number With this change a similar change would be needed in the salesorder table We would rename salesor der customer_td to salesorder customer oid because the column now refers to an OID The column type should be changed also Salesorderncustomer id was defined as type INTEGER The new salesordercustomer oid column would hold the OID of the customer who made the order For this reason we would change the column type from INTEGER to OID Figure 7 2 shows a new version of the sales
81. nightmare As you create your first real world tables you will soon learn to identify good and bad data designs Continually review your table structures and refer to this chapter again for ideas Don t be afraid to redesign everything Redesign is hard but when it is done properly queries are much easier to craft Relational databases excel in their ability to relate and compare data Tables can be joined and analyzed in ways never anticipated With good data layout and the power of SQL you can retrieve an unlimited amount of information from your database In our example changing part price would change the price on previous orders of the part This would be inaccurate In the real world there would have to be a partprice table to store the part number price and effective date for the price 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5935 5936 5937 5938 5939 5940 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5997 5998 5959 5960 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590
82. no columns from the salesorder table are returned by the query A NOT IN comparison returns true if a column s value is not found For example suppose we want to see all customers who have never ordered a product We need to find the customers who have no sales orders This cannot be done with a join We need an anti join because we want to find all customer rows that do not join to any salesorder row Figure 8 11 shows the query The subquery returns a list of customer ids representing all customers who have placed orders The upper query returns all customer names where the customer_id does not appear in the subquery output 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 82 SUBQUERIES 79 test gt SELECT name test gt F
83. number of ANDs and ORs can be linked together to perform complex comparison tests When ANDs are linked with other ANDs there is no possibility for confusion The same is true of ORs However when ANDs and ORs are both used in the same query the results can be confusing Figure 4 13 shows such a case You might suspect that it would return rows with firstname equal to Victor and state equals PA or test gt SELECT FROM friend test gt WHERE firstname Victor AND state PA OR state NJ test gt ORDER BY firstname firstname lastname city state age Dick Gleason Ocean City INJ 19 Sandy Gleason Ocean City INJ 25 Victor Tabor Williamsport PA 22 3 rows Figure 4 13 Mixing ANDs and ORs NJ In fact the query returns rows with firstname equal to Victor and state equals PA or state equals NJ In this case AND is evaluated first then OR When mixing ANDs and ORs it is best to collect the ANDs and ORs into common groups using parentheses Figure 4 14 shows the proper way to enter this query Without parentheses it is very difficult to understand a query with mixed ANDs and ORs 4 8 Range of Values Suppose we wanted to see all friends who had ages between 22 and 25 Figure 4 15 shows two queries that produce this result The first query uses AND to perform two comparisons that both must be true We used 3235 3236 3237 3238 3239 3240 3241
84. primarytest 10304 pkey for table primarytest 10305 CREATE 10306 10307 test gt CREATE TABLE foreigntest 10308 test gt col2 INTEGER REFERENCES primarytest o test gt ON UPDATE CASCADE 10311 test gt ON DELETE NO ACTION 10312 test gt Tem NOTICE CREATE TABLE will create implicit trigger s for FOREIGN KEY check s 10315 CREATE 10316 test gt INSERT INTO primarytest values 1 DA INSERT 148835 1 10319 test gt INSERT INTO foreigntest values 1 10320 INSERT 148836 1 10321 tastas 10322 ES 10323 test gt CASCADE UPDATE is performed 10324 test gt 10325 10326 test gt UPDATE primarytest SET col 2 10327 UPDATE 1 ee test gt SELECT FROM foreigntest 10329 10330 col2 10331 eee 10332 gt 10333 10334 1 row 10335 10336 e 10337 test gt 10338 test gt NO ACTION prevents deletion 10339 test gt ll test gt DELETE FROM primarytest 10342 ERROR lt unnamed gt referential integrity violation ee key in primarytest still referenced from foreigntest 10345 test gt 10346 test gt By deleting the foreign key first the DELETE succeeds 10347 testis 10348 10349 test gt DELETE FROM foreigntest 10350 DELETE 1 10351 test gt DELETE FROM primarytest 10352 10353 DELETE 1 10354 10355 E Figure 14 11 Foreign key actions 10358 10359 10360 10361 10362 134 CHAPTER 14 CONSTRAINTS test gt CREATE TABLE primarytest2 test gt coll
85. so date _part can be used 9 5 Support Operators Operators are similar to functions and are covered in section 4 13 on page 33 Table 9 4 shows the most common operators Psql s do shows all defined operators and their arguments All data types have the standard comparison operators lt lt gt gt and lt gt Not all operator type combinations are defined For example if you try to add two DATE values you will get an error as shown in the first query of figure 9 3 92 Type Character String Number Temporal Function length character _length octet length trim trim BOTH trim LEADING trim TRAILING trim FROM rpad rpad Ipad Ipad upper lower initcap strpos position substr substring FROM substr substring FROM FOR translate to_number to_date to timestamp round round trunc trunc abs factorial sqrt cbrt exp InQ log to_char date part extract FROM date_trunc isfinite now timeofday overlaps to_char Example length col character_length col octet_length col trim col trim BOTH col trim LEADING col trim TRAILING col trim str FROM col rpad col len rpad col len str Ipad col len Ipad col len str upper col lower col initcap col strpos col str position str IN col substr col pos substring col FROM pos substr col pos le
86. statename test gt WHERE code 1 test gt END test gt LANGUAGE plpgsql CREATE Figure 18 7 PL PGSQL version of getstatename Figure 18 8 shows a more complicated PL PGSQL function It accepts a text argument and returns the argument in uppercase with a space between each character This is used in the next SELECT to display a report heading This function illustrates the use of variables and WHILE loops in PL PGSQL Figure 18 9 shows a much more complicated PL PGSQL function This function takes a state name as a parameter and finds the proper state code Because state names are longer than state codes they are often misspelled This function deals with misspellings by performing lookups in several ways First it attempts to find an exact match If that fails 1t searches for a unique state name that matches the first 2 4 or 6 characters up to the length of the supplied string If a unique state is not found an empty string is returned Figure 18 10 shows several getstatecode function calls Getstatecode illustrates several unique PL PGSQL features TYPE Data type that matches a database column RECORD Data type that stores the result of a SELECT SELECT INTO A special form of SELECT that allows query results to be placed into variables It should not be confused with SELECT INTO FOUND Predefined BOOLEAN variable that represents the status of the previous SELECT INTO RETURN Exits and returns a value fr
87. test gt upper trim lastname RIVERS test gt CREATE test gt INSERT INTO friend2 test gt VALUES A1 Rivers Wibbleville J 35 S 1931 09 23 ERROR ExecAppend rejected due to CHECK constraint friend2 last met Figure 14 15 CHECK constraints state Forces the column to be two characters long CHAR pads the field with spaces so state must be trim ed of trailing spaces before the length is computed age Forces the column to hold only positive values gender Forces the column to hold either M or F last met Forces the column to be between January 1 1950 and the current date table Forces the table to only accept rows where firstname is not AL or lastname is not RIVERS The effect of this rule is to prevent Al Rivers from being entered into the table His name will be rejected if it is in uppercase lowercase or mixed case This must be done as a table level CHECK constraint Comparing firstname to AL at the column level would have prevented all AL s from being entered which was not desired The desired restriction is a combination of firstname and lastname The figure then tries to INSERT a row that violates all CHECK constraints Though the CHECK failed on the friend last met constraint if that were corrected the other constraints would prevent the insertion By default CHECK allows NULL values 14 6 Summary This chapter covered a variety of constraints that help keep user data constrained
88. the Source Code 2 ea sa enden ee a ews B Installation C PostgreSQL Non Standard Features by Chapter D Reference Manual Bibliography Index 178 181 181 182 182 183 183 185 185 185 187 187 189 189 190 191 191 191 192 192 193 193 193 193 193 193 195 197 199 201 201 xvi CONTENTS 0991 0992 0993 0994 0995 0996 0997 0998 0999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 List of Figures 21L psa SESSION Startup oia a a el ed AOE ed a 6 22 My TESTUSOLQUEN ze en en en ara aa A a BE we AS 4 6 B HUN ies AA AAA Wee ekke 7 2A Bookelash CMO carmen ia 8 Sik Databases AA AA 9 22 Create Dle Mena so owe hee aca E le a A A a a 10 3 9 Example ol backslashet oda a Bed Bata Aden ee gee aoe Hed 11 Su ASE atten en ae ne A d
89. this example trim firstname space C and lastname are joined using 84 CHAPTER 8 COMBINING SELECTS 8 7 Creating Tables Using SELECT In addition to inserting into existing tables SELECT has an INTO clause that can create a table and place all its output into the new table For example suppose we want to create a new table called newfriend just like our friend table but without an age column This is easily done with the query in figure 8 18 The SELECT INTO test gt SELECT firstname lastname city state test gt INTO newfriend test gt FROM friend SELECT test gt d newfriend Table newfriend Attribute Type Extra AAA dE ne firstname char 15 lastname char 20 city char 15 state char 2 test gt SELECT FROM newfriend ORDER BY firstname firstname l lastname city state Hen non Dean Yeager Plymouth MA Dick Gleason Ocean City NJ Ned Millstone Cedar Creek MD Sandy Gleason Ocean City NJ Sandy Weber Boston MA Victor Tabor Williamsport PA 6 rows Figure 8 18 Table creation with SELECT query e Creates a table called newfriend e Uses SELECT s column labels to name the columns of the new table e Uses SELECT s column types as the column types of the new table SELECT INTO is CREATE TABLE and SELECT combined in a single statement The AS clause can be used to change the column labels and thus control the column names in the new tab
90. weeks to issue sub releases to correct serious bugs We were never tempted to follow a more aggressive schedule with more releases A database server is not like a word processor or a game where you can easily restart it if there is a problem Databases are multi user and lock user data inside the database so we must make our software as reliable as possible Development of source code of this scale and complexity is not for the novice We had trouble getting developers interested in a project with such a steep learning curve However our civilized atmosphere and our improved reliability and performance finally helped attract the experienced talent we needed Getting our developers the knowledge they needed to assist with POSTGRESQL was clearly a priority We had a TODO list that outlined what needed to be done but with 250 000 lines of code taking on any TODO item was a major project We realized developer education would pay major benefits in helping people get started We wrote a detailed flowchart of the back end modules We wrote a developers FAQ to describe some of the common questions of POSTGRESQL developers With this developers became more productive at fixing bugs and adding features The source code we inherited from Berkeley was very modular However most Berkeley coders used POSTGRESQL as a test bed for research projects Improving existing code was not a priority Their coding 4C is a popular computer language first devel
91. with HAVING and table aliases as shown in the first query of figure 8 9 Another way is to execute a subquery for each row which finds the maximum age for that state If the maximum age equals the age of the current row the row is output as shown in the second query The query references the friend table two times using aliases fl and f2 The upper query uses fl The subquery uses f2 The correlating specification is WHERE fl state f2 state This makes it a correlated subquery because the subquery references a column from the upper query Such a subquery cannot be evaluated once and the same result used for all rows It must be evaluated for every row because the upper column value can change 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 8 2 SUBQUERIES 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 test gt SELECT fl firstname fl lastname fl age 6613 test gt FROM friend fl friend f2 6614 6615 test gt WHERE fl state f2 state 6616 test gt GROUP BY f2 state fl firstname fl lastname fl age 6617 test gt HAVING fl age max f2 age 6618 6619 test gt
92. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 0030 0031 0032 0033 0034 0035 0036 0037 0038 0039 0040 0041 0042 0043 0044 0045 0046 0047 0048 0049 0050 0051 0052 0053 0054 0055 0056 0057 0058 0059 0060 0061 0062 0063 0064 0065 0066 ostgreSQL Introduction and Concepts Bruce Momjian May 30 2000 il 0067 0068 0069 0070 0071 0072 0073 0074 0075 0076 0077 0078 0079 0080 0081 0082 0083 0084 0085 0086 0087 0088 0089 0090 0091 0092 0093 0094 0095 0096 0097 0098 0099 0100 0101 0102 0103 0104 0105 0106 0107 0108 0109 0110 0111 0112 0113 0114 0115 0116 0117 0118 0119 0120 0121 0122 0123 0124 0125 0126 0127 0128 0129 0130 0131 0132 0133 0134 0135 0136 0137 0138 0139 0140 0141 0142 0143 0144 0145 0146 0147 0148 0149 0150 0151 0152 0153 0154 0155 0156 0157 0158 0159 0160 0161 0162 0163 0164 0165 0166 0167 0168 0169 0170 0171 0172 0173 0174 0175 0176 0177 0178 0179 0180 0181 0182 0183 0184 0185 0186 0187 0188 0189 0190 0191 0192 0193 0194 0195 0196 0197 0198 Note to Reviewers The material on these pages is a work in progress tentatively titled PostgreSQL Introduction and Concepts to be published in 2000 Addison Wesley Posted with permission of the publisher
93. 026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 8 5 UPDATE WITH FROM 83 8 5 UPDATE with FROM UPDATE can have an optional FROM clause which allows joins to other tables The FROM clause also allows the use of columns from other tables in the SET clause With this capability columns can be updated with data from other tables Suppose we want to update the salesorder table s order_date column For some reason some orders exist in the system that have order dates earlier than the hire date of the employee who recorded the sale For these rows we wish to set the order_date equal to the employee s hire_date Figure 8 16 shows this query test gt UPDATE salesorder test gt SET order_date employee hire_date test gt FROM employee test gt WHERE salesorder employee id employee employee id AND test gt salesorder order date lt employee hire date UPDATE 0 Figure 8 16 UPDATE the order date The FROM clause allows the use of the employee table in the WHERE and SET clauses While UPDATE can use subqueries to control which data rows are updated only the FROM clause allows columns from other tables to be used in the SET clause 8 6 Inserting Data Using SELECT Up to this point every INSERT statement has inserted a single row Each INSERT had a VALUES clause listing
94. 032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 14 3 PRIMARY KEY 129 Instead a separate UNIQUE line is required to specify the columns that make up the constraint This is called a UNIQUE table constraint Figure 14 4 shows a multi column UNIQUE constraint While coll or col2 themselves test gt CREATE TABLE uniquetest2 test gt coll INTEGER test gt col2 INTEGER test gt UNIQUE coll col2 test gt Es NOTICE CREATE TABLE UNIQUE will create implicit index uniquetest2 coll key for table uniquetest2 Figure 14 4 Multi column unique constraint may not be unique the constraint requires the combination of coll and col2 to be unique For example in a table that contains the driver s license numbers of people in various states two people in different states may have the same license number but the combination of their state and license number should always be unique 14 3 PRIMARY KEY The PRIMARY KEY constraint marks the column that uniquely identifies each row It is a combination of UNIQUE and NOT NULL con
95. 0578 0579 0580 0581 0582 0583 0584 0585 0586 0587 0588 0589 0590 0591 0592 0593 0594 Acknowledgements Update this page with current information before publication POSTGRESQL and this book would not be possible without the talented and hard working members of the POSTGRESQL Global Development Team They took source code that could have become just another aban doned project and turned it into the open source alternative to commercial database systems POSTGRESQL is a shining example of Internet community development Steering Fournier Marc G in Wolfville Nova Scotia Canada scrappy hub org coordinates the whole effort and provides the server and administers our primary web site mailing lists ftp site and source code repository Lane Tom in Pittsburgh PA USA tgl sss pgh pa us has performed many PostgreSQL improve ments He has worked on the optimizer and a variety of complex issues Lockhart Thomas G in Pasadena California USA lockhart alumni caltech edu works on documen tation data types particularly date time and geometric objects and on SQL standards compatibility Mikheev Vadim B in Krasnoyarsk Russia vadim krs ru does large projects like vacuum subselects triggers and multi version concurrency control MVCC Momjian Bruce in Philadelphia Pennsylvania USA maillist candle pha pa us maintains FAQ and TODO lists code cleanup some patch application makes training materials and some
96. 070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 20 8 PERFORMANCE 191 e Database SQL command keyword SELECT INSERT UPDATE DELETE CREATE idle Ps displays this information next to the name of each postgres process A typical display is PID TT STAT TIME COMMAND 18923 S 0 27 79 usr local postgres bin postgres demouser localhost test SELECT In this example demouses using process id 18923 is connecting from the local machine to database test and is executing a SELECT Administrators can use ps to analyze who is connected to each database the query command they are running and the system resources used 20 8 Performance Chapter 11 covers the perform
97. 15 8116 8117 8118 10 3 VISIBILITY OF COMMITTED TRANSACTIONS 99 When you begin a transaction with BEGIN WORK you don t have to commit it using COMMIT WORK You can close the transaction with ROLLBACK WORK and the transaction will be discarded The database is left as though the transaction had never been executed In figure 10 5 the current transaction is rolled back causing the DELETE have no effect Also if any query inside a multi statement transaction cannot be executed due test gt INSERT INTO rollback_test VALUES 1 INSERT 19369 1 test gt BEGIN WORK BEGIN test gt DELETE FROM rollback_test DELETE 1 test gt ROLLBACK WORK ROLLBACK test gt SELECT FROM rollback_test Figure 10 5 Transaction rollback to an error the entire transaction is automatically rolled back 10 3 Visibility of Committed Transactions Though we have focused on the all or nothing nature of transactions they have other important benefits Only committed transactions are visible to users Though the current users sees his changes other users do not see them until the transaction is committed For example figure 10 1 shows two users issuing queries using the default mode in which every statement is in its own transaction Figure 10 2 shows the same query with user 1 using a multi query transaction User User 1 User 2 Notes SELECT FROM trans test returns 0 INSERT INTO trans_test VALUES 1 add row to trans_test SELECT
98. 157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 10 5 LOCKING 101 shows the newly INSERTED row When another user commits a transaction it is seen by the current transaction even if it is committed after the current transaction started You can prevent your transaction from seeing changes made to the database SET TRANSACTION ISOLATION LEVEL SERIALIZABLE changes the isolation level of the current transaction SERIALIZABLE isolation prevents the current transaction from seeing commits made by other transactions Any commit made after the start of the first query of the transaction is not visible Figure 10 7 shows an example of a SERIALIZABLE transaction test gt BEGIN WORK BEGIN test gt SET TRANSACTION ISOLATION LEVEL SERIALIZABLE SET VARIABLE test gt SELECT COUNT FROM trans_test count test gt test gt someone commits INSERT INTO trans test test gt test gt SELECT COUNT FROM trans test test gt COMMIT WORK
99. 165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 6 8 ONE TO MANY JOINS 55 e Short two letter codes are not significantly slower than integers in joins e Two letter codes do not require significantly more storage than integers There are basically two choices for join keys identification numbers and short character codes If an item is referred to repeatedly it is best to use a short character code as a join key You can display this key to users and allow them to refer to customers and employees using codes Users prefer to identify items by short fixed length character codes containing numbers and letters For example customers can be identified by six character codes FLE001 employees by their initials BAW and parts by five character codes E7245 Codes are easy to use and remember In many cases users can choose the codes as long as they are unique It is possible to allow users to enter short character codes and still use identification numbers as join keys This is done by adding a code column to the table For the customer table a new column called code can be added to hold the customer code When the user enters a customer code the query can find the customer id assigned to the customer cod
100. 2 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 Chapter 4 Customizing Queries This chapter will illustrate additional capabilities of the basic SQL commands 4 1 Data types Table 4 1 shows the most common column data types Figure 4 1 shows queries using these types There Category Type Description character string char length blank padded string fixed storage length varchar length variable storage length number integer integer 2 billion range float floating point number 15 digit precision numeric precision decimal number with user defined precision and decimal location date time date date time time timestamp date and time Table 4 1 Common data types is table creation INSERT and SELECT There are a few things of interest in this example First notice how the numbers do not require quotes while character strings dates and times require them Also note the timestamp column displays its value in the standard UNIX date format It also displays the time
101. 2 2963 2964 2965 2966 2967 2968 2969 2970 4 3 USING NULL VALUES 21 One way to place a single quote inside a single quoted string is to use two quotes together like this 0 Don ne11 Two single quotes inside a single quoted string cause one single quote to be generated Another way is to use a backslash like this 0 Donnel1 The backslash escapes the single quote character 4 3 Using NULL Values Let s return to the INSERT statement described in section 3 3 on page 11 We will continue to use the friend table from the previous chapter In figure 3 4 we specified a value for friend column Suppose we wanted to insert a new row but did not want to supply data for all the columns i e we want to insert information about Mark but we don t know Mark s age Figure 4 2 shows this After the table name we have column names in parentheses These columns will test gt INSERT INTO friend firstname lastname city state test gt VALUES Mark Middleton Indianapolis IN INSERT 18881 1 Figure 4 2 Insertion of specific columns be assigned in order to the supplied data values If we were supplying data for all columns we wouldn t need to name them In this example we must name the columns The table has five columns but we are only supplying four data values The column we did not assign was age The interesting question is What is in the age cell for Mark The answer is that the age cell contains a NULL val
102. 22466 4 4 444 ee 4 73 e 8 6 INTERSECT returns only duplicated TOWS su ea ea ee ee Bee eS 74 1186 8 7 Friends not in Dick Gleason s state di an wa ee Ee BE ee ar ied 75 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 LIST OF FIGURES XIX 8 8 Subqueries can replace some joins 1 76 89 Correlated SUDETY os aen ak ae ed ee ed Bd a 77 8 10 Employees who took orders ene san ee ee en 78 e L1 Customers who have nt OHELS soes a BRR ERR ER a 79 8 12 IN query rewritten using ANY and EXISTS 80 8 13 NOT IN query rewritten using ALL and EXISTS 81 8 14 Simulating A 82 8 15 Subquenes with UPDATE and DELETE casa eenen eo wa waked ae He ie 82 Ole UPDATE the order dall lt e sec re cri AA e ea E a E S 83 6 17 Usine SELECT WHA INSERT coec eane ad ra AA AA a ad 83 8 18 Table creation wit SELECT cs AAA A a e E Rew Re 84 SL BSE AEO seces ee Gd eee e ae AR A ees 91 9 2 Error generated by undefined function type combination 93 9 3 Error generated by undefined operator type combination o
103. 23 0924 0925 0926 0927 0928 0929 0930 0931 0932 0933 0934 0935 0936 0937 0938 0939 0940 0941 0942 0943 0944 0945 0946 0947 0948 0949 0950 0951 0952 0953 0954 0955 0956 0957 0958 0959 0960 0961 0962 0963 0964 0965 0966 0967 0968 0969 0970 0971 0972 0973 0974 0975 0976 0977 0978 0979 0980 0981 0982 0983 0984 0985 0986 0987 0988 0989 0990 CONTENTS RA AA AI 19 Extending POSTGRESQL Using C INTI vennen a ERAS e RENEE RA RA 192 Comme the Coden cow ADE AAA AE ARA A A 19 3 Register the New Functions 2 eee eee 19 4 Optionally Create Operators Types and Aggregates o te ee U REN ene aneka eden reren dd 20 Administration BON DER oe ear Eer ee AN ATD Te HE ee ER nele 20 2 Creating VOER zever netart ADD A WDS 20 9 Creatine Databases coccion vaneen 20 4 Access Configura 20 tee Ged we edo bedeeeidatkedeeus ead avails s 205 Backup and Restore s ce a at de hee ee a te e iaa 20 6 Server Startup and Shutdown s se se so ea enn re ee ee ee a o ak ene edel menne Oe ee ee wees 20S a ct me nr en ae Re wae Gees ole oS we ee bee ww a eet 20 9 System III IE SONORO oe aerden ikt POLLAS eeen annet balen eh AS BEEP A A Additional Resources A 1 Frequently Asked Questions FAQ S ee AZ Me VASE SUDO era sd oana ya a AA A AAA REELS AS Supplied Documentation r s ssa cicci edri araa dn ded AA Commercial SUpport se ae eeen aanne eren AR Sw 4 AS Modifying
104. 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 3 8 SORTING DATA WITH ORDER BY 2509 EN test gt SELECT FROM friend 2512 firstname lastname city state age 2513 O O O L ainoaa decai dai A tie dima e A Sl Mike Nichols Tampa IFL 19 2516 Cindy Anderson Denver co 23 A Sam Jackson Allentown PA 22 2519 3 rows 2520 oo test gt INSERT INTO friend VALUES Jim Barnes Ocean City NJ 25 ee INSERT 18880 1 2524 test gt SELECT FROM friend P firstname lastname city state age 2527 eenen 2528 Mike Nichols Tampa FL 19 Dea Cindy Anderson Denver CO 23 2531 Sam Jackson Allentown PA 22 ee Jim Barnes Ocean City NJ 25 2534 4 rows 2535 Ar test gt DELETE FROM friend WHERE lastname Barnes E DELETE 1 2539 test gt SELECT FROM friend A firstname lastname city state age 2542 ttre 2543 Mike Nichols Tampa FL 19 Bn Cindy Anderson Denver cO 23 2546 Sam Jackson Allentown PA 22 2547 3 rows 2548 2549 2550 2551 Figure 3 11 DELETE example 2552 2553 2554 2555 2556 Ren 2557 test gt UPDATE friend SET age 20 WHERE firstname Mike 2558 UPDATE 1 ae test g
105. 262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 3 3 ADDING DATA WITH INSERT 11 The important part of this query is between the parentheses You will notice there are five lines there The first line firstname CHAR 15 represents the first column of the table to create The word firstname is the name of the first column and the text CHAR 15 indicates the column type and length The CHAR 15 means the first column of every row holds up to 15 characters The second column is called lastname and holds up to 20 characters Columns of type char hold characters of a specified length User supplied character strings that do not fill the entire length of the field are right padded with blanks Columns city and state are similar The final column age is different It is not a CHARO column It is an INTEGER column It holds whole numbers not characters Even if there were 5 000 friends in the table you can be certain that there are no names appearing in the age column only whole numbers It is this structure that helps databases to be fast and reliable POSTGRESQL supports more column types than just char and integer However in this chapter we will use only these two Sections 4 1 and 9 2 cover column types in more
106. 3 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 17 5 COMPILING PROGRAMS 159 Dal Tibpq sample program include lt iostream h gt include lt libpg h gt Vibpq header file int main char state code 3 holds state code entered by user char query string 256 holds constructed SQL query PgDatabase data dbname test connects to the database if data ConnectionBad did the database connection fail cerr lt lt Connection to database failed lt lt end lt lt Error returned lt lt data ErrorMessage lt lt end exit 1 cout lt lt Enter a state code prompt user for a state code cin get state code 3 n sprintf query_ string create an SQL query string SELECT name FROM statename WHERE code s state code if data ExecTuplesOk query string send the query cerr lt lt SELECT query failed lt lt endl exit 1 for int i 0 i lt data Tuples i loop through
107. 3 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 18 3 PL PGSQL FUNCTIONS test gt SELECT getstatecode Alabama getstatecode AL 1 row test gt SELECT getstatecode ALAB getstatecode AL 1 row test gt SELECT getstatecode Al getstatecode AL 1 row test gt SELECT getstatecode Ail getstatecode Figure 18 10 Calls to getstatecode function 175 176 CHAPTER 18 FUNCTIONS AND TRIGGERS test gt CREATE FUNCTION change statename char 2 char 30 test gt RETURNS boolean test gt AS DECLARE test gt state code ALIAS FOR 1 test gt state name ALIAS FOR 2 test gt statename_rec RECORD test gt test gt BEGIN test gt IF length state code 0 no state code failure test gt THEN RETURN f test gt ELSE test gt IF length state name 0 is INSERT or UPDATE test gt THEN test gt SELECT INTO statename_rec test gt FROM statename test gt WHERE code state code test gt IF NOT FOUND is state not in table test gt THEN INSERT INTO statename test gt VALUES state code state name test gt ELSE UPDATE statename test gt SET name sta
108. 31 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 6 3 CREATING JOINED TABLES 47 is more efficient and allows easier administration and data maintenance The advantages of using multiple tables are e Easier data modification e Easier data lookup e Data stored in only one place e Less storage space required The only time duplicate data should not be moved to a separate table is when all of these are true e Time required to perform a join is prohibitive e Data lookup is unnecessary Duplicate data requires little storage space e Data is very unlikely to change The customer employee part and salesorder example clearly benefits from multiple tables 6 3 Creating Joined Tables Figure 6 3 shows the SQL statements needed to create those tables The customer employee and part tables each have a column to hold their unique identification numbers The salesorder table has columns to hold the customer employee and part numbers associated with the sales order For the sake of simplicity we will assume that each salesorder contains only one part number We have used underscores _ to allow multiple words in column names i e customer_id This is common You co
109. 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 4 8 RANGE OF VALUES test gt SELECT FROM friend test gt WHERE firstname Victor AND state PA OR state NJ test gt ORDER BY firstname firstname lastname Victor Tabor 1 rows city state age Williamsport PA 22 Figure 4 14 Properly mixing ANDs and ORs test gt SELECT test gt FROM friend Comparison Operator less than lt less than or equal lt equal E greater than or equal gt greater than gt not equal lt gt or Table 4 2 Comparisons test gt WHERE age gt 22 AND age lt 25 test gt ORDER BY firstname firstname lastname city eed A A A A ded Dean Yeager Plymout
110. 3365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 18 5 SUMMARY 179 test gt CREATE FUNCTION trigger insert update statename test gt RETURNS opaque test gt AS BEGIN test gt IF new code A Za z A Za z test gt THEN RAISE EXCEPTION Code must be two alphabetic characters test gt END IF test gt IF new name A Za z test gt THEN RAISE EXCEPTION Name must be only alphabetic characters test gt END IF test gt IF length trim new name lt 3 test gt THEN RAISE EXCEPTION Name must be longer than two characters test gt END IF test gt new code upper new code uppercase statename code test gt new name initcap new name capitalize statename name test gt RETURN new test gt END test gt LANGUAGE plpgsql CREATE test gt CREATE TRIGGER trigger_statename test gt BEFORE INSERT OR UPDATE test gt ON statename test gt FOR EACH ROW test gt EXECUTE PROCEDURE trigger insert update statename CREATE test gt DELETE FROM statename DELETE 1 test gt INSERT INTO statename VALUES a alabama ERROR State code must be two alphabetic characters test gt INSERT INTO statename VALUES al alabama2 ERROR State name must be only alphabetic characters
111. 363 cc deis patea 4364 4365 Boston 4366 Cedar Creek 1 1 goad Ocean City NJ 2 4368 4369 Plymouth 1 4370 Williamsport 1 4371 475 5 rows 4373 4374 f 4375 Figure 5 4 GROUP BY on two columns 4376 4377 4378 f Doi 4379 column as shown in figure 5 5 Aggregates can t be used in a WHERE clause They are valid only inside 4380 4381 4382 test gt SELECT state COUNT 4383 test gt FROM friend 4384 test gt GROUP BY state 4386 test gt HAVING COUNT gt 1 4387 test gt ORDER BY state 4388 4389 state count 4390 deser 4392 4393 N 2 4394 2 rows 4395 4396 4397 4398 Figure 5 5 HAVING usage 4399 4400 4401 HAVING 4402 4403 4404 4405 4406 4407 5 4 Query Tips 4408 4409 4410 In figures 5 3 and 5 5 the queries are spread over several lines When a query has several clauses like T FROM WHERE and GROUP BY it is best to place each clause on a separate line It makes queries easier to 4413 understand Clear queries also use appropriate capitalization PE In a test database it isn t a problem if you make a mistake In a live production database one incorrect 4416 query can cause great difficulties It takes five seconds to issue an erroneous query and sometimes five 4417 days to recover from it Double check your queries before executing them This is especially important for ve UPDATE DELETE and INSERT queries because they modify the database Also bef
112. 383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 17 13 PHP lt PHP sample program Output gt did the database connection fail send the query loop through all rows returned print the value returned lt HTML gt lt BODY gt lt database pg Connect test connect to the database if database echo Connection to database failed exit result pg Exec database SELECT name FROM statename WHERE code state code for 1 0 i lt pg NumRows result i echo pg Result result i 0 echo lt BR gt gt lt BODY gt lt HTML gt Figure 17 13 PHP sample program Output 165 166 CHAPTER 17 PROGRAMMING INTERFACES 17 14 Installing Scripting Languages The interpreted languages above require a database interface to be installed into the language
113. 4 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 126 CHAPTER 13 TABLE MANAGEMENT 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 Chapter 14 Constraints Constraints keep user data constrained They help prevent invalid data from being entered into the database Defining a data type for a column is a constraint itself A column of type DATE constrains the column to valid dates This chapter covers a variety of constraints We have already shown DEFAULT can be specified at table creation Constraints are defined at table creation in a similar way 14 1 NoT NULL The constraint NOT NULL prevents NULLs from appearing in a column Figure 14 1 shows the creation of a table with a NOT NULL constraint
114. 4 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 13 6 RULES test gt test gt INSERT test gt test gt test gt UPDATE test gt test gt DELETE test gt test gt test gt customer_id description mod_type mod_user INSERT INTO service request customer id description VALUES 72321 Fix printing press 18808 1 UPDATE service request SET description Fix large printing press WHERE customer id 72321 1 DELETE FROM service request WHERE customer id 72321 1 SELECT FROM service request log WHERE customer id 72321 123 mod_timestamp t 72321 Fix printing press U williams 2000 04 09 07 13 07 04 72321 Fix large printing press D matheson 2000 04 10 12 47 20 04 2 rows test gt CREATE test gt CREATE test gt INSERT test gt INSERT test gt col col Figure 13 11 Use of rule to log table changes CREATE TABLE realtable col INTEGER CREATE VIEW view realtable AS SELECT FROM realtable 407890 1 INSERT INTO r
115. 4 1 test gt SELECT state name children distance budget FROM alltypes state name children distance budget t t PA Hilda Blairwood 3 10 7 4308 20 1 row test gt SELECT born checkin started FROM alltypes born checkin started ae ae ee Leanna O A AAE E too e cos cc 09 08 1974 09 00 00 Wed Jul 03 10 30 00 1996 EDT 1 row test gt x Expanded display is on test gt SELECT FROM alltypes RECORD 1 state PA name Hilda Blairwood children 3 distance 10 7 budget 4308 20 born 09 08 1974 checkin 09 00 00 started Wed Jul 03 10 30 00 1996 EDT Figure 4 1 Example of common data types 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 296
116. 4 18 Complex regular expression Genes os idas eR See owe SRLS 31 xviii LIST OF FIGURES 19 CASE example sa aas oane a ke a e ee 32 1123 4 20 Complex CASP ekamiple a are da ee arte Ade ir eaten Ae de Bl eee ae tes 33 1124 del DISTINCT prevents duplicates 6 og kc AW Seo dar AAA ERS ES 34 i O22 BUBCOONEXAMD ES sc Ke eked SR AAN ARA 35 1127 423 Operator examples occse ce cs Ke GRA BS RO BEER DA RE RS DS 36 1128 A24 SHOW and RESET OBE c e ooer EE ON HRS ER HET ES ORS EN 37 ara 1131 Del A eregave CMPS eee apa he oe Beet et dee ee a eo 40 1132 52 Aporepates and NULLS a nn hae eae ee Ae eR Be ee Oe Ba ewe ea eS 4 41 a 5 3 Appregate Wih GROUP BY circa A a ae RAR ea a 42 1135 54A GROUP BY On TWO COUMANS ne a a a A Ee we ws 43 1136 Doo HANGISI E o ar ene da ee Re ER DE de ee a a 43 EE 6 1 Qualined COMMA Names oo a en ae Bate ae de be we a ee A we 46 i n G2 UTM aa o in a werden ble ate 46 a 6 3 Creation of company LADIES esos ors de rr da RRS d p HE AR a A 48 1143 6 4 Insertion nto company tables 2544 4 das ac da KC a ME REE amave EONS DS 49 1144 6 5 Finding customer name using two queries oo o eee eee 50 ee 6 6 Finding customer name using one query 22444 60228 22408 sms oe He 50 1147 6 7 Finding order number for customer DAME s sa sgoe an an ane ae Oe be ee eS 51 1148 Oe IESO jom lt cacani 444 258 8846 dia AR A 51 6 9 Fourtable IO lt gt popa rr 52 1151 6 10 Employees who have taken orders for customers o o
117. 4 Creating Sequences Sequences are not created automatically like OIDs You must create sequences using the CREATE SEQUENCE command Three functions control the sequence counter They are listed in table 7 1 nextval name Returns the next available sequence number and updates the counter Returns the sequence number from the previous nextval call setval name newval Sets the sequence number counter to the specified value Table 7 1 Sequence number access functions Figure 7 3 shows an example of sequence creation and sequence function usage The first command creates the sequence Then various sequence functions are called Note the SELECTs do not have a FROM clause Sequence function calls are not directly tied to any table This figure shows that e nextval returns ever increasing values e currval returns the previous sequence value without incrementing e setval sets the sequence counter to a new value This is not completely true Gaps can occur if a query is assigned a sequence number as part of an aborted transaction See section 10 2 for a description of aborted transactions 66 test gt CREATE CREATE test gt SELECT nextval test gt SELECT nextval test gt SELECT currval test gt SELECT setval test gt SELECT nextval CHAPTER 7 NUMBERING ROWS SEQUENCE functest_seq nextval functest_seq nextval functest_seq currval functest_seq setval functest_seq 100
118. 42 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 4 13 FUNCTIONS AND OPERATORS 33 test gt SELECT firstname test gt state test gt CASE test gt WHEN state PA THEN close test gt WHEN state NJ OR state MD THEN far test gt ELSE very far test gt END AS distance test gt FROM friend test gt ORDER BY firstname firstname state distance stets E iaa Dean MA very far Dick NJ far Ned MD far Sandy NJ far Sandy MA very far Victor PA close 6 rows Figure 4 20 Complex CASE example 4 13 Functions and Operators There are a large number of functions and operators available in POSTGRESQL Function calls take zero one or more arguments and return a single value You can list all functions and their arguments using psql s df command You can use psql s dd command to display comments about any specific function or group of functions as shown in figure 4 22 Operators differ from functions in the following ways e Operators are symbols not names e Operators usually take two arguments e Arguments appear to the left and right of the operator symbol For example is an operator that takes one argument on the left and one on the right and returns their sum Psql s do command lists all POSTGRESQL operators and their arguments Figure 4 23 shows operator listings and their use The standard arithmetic opera
119. 46 0247 0248 0249 0250 0251 0252 0253 0254 0255 0256 0257 0258 0259 0260 0261 0262 0263 0264 0265 0266 0267 0268 0269 0270 0271 0272 0273 0274 0275 0276 0277 0278 0279 0280 0281 0282 0283 0284 0285 0286 0287 0288 0289 0290 0291 0292 0293 0294 0295 0296 0297 0298 0299 0300 0301 0302 0303 0304 0305 0306 0307 0308 0309 0310 0311 0312 0313 0314 0315 0316 0317 0318 0319 0320 0321 0322 0323 0324 0325 0326 0327 0328 0329 0330 Foreword Most research projects never leave the academic environment Occasionally exceptional ones survive the transition from the university to the real world and go on to become a phenomenon POSTGRESQL is one of those projects Its popularity and success is a testament to the dedication and hard work ofthe POSTGRESQL global development team Developing an advanced database system is no small feat Maintaining and enhancing an inherited code base is even more challenging The POSTGRESQL team has not only managed to improve the quality and usability of the system but to spread its use among the Internet user community This book is a major milestone in the history of the project POSTGRES95 later renamed POSTGRESQL started out as a pet project to overhaul POSTGRES POSTGRES is a novel and feature rich database system created by many students and staff at the UNIVERSITY OF CALIFORNIA AT BERKELEY Our goal was to keep the powerful and useful features while
120. 542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 Chapter 18 Functions and Triggers The previous chapter focused on client side programming programs that run on the user s computer and interact with the POSTGRESQL database Server side functions sometimes called stored procedures run inside the database server rather than in the client application There are some good uses for server side functions For example if a function is used by many applications 1t can be embedded into the database server Each application then no longer needs a copy of the function Whenever it is needed it can be called by the client Unlike client side functions server side functions can be called from inside SQL queries Also functions centrally installed in the server are easily modified When a function is changed client applications immediately start using the new version Figure 9 3 on page 92 lists many pre installed server side functions like upper and date_part This chapter shows how to create your own This chapter also covers special server side functions
121. 58 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 Chapter 13 Table Management This chapter covers a variety of topics involved in managing SQL tables 13 1 Temporary Tables Temporary tables are short lived tables They exist only for the duration of a database session When a database session terminates its temporary tables are automatically destroyed Figure 13 1 illustrates this In the figure CREATE TEMPORARY TABLE creates a temporary table On psql exit the temporary table is destroyed Restarting psql shows the temporary table no longer exists Temporary tables are visible only to the session that creates them They are invisible to other users In fact several users can create temporary tables with the same name and each user sees only their version of the table Table 13 1 shows an example of this Temporary tables will even mask ordinary tables with the User 1 User 2 CREATE TEMPORARY TABLE temptest col INTEGER CREATE TEMPORARY TABLE temptest col INTEGER INSERT INTO temptest VALUES 1 INSERT INTO temptest VALUES 2 SELECT col FROM temptest returns 1 SELECT col FROM temptest returns 2 Table 13 1 Temporary table isolation same name Temporary tables are ideal for holding intermediate data used by the current SQL session For example suppose you need to do many SELECTs on the result of a complex query An efficient way to do this is to execute the complex query once a
122. 6 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 Appendix A Additional Resources A 1 Frequently Asked Questions FAQ S This information comes from http www postgresql org docs faq english html A 2 Mailing List Support This information comes from http www postgresq org lists mailing list html A 3 Supplied Documentation This information comes from http www postgresql org docs index html A 4 Commercial Support Information from http www pgsql com andhttp www greatbridge com A 5 Modifying the Source Code POSTGRESQL allows access to all its source code The web page http www postgresql org docs index html has a Developers section 193 194 APPENDIX A ADDITIONAL RESOURCES 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 143
123. 6 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 16 1 PSQL test gt SELECT NULL column 1 row test gt pset tuples only Showing only tuples test gt SELECT NULL test gt pset null null Null display is null test gt SELECT NULL null Figure 16 1 Example of pset Modifies Field alignment Field separator One field per line Rows only Table title Enable HTML HTML table tags Command Argument a EKA C T separator title tags Table 16 4 psql output format shortcuts 147 148 CHAPTER 16 DATABASE QUERY TOOLS test gt set num var 4 test gt SELECT num var column 1 row test gt set operation SELECT test gt operation num_var column 1 row test gt set str var My long stringl test gt lecho str var
124. 70 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 Appendix B Installation Getting POSTGRESQL The POSTGRESQL software is distributed in several formats e Tar gzipped file with file extension tar gz e Prepackaged file with file extension rpm e Another prepackaged format e CD ROM Because there are so many formats this appendix will only cover the general steps need to install POST GRESQL Each distribution comes with a INSTALL or README file with more specific instructions Create the POSTGRESQL User It is best to create a separate user to own the POSTGRESQL files and processes that are about to be installed The user name is typically postgres Configure Many distributions use a configure command which allows users to choose various options before compiling and installing the software Compiling POSTGRESQL is usually distributed in source code format This means that the C source code must be compiled
125. 703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 Chapter 20 Administration This chapter covers a variety of administrative tasks The chapter assumes POSTGRESQL is installed and running If it is not see appendix B 20 1 Files When POSTGRESQL is installed it creates files in its home directory typically usr local pgsql This directory contains all the files needed by POSTGRESQL It contains various subdirectories bin This contains POSTGRESQL command line programs like psq1 data This contains configuration files and tables shared by all databases For example pg shadow is a table shared by all databases data base This contains a subdirectory for each database Using the du and 1s commands administrators can display the amount of disk space used by each database table or index doc This contains POSTGRESQL documentation and manual pages include T
126. 81 10882 10883 10884 10885 10886 10887 10888 10889 10890 15 3 DELIMITERS 141 because the COPY file is designed for easy processing with one TAB between each column It is not designed for display purposes 15 3 DELIMITERS The default TAB column delimiter can be changed COPY has a USING DELIMITERS option that sets the column delimiter Figure 15 3 shows that setting the delimiter to a pipe symbol causes the output file to use pipes to separate columns test gt COPY copytest TO tmp copytest out USING DELIMITERS COPY test gt q cat tmp copytest out 1 23 99 fresh spring water t 2 55 23 bottled soda t Figure 15 3 Example of COPY TO USING DELIMITERS If a COPY file does not use the default TAB column delimiter COPY FROM must use the proper USING DELIMITERS option Figure 15 3 shows that if a file uses pipes rather than TABs as column delimiters COPY FROM must specify pipes as delimiters The first COPY FROM fails because it cannot find a TAB to test gt DELETE FROM copytest DELETE 2 test gt test gt COPY copytest FROM tmp copytest out ERROR copy line 1 pg atoi error in 1 23 99 fresh spring water t can t parse 23 99 fresh spring water t test gt test gt COPY copytest FROM tmp copytest out USING DELIMITERS COPY Figure 15 4 Example of COPY FROM USING DELIMITERS separate the columns The second COPY FROM succeeds because the proper delimiter for
127. 9369 9370 9371 9372 13 4 INHERITANCE 119 i test gt INSERT INTO parent_test VALUES 1 9375 INSERT 18837 1 9376 test gt INSERT INTO child test VALUES 2 3 9377 9378 INSERT 18838 1 9379 test gt SELECT FROM parent_test 3390 coll 9381 9382 9383 1 3384 1 row 9385 9386 9387 test gt SELECT FROM child_test 9388 9380 coll col2 9390 Terenez 9391 2 3 9392 9393 1 row 9394 9395 test gt SELECT FROM parent test 9396 9397 coll 938 wee 9399 1 9400 9401 2 9402 2 rows 9403 9404 9405 oo z 9406 Figure 13 6 Accessing inherited tables 9407 9408 a test gt CREATE TABLE grandchild test col3 INTEGER INHERITS child test 9411 CREATE 9412 test gt INSERT INTO grandchild test VALUES 4 5 6 9413 9414 INSERT 18853 1 9415 test gt SELECT FROM parent_test 9416 coll 9417 9418 9419 1 9420 2 9421 9422 4 9423 3 rows 9424 9425 9426 test gt SELECT FROM child_test 9427 coll col2 9428 0 Pew e 9429 9430 dl 3 9431 4 5 9432 9433 9434 9435 9436 Figure 13 7 Inheritance in layers 9437 9438 2 rows 120 CHAPTER 13 TABLE MANAGEMENT Consider a practical example that records information about employees and managers Table employee can hold information about non managerial employees Manager can hold information about managers Manager can inherit all the columns from employee and have additional columns You can then access no
128. 94 Oa Eo AA 94 9 5 Weegee escri ARA AA 95 Ad A KS OER ea HERE eRe HEE ORAS 96 10 1 INSERT with no explicit transaction 2 426 464 rennen ab evar d ad ed eae 97 10 2 INSERT with explicit transaction o ecce ve ae E AR AAA 98 10 3 Two INSERTS in a Single transaction seas atman neden e a 98 10 4 Multi statement transaction oc c s ec aeea aa 24062 a a 98 10 5 Transaction o MAA 99 10 6 Read committed isolation level os ccc co ccce rr RA 100 10 7 Serializable meen VEL coca a A ARA ARA 101 105 SELECT WIK AU DORE nce kes eee nt TEN SAS 2a De HS RS 102 109 SELECTA POR UPDATE oG zn neen A RR ER a Oe PERG Eee ee RAPE SE 103 11 1 Example of CREATE INDER oca te bak Gade ad OER ea a a Gales 105 11 2 Example of a unique MAER 2 o oes oee Ee Owe HOS ESO Oe dT 106 US Ea 107 11 4 More complex EXPLAINexamples 2 o n a a tt ee ee 108 11 5 EXPLAIN example using Joins see enaties 109 12 1 Examples of LIMIT and LIMIT OFFSET cocipnr isis drin dna ns 111 12A CUERO USAR nn a oo Sie AA a Ee an aa 113 13 1 Temporary table auto destruction s eee 116 13 2 Example of temporary table use e co snee en ea ee ee e 116 133 ALTER TABLE SRMADER o cier a AR A RA A RA 117 13 4 Examples ofthe GRANT Command s se ss se oan ee a A a Rod 118 13 5 Creation Of Inherited NAMEN or ee ee a A ee AA PES 118 13 6 Accessing inherited tables e 119 E MLO 6 ee eee ede Oe be de eed bwin dad ds 119 13 9 Examples of Views ss oee vane oe we BO oe Hee
129. ACUUM manual page shows all of the VACUUM options 11 6 EXPLAIN EXPLAIN causes POSTGRESQL to display how a query will be executed rather than executing it For example figure 11 3 shows a SELECT query preceeded by the word EXPLAIN In the figure POSTGRESQL reports a test gt EXPLAIN SELECT customer_id FROM customer NOTICE QUERY PLAN Seq Scan on customer cost 0 00 15 00 rows 1000 width 4 EXPLAIN Figure 11 3 Using EXPLAIN sequential scan will be used on customer meaning it will scan the entire table Cost is an estimate of the work required to execute the query The numbers are only meaningful for comparison Rows indicates the number of rows it expects to return Width is the number of bytes per row Figure 11 4 shows more interesting examples of EXPLAIN The first EXPLAIN shows a SELECT with the restriction customer id 55 This is again a sequential scan but the restriction causes POSTGRESQL to estimate ten rows will be returned A VACUUM ANALYZE is run causing the next query to properly estimate one row will be returned instead of ten An index is created and the query rerun This time an index scan 108 CHAPTER 11 PERFORMANCE 8647 8648 8649 8650 8651 8652 8653 test gt EXPLAIN SELECT customer id FROM customer WHERE customer id 55 ee NOTICE QUERY PLAN 8656 8657 8658 Seq Scan on customer cost 0 00 22 50 rows 10 width 4 8659 8660 EXPLAIN sees test gt VACUUM ANALYZE customer 8663 VACUUM 8664
130. AR A SE EA AA AAA 27 LER OMD eek ee RRS Ree See REG SANE SS RA 28 Regular expression operators 1 1 sosoo soe e e ee es 29 Regular expression special characters tt es 29 Regular expression examples 2 eee et ee ee es 31 SET OOUORE RAEE RARAS SESSLER Ew eee SES RE WES a 34 DATESTYUR OUTPUT lt lt ane ee ae he Bal ae ws Be gee ee Se en ar Bh Sad B ae ee 34 POU ORCS oe ve Gd ae Ghee to See de Ee ed We a A Gk 39 Sequence number access functions ee ee es 65 POSTGRESQL data types ps ooo ew kaw Ce ew ee eee a Re ewe a 88 GEOMEITICI DES oe oe A AR ae ek SE ERA ee ONS Ow A 4 90 COMMORTUACIONS s gors da ed ae de dek aem hare HAG dee PH Wee Re 92 COMMON OPEfalors lt sca na on aa Le ae eee EE Oe eS eee ee E 93 COMMON vanabl s 20 a da A Go ae ee a a CE aw Gea eS 94 Visibility of single query transactions 1 ee ee es 99 Visibility using multi query transactions so e 100 Woe ne as a EE ee hee das ded 102 Deadlock v e sae wee eR ae a ARE HR a Ew De ee ASS Rs 103 Temporary table i olati n sb on rss dra a a ESE Ow SY 115 Backslashes understood by COPY ee eee 143 psql query buffer commands coc eaaa eonia e a e a ee ee te ee es 145 psal general COMMANKS sn du A ald we OE Ar a een a Be a ew a A 146 SGU APSEROPUORS cad en el de a de A ADS a 146 psal output format SHOTICUTS coco cis oaeen ae ou ar aa ete a ew ee 147 psql predefined variables n aoo nonoo 149 psa
131. E clause every row is returned The WHERE clause goes right after the FROM clause In the WHERE clause you specify the rows you want returned as shown in figure 3 6 The query returns the rows that have an age column equal to 23 Figure 3 7 test gt SELECT FROM friend WHERE age 23 firstname lastname city state age Cindy Anderson Denver co 23 1 row Figure 3 6 My first WHERE shows a more complex example that returns two rows You can combine the column restrictions and the row test gt SELECT FROM friend WHERE age lt 22 firstname lastname city state age Mike Nichols Tampa FL 19 Sam Jackson Allentown PA 22 2 rows Figure 3 7 More complex WHERE clause restrictions in a single query allowing you to select any single cell or a block of cells See figures 3 8 and 3 9 test gt SELECT lastname FROM friend WHERE age 22 lastname Jackson 1 row Figure 3 8 A single cell Try using one of the other columns in the WHERE clause Up to this point we have made only comparisons test gt SELECT city state FROM friend WHERE age gt 21 city state Sia aia AE Hemmie Denver CO Allentown PA 2 rows Figure 3 9 A block of cells on the age column The age column is integer The only tricky part about the other columns is that they 14 CHAPTER 3
132. ET CONSTRAINTS See the CREATE_TABLE and SET manual pages for more information 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 14 4 FOREIGN KEY REFERENCES test gt test gt INSERT test gt test gt INSERT test gt test gt UPDATE test gt test gt test gt test gt test gt test gt NOTICE CREATE test gt test gt UPDATE test gt test gt ERROR INSERT INTO primarytest2 VALUES 1 2 148816 1 INSERT INTO foreigntest2 VALUES 1 2 148817 1 UPDATE foreigntest2 SET col4 NULL 1 CREATE TABLE matchtest col3 INTEGER col4 INTEGER FOREIGN KEY
133. FROM trans test returns 1 SELECT FROM trans test returns 1 Table 10 1 Visibility of single query transactions 1 sees the changes made by his transaction However user 2 does not see the changes until user 1 commits the transaction This is another advantage of transactions They insulate users from seeing uncommitted transactions Users never see a partially committed view of the database As another example consider the bank account query where we transfered 100 from one bank account to another Suppose we were calculating the total amount of money in all bank accounts at the same time the 100 was being transfered If we did not see a consistent view of the database we could have seen the 100 removed from the account but not see the 100 added Our bank account total would be wrong A consistent database view means we either see the 100 in its original account or we see it in its new account 100 CHAPTER 10 TRANSACTIONS AND LOCKS User 1 User 2 Notes BEGIN WORK User 1 starts a transaction SELECT FROM trans test returns 0 INSERT INTO trans_test VALUES 1 add row to trans test SELECT FROM frans test returns 1 SELECT FROM trans test returns 0 COMMIT WORK SELECT FROM trans test returns 1 Table 10 2 Visibility using multi query transactions Without this feature we would have to make sure no one was making bank account transfers while we were calculating the amount of money in all accounts Whil
134. Finally it reconnects to the database as a different user This was possible because the site has local users configured with trust access This is covered in section 20 4 These commands can only be performed by a user with create user privileges More information about each command can be found in the manual pages 20 3 Creating Databases New databases are created by running createdb from an operating system prompt Initially only the POST GRESQL super user can create new databases Other users can be given permission to create new databases Createdb creates a new database by making a copy of the templatel database Templatel is made when POSTGRESQL is first initialized Any modifications to templatel will appear in newly created databases Databases are removed with dropdb CREATE DATABASE and DROP DATABASE commands are also available in SQL Figure 20 2 shows a database created from the command line and another one created in psq1 A database createdb demodb1 CREATE DATABASE psql test Welcome to psql the PostgreSQL interactive terminal Type copyright for distribution terms h for help with SQL commands for help on internal slash commands g or terminate with semicolon to execute query q to quit test gt CREATE DATABASE demodb2 CREATE DATABASE test gt DROP DATABASE demodb1 DROP DATABASE test gt connect demodb2 You are now connected to database demodb2 demodb2 gt q Figure 20 2 Examples of database
135. L when using the default NULL representation The other backslash entries show simple representations for common characters The last line shows double backslash is required to represent a literal backslash 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 15 6 COPY TIPS 143 Backslash string Meaning VTAB TAB if using default delimiter TAB pipe if using pipe as the delimiter N NULL if using the default NULL output b backspace f form feed n newline r carriage return t tab v vertical tab character represented by octal number backslash Table 15 1 Backslashes u
136. LE output 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 4 14 SET SHOW AND RESET test gt df List of functions Result Function l Arguments A des A A AI II A A _bpchar _bpchar _bpchar int4 _varchar _varchar _varchar int4 numeric abs numeric test gt df int List of functions Result Function Arguments elec scons Ep a a A N EDEA int4 int int4 int2 int2 float4 test gt df upper List of functions Result Function Arguments zes His cata cada text upper text 1 row test gt dd upper Object descriptions Name What Description So flee ee ot eee ees upper function uppercase 1 row test gt SELECT upper jacket upper JACKET test gt SELECT sqrt 2 0
137. LETE query This means if you perform a set of complex table modifications foreign key constraints must remain valid at all times For example using the tables in figure 14 7 if there is a new state and a new customer in the new state the new state must be added to statename before the customer is added to customer In some cases it is not possible to keep foreign key constraints valid between queries For example if two tables are foreign keys for each other it may not be possible to INSERT into one table without having the other table row already present A solution is to use the DEFERRABLE foreign key option and SET CONSTRAINTS so foreign key constraints are checked only at transaction commit Using these a multi query transaction can make table modifications that violate foreign key constraints inside the transaction as long as the foreign key constraints are met at transactions commit Figure 14 14 illustrates this This is a contrived example because the proper way to perform this query is to INSERT into primarytest first then INSERT into defertest However in complex situations this reordering might not be possible and DEFERRABLE and SET CONSTRAINTS should be used to defer foreign key constraints A foreign key may also be configured as INITIALLY DEFERRED causing the constraint to be checked only at transaction commit by default Constraints can even be named Constraint names appear in constraint violation messages and can be used by S
138. N DELETE NO ACTION NO ACTION is the default so ON DELETE NO ACTION was not required The figure inserts a single row into each table then shows an UPDATE on primarytest cascades to UPDATE foreigntest The figure also shows that the primarytest row cannot be deleted unless the foreign key row is deleted first Foreign key actions offer great flexibility in controlling how primary key changes affect foreign key rows Multi Column Primary Keys In order to specify a multi column primary key it was necessary to use PRIMARY KEY on a separate line in the CREATE TABLE statement Multi column foreign keys have the same requirement Using primarytest2 from figure 14 6 figure 14 12 shows how to create a multi column foreign key FOREIGN KEY col must be used to label multi column foreign key table constraints 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 14 4 FOREIGN KEY REFERENCES 133 10297 10298 10299 10300 10301 test gt CREATE TABLE primarytest col INTEGER PRIMARY KEY e NOTICE CREATE TABLE PRIMARY KEY will create implicit index
139. O aggtest VALUES NULL INSERT 18826 1 test gt SELECT SUM col FROM aggtest sum 1 row test gt SELECT MAX col FROM aggtest max 1 row test gt SELECT COUNT FROM aggtest count count test gt INSERT INTO aggtest VALUES 3 INSERT 18827 1 test gt SELECT AVG col FROM aggtest avg count count Figure 5 2 Aggregates and NULLs 41 42 CHAPTER 5 SQL AGGREGATES 5 2 Using GROUP BY Simple aggregates return one row as a result It is often desirable to apply an aggregate to groups of rows Queries using aggregates with GROUP BY have the aggregate applied to rows grouped by another column in the table For example SELECT COUNT FROM friend returns the total number of rows in the table The query in figure 5 3 shows the use of GROUP BY to generate a count of the number of people in each state COUNT is not applied to the entire table at once With GROUP BY the table is split up into groups by state and COUNT is applied to each group test gt SELECT state COUNT test gt FROM friend test gt GROUP BY state state count PA 4 rows test gt SELECT state MIN age MAX age AVG age test gt FROM friend test gt GROUP BY state test gt ORDER BY 4 DESC state min max avg PA 22 22 22 4 rows Figure 5 3 Aggregate with GROUP BY The second query shows the minimum maximum and average age of the people in each state It also shows an ORDER BY on the aggregate
140. REATE TABLE will create implicit sequence customer customer id seq for SERIAL column customer customer_id NOTICE CREATE TABLE UNIQUE will create implicit index customer customer id key for table customer CREATE test gt d customer Table customer customer id int4 name char 30 Index customer customer id key test gt INSERT INTO customer name VALUES Car Wash INSERT 19152 1 test gt SELECT FROM customer customer id name eee EE 1 Car Wash Figure 7 5 Customer table using SERIAL the second NOTICE line in the figure Indexing is covered in section 11 1 7 7 Manually Numbering Rows Some people wonder why OIDs and sequences are needed Why can t a database user just find the highest number in use add one and use that as the new unique row number There are several reasons why OIDs and sequences are preferred e Performance e Concurrency e Standardization First it is usually slow to scan all numbers currently in use to find the next available number Using a counter in a separate location is faster Second there is the problem of concurrency If one user gets the highest number and another user is looking for the highest number at the same time the two users might 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044
141. ROM customer test gt WHERE customer id NOT IN test gt SELECT customer id test gt FROM salesorder test gt name 0 rows Figure 8 11 Customers who have no orders NOT IN and Subqueries with NULLs If a NOT IN subquery returns a NULL row the NOT IN comparison always returns false This is because NOT IN requires the upper column to be not equal to every value returned by the subquery Every inequality comparison must return true However all comparisons with NULL return false even inequality comparisons so NOT IN returns false NULL comparisons are covered in section 4 3 We can prevent NULLs from reaching the upper query by adding IS NOT NULL to the subquery As an example in figure 8 11 if there were any NULL customer_id values the query would return no rows We can prevent this by adding WHERE customer_id IS NOT NULL to the subquery An IN subquery does not have this problem with NULLs because IN will return true if it finds any true equality comparison NOT IN must find all inequality comparison to be true There is another way to analyze subqueries returning NULLs Suppose a subquery returns three rows 1 2 and NULL The test uppercol NOT IN subquery expands to uppercol NOT IN 1 2 NULL This further expands to uppercol lt gt 1 AND uppercol lt gt 2 AND uppercol lt gt NULL The last comparison with NULL is false because all comparisons with NULL are false even not equal comparisons AND returns false if
142. T Figure 10 3 Two INSERTs in a single transaction For a more complicated example suppose you have a table of bank account balances and suppose you wish to transfer 100 from one account to another account This is performed using two queries an UPDATE to subtract 100 from one account and an UPDATE to add 100 to another account The UPDATEs should either both complete or none of them If the first UPDATE completes but not the second the 100 would disappear from the bank records It would have been subtracted from one account but never added to any account Such errors are very hard to find Multi statement transactions prevent them from happening Figure 10 4 shows the two queries bound into a single transaction The transaction forces POSTGRESQL to test gt BEGIN WORK BEGIN test gt UPDATE bankacct SET balance balance 100 WHERE acctno 82021 UPDATE 1 test gt UPDATE bankacct SET balance balance 100 WHERE acctno 96814 UPDATE 1 test gt COMMIT WORK COMMIT Figure 10 4 Multi statement transaction perform the queries as a single operation 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 81
143. T 148947 1 10540 test gt COMMIT 10541 10542 COMMIT ee 10544 10545 Figure 14 14 DEFERRABLE foreign key constraint re 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 14 5 CHECK 137 145 CHECK The CHECK constraint enforces column value restrictions CHECK constraints can restrict a column to a set of values only positive numbers or reasonable dates Figure 14 15 shows an example of CHECK constraints This is a modified version of the friend table from figure 3 2 page 10 This figure has many CHECK clauses test gt CREATE TABLE friend2 test gt firstname CHAR 15 test gt lastname CHAR 20 test gt city CHAR 15 test gt state CHAR 2 CHECK length trim state 2 test gt age INTEGER CHECK age gt 0 test gt gender CHAR 1 CHECK gender IN M F test gt last_met DATE CHECK last_met BETWEEN 1950 01 01 test gt AND CURRENT DATE test gt CHECK upper trim firstname AL OR
144. This is done by either recompiling the language or dynamically loading the interface into the language The following gives details about each interface PERL Use loads the POSTGRESQL interface into the PERL interpreter TCL TK TCL TK offers three interface options e Pre built TCL interpreter called pgtclsh e Pre built TCL TK interpreter called pgtksh like TCL TK s wish Loadable library called libpgtcl PYTHON Import loads the POSTGRESQL interface into the PYTHON interpreter PHP PHP must be recompiled to access POSTGRESQL 17 15 Summary All interface source code is located in pgsql src interfaces Each interface includes sample source code for use in writing your own programs These interfaces allow the creation of professional database applications Each interface has advantages Some are easier some faster some more popular and some work better in certain environments The choice of an interface is often difficult Hopefully this chapter will make that choice easier 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12
145. W ay Bs 24 AG GOMMERS en on we la a vete we Ai a a a EE at ee we 25 LF AOR reren nnen the erk ane 25 AS B nde ot Valles nm ad Bd Re laa Ee Bee Wa a Rhee BE are 26 A vane eee B A B anke sk 28 410 Repular tr 29 ALI CASE Clase cocos a eae a RE es 32 AMA Dista ROWS a se a ros Sh iw aa bee te RA ede A tbe He Gh ar ied 32 4 13 Fu ctions and Operators ccc aranea A ORS Oe SES 33 AIA SET SHOW and RESET o sa ace oe aa ie Go GH OU age aw B 33 lS UI canoa eee A AE Oe ORS A CASE ES 37 5 SQL Aggregates 39 Gl o o 22646 6n08 be 0 ea ee eee awe ba ee es Dae pele eae be 39 CeO Cat AI 42 Bo Using HAVING lt 2 es2isened es Ce eead Ra tenes SES ES Ee a 42 DD OER MDN ve che Gave ERE Ge ee ea Bee da ee Er Se ee we Bas 43 Oo SUES te oy Bri ee dae he Be Dee Saw See ee ee BE wd 44 6 Joining Tables 45 6 1 Table and Column References eee 45 62 Jomed Tables ee vane lw ew ee Re a we 45 6 3 Creating Jomed TaDIES vias ad eek ERE RARE EER ERES SHARED ER ES BS 47 Of Perlorming Oe gt restaurant 50 6 5 Three and Four Table Joins eee ee ee ee ee ee es 51 6 6 Additional Jom Possibilities a oi nen ar ate ek ee as 53 Or ChoosmgaJoin Key ss sde na aat nee SESS teha hee Ht 54 6 8 Uisdo Man Joins socie A AA A a 55 69 Umomed Tables ARI 57 6 10 Table Aliases and Self Joins eee 57 GTI Nom II 58 6 12 Ordene Multiple Parts s ce ostat ere usa ARA AAA ES 58 6 13 Primary and Foreign Keys onee vanen A A A a 60 OLA SUMY see be en ee e
146. all rows returned cout lt lt data GetValue i 0 lt lt endl print the value returned return 0 Figure 17 7 Libpq sample program 160 CHAPTER 17 PROGRAMMING INTERFACES The compiler flag l is needed so the compiler links to a specific library file To link to libpq a or libpq so the flag 1pq is needed The flag knows the file begins with lib so 11ibpq is not required just 1pq The commands to compile myapp for various interfaces are listed below libpq cc I usr local pgsql include o myapp myapp c L usr local pgsql lib 1pq libpgeasy cc I usr local pgsql include o myapp myapp c L usr local pgsql lib 1pgeasy ecpg ecpg myapp pgc cc I usr local pgsql include o myapp myapp c L usr local pgsq1 1ib lecpg libpq cc I usr local pgsql include o myapp myapp cpp L usr local pgsql lib 1pq Notice each interface has its own library Ecpg requires the ecpg preprocessor to be run before compilation Libpq requires a different compiler to be used 17 6 Assignment to Program Variables POSTGRESQL is a network capable database This means the database server and user application can be run on different computers Because character strings have the same representation on all computers they are used for communication between the user program and database server Queries are submitted as character strings and results are passed back as character strings This allows reliable communication even if the two computers a
147. ame Gleason we would get both Sandy Gleason and her brother Dick Gleason The proper way is to use AND to join tests of both firstname and lastname The proper query is shown in figure 4 11 The AND joins the two comparisons we need A similar comparison could be done to select friends living in Cedar Creek Maryland There could be other friends living in Cedar Creek Ohio so the comparison city Cedar Creek is not enough The proper test is city Cedar Creek AND state MD Another complex test would be to select people who are in the state of New Jersey NJ or Pennsylvania PA Such a comparison requires the use of OR The test state NJ OR state PA would return the desired rows as shown in figure 4 12 26 CHAPTER 4 CUSTOMIZING QUERIES test gt SELECT FROM friend test gt WHERE firstname Sandy AND lastname Gleason firstname lastname city state age Sandy Gleason Ocean City INJ 25 1 row Figure 4 11 WHERE test for Sandy Gleason test gt SELECT FROM friend test gt WHERE state NJ OR state PA test gt ORDER BY firstname firstname lastname city state age Dick Gleason Ocean City INJ 19 Sandy Gleason Ocean City NJ 25 Victor Tabor Williamsport PA 22 3 rows Figure 4 12 Friends in New Jersey and Pennsylvania An unlimited
148. ance of SQL queries This chapter covers more general performance consid erations One of the most important administrative tasks is the scheduling of the vacuumdb a command This vacuums all databases It should be run when the databases are least busy Section 11 4 describes the purpose of vacuuming Vacuum analyze should also be performed periodically This is covered in section 11 5 Vacuumdb can perform analyzing as well See the vacuumdb manual page for more information Postmaster and postgres have several flags that can improve performance The postgres F flag prevents the flushing of kernel buffers to disk at transaction commit While this improves performance it also affects data reliability If there is an operating system crash or power failure only part of a transaction may have been written to disk When this happens the database must be restored from backup This option may be removed in future POSTGRESQL releases when write ahead logging WAL is implemented The postmaster B flag controls the amount of shared buffer memory allocated The postgres S flag controls the amount sort memory allocated While these consume system resources they also improve performance by reducing disk access Database performance can also be improved by moving databases to different disk drives This allows disk access to be spread among multiple drives The initlocation utility allows new database locations to be created on different drives Createdb ca
149. and side For example the test col IN 1 2 3 4 compares col against four values If col equals any of the four values the comparison will return true and output the row The test col NOT IN 1 2 3 4 will return true if col does not equal any of the four values An unlimited number of values can be specified on the right hand side of an IN or NOT IN comparison In addition instead of constants a subquery can be placed on the right hand side The subquery can return multiple rows The subquery is evaluated and its output used like a list of constant values Suppose we want all employees who took sales orders on a certain date We could perform the query two ways We could join the employee and salesorder tables as shown in the first query of figure 8 10 The second test gt SELECT DISTINCT employee name test gt FROM employee salesorder test gt WHERE employee employee id salesorder employee id AND test gt salesorder order date 7 19 1994 name Lee Meyers 1 row test gt SELECT name test gt FROM employee test gt WHERE employee id IN test gt SELECT employee_id test gt FROM salesorder test gt WHERE order date 7 19 1994 test gt name Lee Meyers 1 row Figure 8 10 Employees who took orders query uses a subquery The subquery is evaluated and generates a list of values used by IN to perform the comparison The subquery is possible because the salesorder table is involved in a single join and
150. any of its comparisons return false Therefore the NOT IN comparison returns false If the test used IN the comparison would be uppercol 1 OR uppercol 2 OR uppercol NULL While the last comparison is false OR will return true if any of the comparisons is true It does not require them all to be true like AND Subqueries Returning Multiple Columns Most subqueries return a single column to the upper query However 1t is possible to handle subqueries returning more than one column For example the test WHERE 7 3 IN SELECT coll col2 FROM subtable returns true ifthe subquery returns a row with 7 in the first column and 3 in the second column The test WHERE uppercoll uppercol2 IN SELECT coll col2 FROM subtable performs equality comparisons between the upper two columns and the subquery s two columns This allows multiple columns in the upper query to be compared with multiple columns in the subquery Of course the number of values specified on the left of IN or NOT IN must be the same as the number of columns returned by the subquery ANY ALL and EXISTS Clauses IN and NOT IN are special cases of the more generic subquery clauses ANY ALL and EXISTS ANY will return true if the comparison operator is true for any value in the subquery The test col lt ANY 5 7 9 returns true if col is less than any of the three values ALL requires all subquery values to compare as true so col lt 80 CHAPTER 8 COMBINING SELECTS ALL 5
151. are features unique to POSTGRESQL Chapter 14 None Chapter 15 COPY s a unique feature of POSTGRESQL Chapter 16 Psql and pgaccess are unique features of POSTGRESQL Chapter 17 All the programming interfaces except libecpg and JAVA are implemented differently in other database systems 197 198 APPENDIX C POSTGRESQL NON STANDARD FEATURES BY CHAPTER Chapter 18 Server side functions and triggers are implented differently in other database systems Chapter 19 Using C to enhance the database is a unique POSTGRESQL feature Chapter 20 The administrative utilities are unique to POSTGRESQL 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 us Appendix D 14661 14662 14663 us Ref M l u ererence Wianua 14667 14668 14669 14670 B 14671 The following is a copy of the reference manual pages man pages as they appeared in a pre release 14672 version of POSTGRESQL 7 0 These come from http www postgresql org docs user sql commands htmand 7 http www postgresql org docs us
152. art name test gt FROM part employee test gt WHERE part employee id employee employee id AND test gt employee employee_id 24 test gt ORDER BY name Figure 6 12 Joining part and employee There are cases where a join could be performed with the state column For example to check state codes for validity a statecode table could be created with all valid state codes An application could check gt The United States Postal Service has assigned a unique two letter code to each U S state 54 CHAPTER 6 JOINING TABLES the state code entered by the user and report an error if the state code is not in the statecode table Another example would be the need to print the full state name in queries State names could be stored in a separate table and joined when the full state name is desired Figure 17 2 shows an example of a statename table This test gt CREATE TABLE statename code CHAR 2 test gt name CHAR 30 test gt CREATE test gt INSERT INTO statename VALUES AL Alabama INSERT 18934 1 test gt SELECT statename name AS customer_statename test gt FROM customer statename test gt WHERE customer customer id 648 AND test gt customer state statename code Figure 6 13 Statename table shows two more uses for additional tables e Check codes against a list of valid values i e only allow valid state codes e Store code descriptions i e state code and state name 6 7 Choosing a Join Key
153. art_id part part_id Figure 6 22 Queries involving orderpart table 6l 62 CHAPTER 6 JOINING TABLES 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 Chapter 7 Numbering Rows Unique identification numbers and short character codes allow reference to specific rows in a table They were used extensively in the previous chapter The customer table had a customer_id column that held a unique identification number for each customer The employee and part tables had similar uniquely numbered columns Those columns were important for joins to those tables While unique character codes must be supplied by users unique row numbers can be generated auto matically using two methods This chapter shows how to uniquely number rows in POSTGRESQL 7 1 Object Identification Numbers OIDs Every row in POSTGRESQL is assigned a unique normally invisible number called an object identification number or OID When the software is initialized with initdb a counter is created and set to approximately seventeen thousand The counter is used to uniquely number every row Databases can be created and destroyed but th
154. ate Raed tee Med od 12 20 NDL EMM 12 3 6 MVAESEWHERE s ros reagan em A Ae ER aN MESSE aE 13 3 7 More complex WHERE clause 2 1 ee eee eee 13 26 ASIS ra ee dn AAA ee ee E ASA 13 29 A DIOERORGENS ar aoe A a as A Ee A 4 13 SL Comparne MOO a A ek BE SE GO ES 14 311 DELETE Example 54444446 Ra A we ed 15 312 My Arst UPDATE rieseg 245 terne dn had EER in Bee Wd 15 3 19 Lee Of ORDER EY nana Eee RARE SSH 16 21A Reverse ORDER BY o ro hee Doe doe ceed ewe i aa ede ce eee sd aceadss 16 3 15 Useof ORDER BY and WHERE s 6 6 eee ek ebb oe eae eh a 16 4 1 Example of common datatypes ee ee 20 4 2 Insertion of specific columns ici RSS Rw RE ASS RRA 21 AA rrkm ew ee ee Ba 22 AA Comparison or TEIUS cs as AAA AAA RA A A 22 den NULLS and DAS sen eenen mad hee AR RA A A i 23 46 USO PERU 4 oe peed a ee ee Ree Tbr A dann 24 LF Controlling column labels lt gt AAA dae ee ee ARA 24 4 8 Computation using a column label n noaoo ee es 24 ES Comment Styles endoa 44 4 4046 A paca dard e ea a da 25 AIO NeW AI 25 4 11 WHERE test for Sandy Gleason o e se ce ew aade a aa k e a e 26 4 12 Friends in New Jersey and Pennsylvania lt cc e wee ES 26 413 MEE A OS TODOS os eee RA ERED a a DEE RA 26 4 14 Properly mixing ANDS and ORS 4 os oss cris ARA AAA 27 4 15 SEE arange of Valie amp 64 eee ae a ARA AAA Ok 27 410 Fosmame Dees WIND cdo tene dae AA AA RRA A Ore 28 4 17 Regular expression sample queries 22 aaa DR OA a 30
155. base We had a whole list of them It became clear that some organization was needed Most bug reports required significant research to fix and many were duplicates so our TODO list reported every buggy SQL query It helped us identify our bugs and made users aware of them too cutting down on duplicate bug reports We had many eager developers but the learning curve in understanding how the back end worked was significant Many developers got involved in the edges of the source code like language interfaces or database tools where things were easier to understand Other developers focused on specific problem queries trying to locate the source of the bug It was amazing to see that many bugs were fixed with just one line of C code POSTGRES had evolved in an academic environment and had not been exposed to the full spectrum of real world queries During that period there was talk of adding features but the instability of the system made bug fixing our major focus 1 4 POSTGRESQL Global Development Team In late 1996 we changed the name from POSTGRES95 to POSTGRESQL It is a mouthful but honors the Berkeley name and SQL capabilities We started distributing the source code using remote cvs which allowed people to keep up to date copies of the development tree without downloading an entire set of files every day Releases were every 3 5 months This consisted of 2 3 months of development one month of beta testing a major release and a few
156. ber Boston MA 33 Victor Tabor Williamsport PA 22 6 rows test gt SELECT fl firstname fl lastname fl state test gt FROM friend fl friend f2 test gt WHERE fl state lt gt f2 state AND test gt f2 firstname Dick AND test gt f2 lastname Gleason test gt ORDER BY firstname lastname firstname lastname state EEE en AE A gn epe Dean Yeager MA Ned Millstone MD Sandy Weber MA Victor Tabor PA 4 rows test gt SELECT fl firstname fl lastname fl state test gt FROM friend fl test gt WHERE fl state lt gt test gt SELECT f2 state test gt FROM friend f2 test gt WHERE f2 firstname Dick AND test gt f2 lastname Gleason test gt test gt ORDER BY firstname lastname firstname lastname state o A E SEEE A E ane Dean Yeager MA Ned Millstone MD Sandy Weber MA Victor Tabor PA 4 rows Figure 8 7 Friends not in Dick Gleason s state 79 76 CHAPTER 8 COMBINING SELECTS tables This is shown as the first query in figure 8 8 The second query does not have a join but instead gets test gt SELECT name test gt FROM customer salesorder test gt WHERE customer customer id salesorder customer id AND test gt salesorder order id 14673 name Fleer Gearworks Inc 1 row test gt SELECT name test gt FROM customer test gt WHERE customer customer id test gt SELECT salesorder customer_id test gt FROM salesorder t
157. ble miis el Gee ne Be dl Geel e a a 169 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 LIST OF FIGURES Xxl 1321 18 4 SOL shipping RICO as ee RR RE GRE RR a MR ER ERE 170 1322 18 5 SQL function getstatename een 171 Eep 18 6 Getting state name using join and function 20 64666046 errar 171 1325 18 7 PL PGSQL version of getstatename nnna ee ee es 172 1326 18 8 PLUPGSQL gread CIO lt a RARA HERON EH A AA RE REESE 173 nit 18 9 PL PGSQL getstatecode function lt lt o lt s cre eee eee ee 174 1329 18 10Calls to getstatecode function eee 175 He 18 11PL PGSQL change_statename function oo e es 176 1332 18 12Example of change statename err nnen AAA ARANA 177 1333 INIA ION e dee RAR A ARA A RR AA A 179 1334 1335 Lo DT Cdo MUCUR cd A a ds A Oe Hae is 182 1337 19 2 Create MORE Sir ic AAA EER sz 182 1338 19 3 Calling TUCOON O esed hae een d RRR AAA AR AR 183 1339 Hr 20 1 Examples of user administration s o ee ee es 186 1342 20 2 Examples of database creation and removal es 187 1343 20 3 Making a new copy of database t
158. c Network Type TEXT VARCHAR length CHAR length INTEGER INT2 INT8 OID NUMERIC precision decimal FLOAT FLOAT4 DATE TIME TIMESTAMP INTERVAL POINT LSEG PATH BOX CIRCLE POLYGON INET CIDR MACADDR CHAPTER 9 DATA TYPES 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 Description PA 342 variable storage length 7343 variable storage length with maximum length 7344 fixed storage length blank padded to length internally BPCHAR is integer 2 billion range internally INT4 7347 integer 32 thousand range 7348 integer 4 x 101 range Ge object identifier 7351 number user defined precision and decimal location 7352 floating point number 15 digit precision internally FLOAT8 EEn floating point number 6 digit precision 7355 date 356 7357 time 7358 date and time 7359 interval of time 7360 boolean true or false 7362 point 7363 line ment 1903 segme 7365 list of points 7366 rectangle T367 rel 7368 circle 7369 polygon 7370 IP address with optional netmask as IP network address 7373 Ethernet MAC address 7374 7375 Table 9 1 POSTGRESQL data types Be 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425
159. cessing a table POSTGRESQL normally reads from the beginning of the table to the end looking for relevant rows With an index POSTGRESQL can quickly find specific values in the index and go directly to matching rows Indexes allow fast retrieval of specific rows from a table For example consider the query SELECT FROM customer WHERE col 43 Without an index POST GRESQL must scan the entire table looking for rows where col equals 43 With an index on col POSTGRESQL can go directly to rows where col equals 43 bypassing all other rows For a large table it can take minutes to check every row Using an index finding a specific row takes fractions of a second Internally POSTGRESQL stores data in operating system files Each table has 1ts own file Data rows are stored one after another in the file An index is a separate file that is sorted by one or more columns It contains pointers into the table file allowing rapid access to specific values in the table However POSTGRESQL does not create indexes automatically Users should create them for columns frequently used in WHERE clauses Indexes are created using the CREATE INDEX command as shown in figure 11 1 In this example test gt CREATE INDEX customer_custid_idx ON customer customer id CREATE Figure 11 1 Example of CREATE INDEX customer _custid idx is the name of the index customer is the table being indexed and customer id is the column being indexed You can use any na
160. col3 col4 REFERENCES primarytest2 MATCH FULL CREATE TABLE will create implicit trigger s for FOREIGN KEY check s UPDATE matchtest SET col3 NULL col4 NULL 1 UPDATE matchtest SET col4 NULL lt unnamed gt referential integrity violation MATCH FULL doesn t allow mixing of NULL and NON NULL key values Figure 14 13 MATCH FULL foreign key 135 136 CHAPTER 14 CONSTRAINTS 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 test gt CREATE TABLE defertest 10507 10508 test gt col2 INTEGER REFERENCES primary 10509 test test gt DEFERRABLE 10510 10511 test gt est gt 10512 NOTICE CREATE TABLE will create implicit trigger s for FOREIGN KEY check s 10513 CREATE 10514 10515 test gt BEGIN 10516 BEGIN 1931 test gt INSERT is attempted in non DEFERRABLE mode 10518 10519 test gt 10520 test gt INSERT INTO defertest VALUES 5 10521 ERROR lt unnamed gt referential integrity violation 10522 10523 key referenced from defertest not found in primarytest 10524 test gt COMMIT 10525 COMMIT 10929 10527 test gt BEGIN 10528 BEGIN 10529 test gt all foreign key constraints are set to DEFERRED ae test gt 10532 test gt SET CONSTRAINTS ALL DEFERRED 10533 10534 SET CONSTRAINTS 10535 test gt INSERT INTO defertest VALUES 5 10536 INSERT 148946 1 10537 test gt INSERT INTO primarytest VALUES 5 es INSER
161. column Because the column is the fourth column in the result you can identify the column by the number 4 Doing ORDER BY avg would have worked too You can GROUP BY more than one column as shown in figure 5 4 GROUP BY collects all NULL values into a single group Psql s da command lists all the aggregates supported by POSTGRESQL 5 3 Using HAVING There is one more aggregate capability that is often overlooked It is the HAVING clause HAVING allows you to perform conditional tests on aggregate values It is often used with GROUP BY With HAVING you can include or exclude groups based on the aggregate value for that group For example suppose you want to know all the states where there is more than one friend Looking at the first query in figure 5 3 you can see exactly which states have more than one friend HAVING allows you to programmatically test on the count 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 5 4 QUERY TIPS 43 Her test gt SELECT city state COUNT 4358 test gt FROM friend 4359 test gt GROUP BY state city 4360 4361 test gt ORDER BY 1 2 4362 city state count 4
162. command that is valuable when performance is critical and the indexed column has many duplicate values For example suppose column customerage has many duplicate values and the query SELECT FROM customer WHERE age 98 is executed An index on age allows rapid retrieval of the row locations from the index but if there are thousands of matching rows they may be scattered in the table file requiring many disk accesses to retrieve them CLUSTER reorders the table placing duplicate values next to each other This speeds access for large queries accessing many duplicate values 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 11 4 VACUUM 107 CLUSTER even helps with range queries like col gt 3 AND col lt 5 CLUSTER place
163. covered later have type less variables so they do not have this problem 17 7 ODBC ODBC Open Database Connectivity is an interface used by some applications and application building tools to access SQL databases ODBC is a middle ware layer that is not meant for programming directly but for communicating with other applications The ODBC source code is located in pgsql src interfaces odbc It can be compiled on UNIX and non UNIX operating systems 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 17 8 JAVA JDBC 161 17 8 JAVA JDBC Figure 17 8 shows a JAVA version of the same application
164. creation and removal is then destroyed and a connection made to a new database Additional information about each command can be found in the manual pages 20 4 Access Configuration POSTGRESQL allows administrators to control database access Access can be granted by database user or TCP IP network address By default POSTGRESQL allows database access only to users logged into the computer running the database server To enable network access the postmaster must be started with the 1 flag Database access is controlled by the data pg_hba conf file which is located in the POSTGRESQL home directory It contains several types of configuration entries 188 CHAPTER 20 ADMINISTRATION local Local entries control access by users logged into the same computer as the database server Local connections use unix domain sockets These are the per database authentication options e trust Trust users connecting to this database password Require a password of users connecting to this database e crypt Like password except send the password in an encrypted manner This method is more secure than password e reject Reject all connection requests for this database host and hostssl Host and hostssl entries control TCP IP network access They include host and netmask fields They support all the local options plus e indent Use a remote indent server for authentication e krb4 Use Kerberos IV authentication
165. ctof float test gt RETURNS float test gt AS users pgman sample ctof so test gt LANGUAGE C CREATE Figure 19 2 Create function ctof The SQL data type float is the same as the C type double used in ctof above The dynamically linkable object files is users pgman sample ctof so and it is written in the C language A single object file can contain many functions You must use CREATE FUNCTION to register each function you want to access from POSTGRESQL CREATE FUNCTION also allows non object files to be used as functions This is covered in chapter 18 With the functions registered they can be called just like POSTGRESQL internal functions Figure 19 3 shows the ctof function used in a SELECT statement See CREATE_FUNCTION for more information 1Some operating systems may need to use gmake rather than make Also some operating systems will use regress o rather than regress so 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611
166. customer id customer customer id Figure 8 13 NOT IN query rewritten using ALL and EXISTS In some cases subqueries simply allow an additional way to phrase a query In others a subquery is the only way to produce the desired result 8 3 Outer Joins An outer join is like a normal join except special handling is performed to prevent unjoined rows from being suppressed in the result For example in the join customercustomer_1d salesorder customer id only customers that have sales orders appear in the result If a customer has no sales orders he is suppressed from the output However if the salesorder table is used in an outer join the result will include all customers The customer and salesorder tables are joined and output plus one row for every unjoined customer is output In the query any reference to salesorders columns for these unjoined customers returns NULL As of POSTGRESQL 7 0 outer joins are not supported They can be simulated using subqueries and UNION ALL as shown in figure 8 14 The first SELECT performs a normal join of the customer and salesorder tables The second SELECT displays all customer who have no orders and displays NULL as their order number 8 4 Subqueries in Non SELECT Queries Subqueries can be used in UPDATE and DELETE statements also Figure 8 15 shows two examples The first query deletes all customers who have no sales orders The second query sets the ship date equal to 11 16 96 for all order
167. database It can be specified during POSTGRESQL initialization at database creation or inside psq1 POSTGRESQL can also be installed to support locales POSTGRESQL can read and display dates in a variety of formats The default date format can be specified as a postgres flag from inside psq using SET DATESTYLE or using the PGDATESTYLE environment variable 20 11 Upgrading The process of upgrading from previous POSTGRESQL releases is covered in the documentation distributed with each version Sometimes the pg_upgrade utility can be used In other cases a pg_dumpall and reload are required 20 12 Summary This chapter is only a summary of basic administrative tasks Each utility has many options not covered in this chapter Administration can be quite challenging It takes skill and experience Hopefully this chapter has supplied enough information for you to start exploring topics of interest The manual pages and Administrators Guide mentioned in appendix A 3 contain more valuable information 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 1425
168. date statename to be called every time a row is inserted or updated in statename The remaining queries in the figure show three rejected INSERTs and a successful INSERT that is properly uppercased and capitalized by the function Trigger functions can be quite complicated They can perform loops SQL queries and any operation supported in server side functions See the CREATE TRIGGER and DROP_ TRIGGER manual pages for additional information 18 5 Summary Server side functions allow programs to be embedded into the database These programs can be accessed from client applications and used in database queries Moving code into the server allows for increased efficiency maintainability and consistency Triggers are special server side functions called when a table is modified 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 1
169. de language except SQL These functions control the action taken by the query They can reject certain values or modify them before they are added to the database Triggers that return NULL cause the operation that caused the trigger to be ignored Server side trigger functions are special because they have predefined variables to access the row that caused the trigger For INSERT triggers the variable new represents the row being inserted For DELETE the variable old represents the row being deleted For UPDATE triggers can access the pre UPDATE row using old and the post UPDATE row using new These are the same as the old and new variables in rules Figure 18 13 shows the creation of a special server side trigger function called trigger insert update statename This function uses the new RECORD variable to e Reject a state code that is not exactly two alphabetic characters e Reject a state name that contains non alphabetic characters e Reject a state name less than three characters in length e Uppercase the state code e Capitalize the state name When invalid data is entered RAISE EXCEPTION aborts the current query and displays an appropriate error message Validity checks can also be performed using CHECK constraints covered in section 14 5 Uppercase and capitalization occur by simply assigning values to the new variable The function return type is opaque because new is returned by the function CREATE TRIGGER causes trigger insert up
170. dentified by the first few words The rest of the request has a specific format that is understood by the database server While capitalization and spacing are optional the format for a query must be followed Otherwise the database server will issue an error such as parser parse error at or near pencil meaning the database server got confused near the word pencil In such a case the manual page for the command should be consulted and the query reissued in the proper format A copy of the POSTGRESQL manual pages appear in appendix D The CREATE TABLE command follows a specific format First the two words CREATE TABLE then the table name then an open parenthesis then a list of column names and their types followed by a close parenthesis lIn a real world database the person s birth date would be stored and not the person s age Age has to be updated every time the person has a birthday A person s age can be computed when needed from a birth date field 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2
171. detail Create some tables yourself now Only use letters for your table and column names Don t use any numbers punctuation or spaces at this time The d command allows you to see information about a specific table or a list of all table names in the current database To see information about a specific table type d followed by the name of the table For example to see the column names and types of your new friend table in psql type d friend Figure 3 3 shows this If you use d with no table name after it you will see a list of all table names in the database test gt d friend Table friend Attribute Type Extra Tesse A ERES firstname char 15 lastname char 20 city char 15 state char 2 age int4 Figure 3 3 Example of backslash d 3 3 Adding Data with INSERT Let s continue toward the goal of making a table exactly like the friend table in table 3 1 We have the table created but there is no data friends in it You add data into a table with the INSERT command Just as CREATE TABLE has a specific format that must be followed INSERT has a specific format too You can see the format in figure 3 4 First you must use single quotes around the character strings Double quotes will not work Spacing and capitalization are optional except inside the single quotes Inside them the text is taken as literal so any capitalization will be stored in the database exactly as you specify If you type too many
172. dsheets are used for financial calculations and analysis Databases are used primarily for data storage and retrieval You can use a word processor or a spreadsheet to store small amounts of data However with large volumes of data or data that must be retrieved and updated frequently databases are the best choice Databases allow orderly data storage rapid data retrieval and complex data analysis as you will see in the coming chapters 1 2 UNIVERSITY OF CALIFORNIA AT BERKELEY POSTGRESQLS ancestor was INGRES developed at the UNIVERSITY OF CALIFORNIA AT BERKELEY 1977 1985 The INGRES code was taken and enhanced by RELATIONAL TECHNOLOGIES INGRES CORPORATION which produced one of the first commercially successful relational database servers Also at Berkeley MICHAEL STONEBRAKER led a team to develop an object relational database server called POSTGRES 1986 1994 The POSTGRES code was taken by ILLUSTRA and developed into a commercial product Two Berkeley graduate students JOLLY CHEN and ANDREW YU added SQL capabilities to POSTGRES and called it POSTGRES95 1994 1995 They left Berkeley but Chen continued maintaining POSTGRES95 which had an active mailing list 1 3 Development Leaves BERKELEY In the summer of 1996 it became clear that the demand for an open source SQL database server was great and a team was formed to continue development MARC G FOURNIER Toronto Canada offered to host the mailing list and provide a server to
173. e and use that customer id in joins with other tables Figure 6 14 shows a query using a customer code to find all order numbers for that customer test gt SELECT order_id test gt FROM customer salesorder test gt WHERE customer code FLEOO1 AND test gt customer customer_id salesorder customer_id Figure 6 14 Using a customer code In some cases identification numbers are fine and codes unnecessary Items with short lifespans i e order numbers e Items without appropriate codes i e payroll batch numbers e Items used internally and not referenced by users Defining codes for such values would be useless It is better to allow the database to assign a unique number to each item The next chapter covers database support for assigning unique identifiers There is no universal rule about when to choose codes or identification numbers U S states are clearly better keyed on codes because there are only 50 U S states The codes are short unique and well known by most users At the other extreme order numbers are best used without codes because there are too many of them and codes would be of little use 6 8 One to Many Joins Up to this point when two tables were joined one row in the first table matched exactly one row in the second table making the joins one to one joins Imagine if there were more than one salesorder row for a customer id Multiple order numbers would be printed That would be a one to many join wh
174. e Oa EG eRe ee He lar de Oe me De 141 0880 15 4 COPY Without TIES s sone ca a Be we eo Ge oa 141 a 15 5 Backslashes and NULES s scale Ge A aw a ww a OH We Bw ewe a we ln 142 0883 e IN Sa 143 nee WOE IN ore wa RARA A AAA RARA RARA E AAA oe AAA 143 0886 0887 16 Database Query Tools 145 0888 A E Nn 145 ao Oe Ek hen Ae te ick bn Bees A 150 0891 A rennen enn eren rek ee Res 152 0892 0893 0894 17 Programming Interfaces 153 0895 17 1 C Language Interface LIBPO o eca oan emee enen Re Rw e i 154 0896 17 2 Pgeasy LIBPGEASY o po bh we hoe RAKE RARER SRG REN OREO EKER ES 156 el 17 3 Embedded C BOPG lt san ee a a Beate a dos 156 0899 IZA BPS a a te arn ear a ae e Zande Biest de Bie le Gee oe rt ae de 156 0900 1745 Compiling Programs eenderde enk 156 pite 17 6 Assignment to Program Variables nonono a 160 0903 DIA a ER Re de ee ae Ned 160 E AO A EAN 161 0906 179 SOR LAS ss o he AR bek A ek RA 161 0907 a A Re en sek 161 a LEAL VOL TREPSTCESEIPGERSHN en a ee ee eee ge eh ee eS ar 161 0910 1 12 PYTHON PYGRBSQL an ads Bla ek da at TE eee A do 161 0911 A eenn resten bobs nen nee 10d e 17 12 Installing Sonpting Languages oo ce av eae eh ERE RSE SES EAD end 166 0914 A he en 6 ES ESS OWS EG SOR Oe tarda 166 dale 0916 0917 18 Functions and Triggers 167 0918 EE ee en 167 0919 182 SOLEUACUONS so en aan een aar a WET aia 167 ee 183 PLPGSOL FURGONES sea sae ad a WO we We ew ees bc Gee ae we we BS a 172 0922 IBA AI 178 09
175. e counter continues to increase The counter is used by all databases so object identification numbers are always unique No two rows in any table or in any database have the same object id You have seen object identification numbers already Object identification numbers are displayed after every INSERT statement If you look back at figure 3 4 on page 12 you will see the line INSERT 18720 1 INSERT is the command that was executed 18720 is the object identification number assigned to the inserted row and 1 is the number of rows inserted A similar line appears after every INSERT statement Figure 6 4 on page 49 shows sequential object identification numbers assigned by consecutive INSERT statements Normally a row s object identification number is displayed only by INSERT queries However if the OID is specified by a non INSERT query 1t will be displayed as shown in figure 7 1 The SELECT has accessed the normally invisible OID column The OID displayed by the INSERT and the OID displayed by the SELECT are the same Even though no OID column is mentioned in CREATE TABLE statements every POSTGRESQL table has an invisible column called om The column only appears if you specifically access it The query SELECT FROM table_name does not display the OID column SELECT OID FROM table_name will display it Object identification numbers can be used as primary and foreign key values in joins Since every row has a unique object id there is no
176. e customer employee and part numbers to link the salesorder row to the other rows we inserted For simplicity we will use only a single row per table The process of distributing data across multiple tables to prevent redundancy is called data normalization In the real world the name columns would be much longer perhaps char 60 or char 180 You should base the length on the longest name you may ever wish to store Iam using short names so they display properly in the examples 3A table can not be called order Order is a reserved keyword for use in the ORDER BY clause Reserved keywords are not available as table or column names Technically the column customercustomer_id is a primary key because it is the unique key for each customer row The column 48 test gt CREATE TABLE customer CHAPTER 6 JOINING TABLES test gt customer_id INTEGER test gt name CHAR 30 test gt telephone CHAR 20 test gt street CHAR 40 test gt city CHAR 25 test gt state CHAR 2 test gt zipcode CHAR 10 test gt country CHAR 20 test gt CREATE test gt CREATE TABLE employee test gt employee id INTEGER test gt name CHAR 30 test gt hire date DATE test gt CREATE test gt CREATE TABLE part test gt part id INTEGER test gt name CHAR 30 test gt cost NUMERIC 8 2 test gt weight FLOAT test gt CREATE test gt CREATE TABLE salesorder te
177. e is no restriction on age which is the first part of the index Indexes can be useful for columns involved in joins too An index can even be used to speed up some ORDER BY clauses Indexes are removed using the DROP INDEX command See the CREATE_INDEX and DROP_INDEX manual pages for more information 11 2 Unique Indexes Unique indexes are like ordinary indexes except they prevent duplicate values from occurring in the table For example figure 11 2 shows the creation of a table and a unique index The index is unique because the test gt CREATE TABLE duptest channel INTEGER CREATE test gt CREATE UNIQUE INDEX duptest_channel_idx ON duptest channel CREATE test gt INSERT INTO duptest VALUES 1 INSERT 130220 1 test gt INSERT INTO duptest VALUES 1 ERROR Cannot insert a duplicate key into unique index duptest_channel_idx Figure 11 2 Example of a unique index keyword UNIQUE was used The remaining queries try to insert a duplicate value The unique index prevents this and displays an appropriate error message Sometimes unique indexes are created only to prevent duplicate values and not for performance reasons Multi column unique indexes ensure the combination of indexed columns remains unique Unique indexes do allow multiple NULL values Unique indexes speed data access and prevent duplicates 11 3 Cluster The CLUSTER command reorders the table file to match the ordering of an index This is a specialized
178. e krb5 Use Kerberos V authentication These entries are only effective if the postmaster is using the i option Hostssl controls access via the Secure Socket Layer SSL if enabled in the server Examples Local entries are configured per database A database entry of all applies to all databases In data pg_hba conf the lines local all trust host all 127 0 0 1 255 255 255 255 trust cause all local users to be trusted The first line affects users connecting via unix domain sockets while the second line controls local users connecting to their same machine by TCP IP The local machine is accessed as TCP IP address 127 0 0 1 localhost Host and hostssl entries require the additional specification of host addresses and network masks The lines host all 192 168 34 0 255 255 255 255 crypt host all 192 168 90 0 255 255 255 0 password force passwords of all users from host 192 168 34 0 and network 192 168 90 0 Crypt encrypts passwords when sent while password sends passwords over the network without encryption Password should only be used for database clients that do not support crypt authentication The line host sales 192 168 7 12 255 255 255 255 ident 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966
179. e main body of the book into appendices Appendix A shows how to find additional information about POSTGRESQL Appendix B has information about installing POSTGRESQL Appendix C lists the features of POSTGRESQL not found in other database systems Appendix D contains a copy of the POSTGRESQL reference manual which should be consulted anytime you are having trouble with query syntax Also I should mention the excellent documentation that is part of POSTGRESQL The documentation covers many complex topics It includes much POSTGRESQL specific functionality that cannot be covered in a book of this length I refer to sections of the documentation in this text where appropriate The website for this book is located at http www postgresql org docs awbook html vil viil PREFACE 0463 0464 0465 0466 0467 0468 0469 0470 0471 0472 0473 0474 0475 0476 0477 0478 0479 0480 0481 0482 0483 0484 0485 0486 0487 0488 0489 0490 0491 0492 0493 0494 0495 0496 0497 0498 0499 0500 0501 0502 0503 0504 0505 0506 0507 0508 0509 0510 0511 0512 0513 0514 0515 0516 0517 0518 0519 0520 0521 0522 0523 0524 0525 0526 0527 0528 0529 0530 0531 0532 0533 0534 0535 0536 0537 0538 0539 0540 0541 0542 0543 0544 0545 0546 0547 0548 0549 0550 0551 0552 0553 0554 0555 0556 0557 0558 0559 0560 0561 0562 0563 0564 0565 0566 0567 0568 0569 0570 0571 0572 0573 0574 0575 0576 0577
180. e this is a contrived example real world database users INSERT UPDATE and DELETE data all at the same time while others SELECT data All this activity is orchestrated by the database so each user can operate in a secure manner knowing other users will not affect their results in an unpredictable way 10 4 Read Committed and Serializable Isolation Levels The previous section illustrated that users only see committed transactions This does not address what happens if someone commits a transaction while you are in your own transaction There are cases where you need to control if other transaction commits are seen by your transaction POSTGRESQL s default isolation level READ COMMITTED allows you to see other transaction commits while your transaction is open Figure 10 6 illustrates this effect First the transaction does a SELECT test gt BEGIN WORK BEGIN test gt SELECT COUNT FROM trans_test count test gt test gt someone commits INSERT INTO trans test test gt test gt SELECT COUNT FROM trans_test test gt COMMIT WORK COMMIT Figure 10 6 Read committed isolation level COUNT Then while sitting at a psql prompt someone INSERTS into the table The next SELECT COUNT 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8
181. e user exits the editor the editor contents are reloaded into the query buffer ready for execution The environment variable EDITOR specifies the default editor General Commands A list of general psql commands is shown in table 16 2 Psql has a local copy interface that allows copy operations using files local to the computer running psql rather than local to the computer running the database server Later sections cover the use of lset lunset and pset 145 146 CHAPTER 16 DATABASE QUERY TOOLS Operation Command Connect to another database connect dbname Copy tablefile to from database copy tablename to from filename Set a variable set variable or set variable value Unset a variable unset variable Set output format pset option or pset option value Echo echo string or lecho command Echo to o output gecho string or gecho command Copyright copyright Change character encoding encoding newencoding Table 16 2 psql general commands Output Format Options The pset command controls the output format used by psq1 Table 16 3 shows all the formatting commands and figure 16 1 shows examples of their use In the figure pset tuples only causes psql to show only data Format Parameter Options Field alignment format unaligned aligned html or latex Field separator fieldsep separator One field per line expanded Rows only tuples_only Row separator recordsep separator Table title title title Table bo
182. eager Plymouth Gleason Ocean City Millstone Cedar Creek Gleason Ocean City Weber Boston Tabor Williamsport Victor 6 rows test gt SELECT COUNT count test gt SELECT SUM age sum 150 1 row test gt SELECT MAX age max 33 1 row test gt SELECT MIN age min 19 1 row test gt SELECT AVG age avg 25 1 row FROM friend FROM friend FROM friend FROM friend FROM friend CHAPTER 5 SQL AGGREGATES state age MA 24 NJ 19 MD 27 NJ 25 MA 33 PA 22 Figure 5 1 Aggregate examples 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 5 1 AGGREGATES test gt CREATE TABLE aggtest col INTEGER CREATE test gt INSERT INT
183. ealtable VALUES 1 407891 1 INSERT INTO view realtable VALUES 2 407893 1 SELECT FROM realtable SELECT FROM view_realtable Figure 13 12 Views ignore table modifications 124 CHAPTER 13 TABLE MANAGEMENT test gt CREATE RULE view_realtable_insert AS INSERT rule test gt ON INSERT TO view_realtable test gt DO INSTEAD test gt INSERT INTO realtable test gt VALUES new col CREATE 407894 1 test gt test gt CREATE RULE view realtable update AS UPDATE rule test gt ON UPDATE TO view_realtable test gt DO INSTEAD test gt UPDATE realtable test gt SET col new col test gt WHERE col old col CREATE 407901 1 test gt test gt CREATE RULE view realtable delete AS DELETE rule test gt ON DELETE TO view_realtable test gt DO INSTEAD test gt DELETE FROM realtable test gt WHERE col old col CREATE 407902 1 Figure 13 13 Rules to handle view modifications Creating a rule whose action performs the same command on the same table causes an infinite loop POSTGRESQL will call the rule again and again from the rule action For example if an UPDATE rule on ruletest has a rule action that also performs an UPDATE on ruletest an infinite loop is created POSTGRESQL will detect the infinite loop and return an error Fortunately POSTGRESQL also supports triggers Triggers allow actions to be performed when a table is modified They can perform actions that can not be implemented usi
184. eee Od Ee ewe oe eS 120 13 9 Rule fiat preyentS INSERT 24 424 04 004 8G 4s os BRGY REECE RE es 121 13 lO Rules to log table Changes ran ae ae aes ae eae ae B ee ee nk Hed 122 Is Wee of tule to log table Changes ran von Soak ew SE Oe ak BOR Ard ge ow Beek ip 123 XX LIST OF FIGURES 13 12Views ignore table modifications 1 eee 123 13 18 Rules to handle view modifications 26 404 see ben eee cerrara a oun 124 13 4 Rules handle view modifications ze av Gas Ghee rara RA 125 141 NOT NULLOODS HADE nn ese ii AA oe ee eS oes Se wee PSS ws 127 14 2 NOT NULL With DEFAULT constraint oo kek he eR RS AEA GY A 128 14 3 Umane EMMA COASTAL oee deer ede te tee ee bed Cae oe oak Oe eS 128 14 4 Mult column que constraint ica iia AAA 129 14 5 Creation Of PRIMARY REY COMI o oe acadara rr RARA 129 14 6 Example of a multicolumn primary Key o ess s edad tuk ak maas hed 130 14 7 Foran key eredo s oe ee a ARA AAA A EA 130 14 8 Foreign key constraints ceca da dd 131 14 9 Creation of company tables using primary and foreign keys o 131 14 10Customer table with foreign key actions o lt lt lt lt lt 2 132 AMI 133 14 12Esample of a multicolumn foreign key o aa are eens an ek ae eG ae 134 14 ASMATOR FULL foreign Key sane nek ne EDR a 135 14 JADEFERRABLE foreign key constraint asana asana enke es 136 E e CORUS eenma eee ewe PEE a we EES SOO SESE SES REESE 137 15 1 Example of Copy TO amd COPY
185. efinite advantages to having different data types Consistent Results Columns of a uniform type produce consistent results Displaying sorting aggregates and joins deliver consistent results There is no conflict about how different types are compared or displayed Selecting from an INTEGER column always yields INTEGER values Data Validation Columns of a uniform type accept only properly formated data Invalid data is rejected A column of type INTEGER will reject a DATE value Compact Storage Columns of a uniform type are stored more compactly Performance Columns of a uniform type are processed more quickly For these reasons each column in a relational database can hold only one type of data Data types cannot be mixed within a column This limitation can cause some difficulties For example in our friend table there is an age column of type INTEGER Only whole numbers can be placed in that column The values 7 will ask for his age soon or She will not tell me her age cannot be placed in that column NULL can represent 7 don t know her age The solution is to create an age_comments column of type CHARO to hold comments which cannot be placed in the age field 9 2 Installed Types POSTGRESQL supports a large number of data types as shown in table 9 1 Except for the number types all entered values must be surrounded by single quotes 87 88 Category Character string Number Temporal Logical Geometri
186. ences These are important in multi table queries Then we cover the advantages of splitting data across multiple tables Next we introduce an example based on a mail order company showing table creation insertion and queries using joins Finally we explore various join types 6 1 Table and Column References Before dealing with joins there is one important feature that must be mentioned Up to this point all queries have involved a single table With multiple tables in a query column names get confusing Unless you are familiar with each table it is difficult to know which column names belong to which tables Sometimes two tables have the same column name For these reasons SQL allows you to fully qualify column names by preceding the column name with the table name An example of table name prefixing is shown in figure 6 1 The first query has unqualified column names The second is the same query but with fully qualified column names A period separates the table name from the column name The final query shows another feature Instead of specifying the table name you can create a table alias to take the place of the table name in the query The alias name follows the table name in the FROM clause In this example f is used as an alias for the friend table While these features are not important in single table queries they are useful in multi table queries 6 2 Joined Tables In our friend example splitting data into multiple tables
187. er test gt ALTER TABLE alterdemo ALTER COLUMN col2 SET DEFAULT 0 ALTER test gt show new default value test gt d alterdemo Table alterdemo Attribute Type Modifier aaa E AAA EA democol integer col2 integer default 0 test gt ALTER TABLE alterdemo ALTER COLUMN col2 DROP DEFAULT ALTER Figure 13 3 ALTER TABLE examples 13 3 GRANT and REVOKE When a table is created only the owner can access it If the owner wants others to have access the table s permissions must be changed using the GRANT command Figure 13 4 shows some examples of GRANT Available privileges are SELECT UPDATE DELETE RULE and ALL Rules are covered later in section 13 6 REVOKE removes permissions from a table See the GRANT and REVOKE manual pages for more informa tion 118 CHAPTER 13 TABLE MANAGEMENT test gt CREATE TABLE permtest col INTEGER CREATE test gt now only the owner can use permtest test gt test gt GRANT SELECT ON permtest TO meyers CHANGE test gt now user meyers can do SELECTs on permtest test gt test gt GRANT ALL ON permtest TO PUBLIC CHANGE test gt now all users can perform all operations on permtest test gt Figure 13 4 Examples of the GRANT command 13 4 Inheritance Inheritance allows the creation of a new table related to an existing table Figure 13 5 shows the creation of an inherited table Using inheritance the child table gets all the columns of the paren
188. er applications htm They are in sgml Docbook format Approximately 14675 200 pages 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 199 200 APPENDIX D REFERENCE MANUAL 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 Bibliography Bowman Bowman et al The Practical SQL Handbook Addison Wesley Date Standard Date C J A Guide to The SQL S
189. er interfaces use 1bpq internally for database access Figure 17 3 shows how libpq is used The application code communicates with the user s terminal and User Terminal PostgreSQL Application Database Code Server Libpq Queries lt Results Figure 17 3 Libpq data flow uses libpq for database access Libpq sends queries to the database server and and retrieves results Figure 17 4 shows the sample program using libpq to access POSTGRESQL These are the tasks performed by the sample program e Establish database connection e Prompt for and read the state code e Form an appropriate SQL query e Pass the SQL query to libpq e POSTGRESQL executes the query e Retrieve the query results from libpq 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 17 1 CLANGUAGE INTERFACE LIBPQ 155 11749 4 i 11750 libpq sample program 11751 el 11752 11753 include lt stdio h gt ee include lt stdlib h gt 11756 include libpq fe h libpq header file 11757 11758 int 11759 main
190. erators characters Note that the caret has a different meaning outside and inside square brackets While Test Special Characters start end any single character set of characters ccc set of characters not equal ecc range of characters c c range of characters not equal c c zero or one of previous character zero or multiple of previous characters ss one or multiple of previous characters OR operator Table 4 5 Regular expression special characters regular expressions are powerful they are complex to create Table 4 6 shows some examples Figure 4 17 shows examples of queries using regular expressions For a description see the comment above each query Figure 4 18 shows two more complex regular expressions The first query shows the way to properly test for a trailing n Because char columns have trailing space to fill the column you need to test for possible trailing spaces See section 9 2 for complete coverage on character data types The second query might be surprising Some think it returns rows that do not contain an S Instead the query returns all rows that have any character that is not an S Sandy contains characters that are not S such as a n d and y so that row is returned The test would only prevent rows containing only S s from being printed You can test for the literal characters listed in table 4 5 For example to test for a dollar sign use To test for an asterisk use
191. ere one customer row joins to more than one salesorder row Suppose there were no orders made by a customer Even though there was a valid customer row if there were no salesorder row for that customer identification number no rows would be returned We could call that a one to none join Figure 6 15 shows an example Because the animal table s 507 rabbit row join to three rows in the SMany database servers support a special type of join called an outer join that allows non joined data to appear in the query Unfortunately POSTGRESQL does not support outer joins at this time 56 test gt SELECT FROM animal animal_id name PEE pa AA 507 rabbit 508 cat 2 rows test gt SELECT FROM vegetable animal_id name ls Tp Da ene 507 lettuce 507 carrot 507 nuts 3 rows test gt SELECT test gt FROM animal vegetable test gt WHERE animal animal_id vegetable animal_id animal id name animal id name Sets NE isa EEEN MAESEN ooh han A 507 rabbit 507 lettuce 507 rabbit 507 carrot 507 rabbit 507 nuts 3 rows Figure 6 15 One to many join CHAPTER 6 JOINING TABLES 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 9253 5254 9255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268
192. erver model of communication That means that a POSTGRESQL server continually runs waiting for client requests The server processes the request and returns the result to the client Choosing an Interface Because the POSTGRESQL server runs as an independent process on the computer there is no way for a user to interact with it directly Instead there are client applications designed specifically for user interaction This chapter shows you how to interact with POSTGRESQL using the psql interface Additional interfaces are covered in Chapter 17 Choosing a Database Each POSTGRESQL server controls access to a number of databases Databases are storage areas used by the server to partition information For example a typical installation may have a production database used to keep all information about a company They may also have a training database used for training and testing purposes They may have private databases used by individuals to store personal information For this exercise we will assume you have created an empty database called test If this is not the case see section B 6 CHAPTER 2 ISSUING DATABASE COMMANDS Starting a Session To start a psql session and connect to the test database type psql test at the command prompt Your output should look similar to figure 2 1 Remember the operating system command prompt is case sensitive so you must type this in all lowercase psql test Welcome to psql the PostgreSQL i
193. ery 10 2 Multi Statement Transactions By default each SQL query runs in its own transaction Figures 10 1 and 10 2 show two identical queries test gt INSERT INTO trans_test VALUES 1 INSERT 130057 1 Figure 10 1 INSERT with no explicit transaction Figure 10 1 shows a typical INSERT query Before POSTGRESQL starts the INSERT it begins a transaction It performs the INSERT then commits the transaction This is done automatically for any query with no explicit 97 98 CHAPTER 10 TRANSACTIONS AND LOCKS test gt BEGIN WORK BEGIN test gt INSERT INTO trans test VALUES 1 INSERT 130058 1 test gt COMMIT WORK COMMIT Figure 10 2 INSERT with explicit transaction transaction Figure 10 2 shows an INSERT using an explicit transaction BEGIN WORK starts the transaction and COMMIT WORK commits the transaction The only difference between the two queries is that there is an implied BEGIN WORK COMMIT WORK surrounding the INSERT Even more valuable is the ability to bind multiple queries into a single transaction When this is done either all the queries execute to completion or none of them have any effect For example figure 10 3 shows two INSERTs in a transaction PostgreSQL guarantees either both INSERTs succeed or none of them test gt BEGIN WORK BEGIN test gt INSERT INTO trans test VALUES 1 INSERT 130059 1 test gt INSERT INTO trans test VALUES 2 INSERT 130060 1 test gt COMMIT WORK COMMI
194. es in user data Figure 15 6 shows an example of this Each column is separated by a pipe but test gt DELETE FROM copytest DELETE 3 test gt INSERT INTO copytest test gt VALUES 4 837 20 abc def NULL INSERT 174786 1 test gt COPY copytest TO stdout USING DELIMITERS 4 837 20 abc def N Figure 15 6 Copy backslash handling the pipe that appears in user data is output as abc def Backslash causes any character that follows it to be treated specially Because of this a backslash in user data must be output as two backslashes Another special backslash in this figure the use of N to represent NULL This prevents NULLs from being confused with user values The default NULL representation can be changed using WITH NULL AS The command COPY copytest TO Amp copytest out WITH NULL AS will output NULLs as a question marks However this will make a user column containing a single question mark indistinguishable from a NULL in the file To output NULLs as blank columns use the command COPY copytest TO tmp copytest out WITH NULL AS To treat empty columns as NULLs on input use COPY copytest FROM tmp copytest out WITH NULL AS Table 15 1 summarizes the delimiter NULL and backslash handling of COPY The first two lines in the table show that preceeding a character with a backslash prevents the character from being interpreted as a delimiter The next line shows that N means NUL
195. es of aggregate queries Aggregates can be combined with the WHERE clause to produce more complex results The query SELECT AVG age FROM friend WHERE age gt 21 computes the average age of people age 21 or older This prevents Dick Gleason from being included in the average computation because he is younger than 21 The column label defaults to the name of the aggregate You can use AS to change it as shown in section 4 5 NULLs are not processed by most aggregates like MAX SUMO and AVGO If a column is NULL it is skipped and the result is not affected by any NULL values However if a column contains only NULL values the result is NULL not zero COUNT is different It does count NULLs because it is looking at entire rows by using the asterisk It is not looking at individual columns like the other aggregates To find the COUNT of all non NULL values in a certain column use COUNT columnname Figure 5 2 illustrates aggregate handling of NULLs First a single row containing a NULL column is used to show aggregates returning NULL results Two versions of COUNT on a NULL column are shown Notice COUNT never returns a NULL value Then a single non NULL row is inserted and the results shown Notice the AVG of 3 and NULL is 3 not 1 5 illustrating the NULL is not involved in the average computation 39 40 test gt SELECT FROM friend ORDER BY firstname firstname Sandy lastname city i EE EE ts Poo oe E oS E Y
196. est 189 TE 20 4 Postmaster and postgres processes coras u kie ko tavata 190 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 xxii LIST OF FIGURES 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 List of Tables a l 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 5 1 del ZI 9 2 9 3 9 4 9 5 10 1 10 2 10 3 10 4 13 1 15 1 16 1 16 2 16 3 16 4 16 5 16 6 16 7 16 8 17 4 AA A NER 8 10 Common data types gt nan aa ae rl ar A A A a eae 19 COI ee oee aon R
197. est gt WHERE order_id 14673 test gt name Fleer Gearworks Inc 1 row Figure 8 8 Subqueries can replace some joins the customer _id from a subquery In general if a table is involved in only one join and no columns from the table appear in the query result the join can be eliminated and the table moved to a subquery In this example we have specified salesorder customer_id and customer customer_id to clearly indicate the tables being referenced However this is not required We could have used only customer_1d in both places POSTGRESQL finds the first table in the same subquery or higher that contains a matching column name Subqueries can be used anywhere a computed value is needed A subquery has its own FROM and WHERE clauses It can have its own aggregates GROUP BY and HAVING Its only interaction with the upper query is the value it returns This allows sophisticated comparisons that would be difficult if the subquery s clauses had to be combined with those of the upper query Subqueries as Correlated Values While subqueries can act as constants in queries subqueries can also act as correlated values Correlated values vary based on the row being processed A normal subquery is evaluated once and its value used by the upper query In a correlated subquery the subquery is evaluated repeatedly for every row processed For example suppose you want to know the name of your oldest friend in each state You can do this
198. excluded from the output because it is returned by the second query While UNION adds rows to the first SELECT EXCEPT subtracts rows from the first SELECT INTERSECT returns only rows generated by all SELECTs Figure 8 6 uses INTERSECT and displays only penguin While several animals are returned by the two SELECTs only penguin is returned by both SELECTs Any number of SELECTs can be linked using these methods The previous examples allowed multiple 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 8 1 UNION EXCEPT INTERSECT CLAUSES test gt INSERT INTO aquatic_animal name VALUES penguin INSERT 19124 1 test gt INSERT INTO terrestrial_animal name VALUES penguin INSERT 19125 1 test gt SELECT name test g
199. fault value is used when an INSERT does not supply a value for the column In this example defaults allow auto assignment of these values on INSERT to service request and on rule INSERTs to service request log Figure 13 11 shows these rules in use A row is inserted updated and deleted from service request A SELECT on service request log shows the UPDATE rule recorded the pre UPDATE values a U in mod type and the user date and time of the UPDATE The DELETE appears similarly While views ignore INSERT UPDATE and DELETE rules can be used to properly handle them Figure 13 12 shows the creation of a table and view on the table The figure also illustrates views ignore INSERTs UPDATES and DELETEs are similarly ignored Figure 13 13 shows the creation of DO INSTEAD rules to properly handle INSERT UPDATE and DELETE This is done by changing INSERT UPDATE and DELETE queries on the view to queries on realtable Notice new is used by the INSERT rule to reference the new value to be inserted In UPDATE and DELETE old is used to reference old values Figure 13 14 shows the view now properly handles modifications It would be wise to add an index on col because the rules do lookups on that column SELECT rules can also be created Views are implemented internally as SELECT rules Rules can even be applied to only certain rows Rules are removed with the DROP RULE command See the CREATE _RULE and DROP _RULE manual pages for more information 122
200. ferent 38 CHAPTER 4 CUSTOMIZING QUERIES 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 Chapter 5 SQL Aggregates Users often require the ability to summarize database information Instead of seeing all rows they want just a count or total This is called aggregation or gathering together This chapter deals with POSTGRESQL s ability to generate summarized database information using aggregates 5 1 Aggregates There are five aggregates outlined in table 5 1 COUNT operates on entire rows The others operate on Aggregate Function COUNT count of rows SUM colname total MAX colname maximum MIN colname minimum AVG colname average Table 5 1 Aggregates specific columns Figure 5 1 shows exampl
201. ficient as a POSTGRESQL backup If the databases are active the pg_dumpal1 utility must be used for reliable backup Pg _dumpal1 outputs a consistent snapshot of all databases into a file that can be included in a file system backup In fact once a pg_dumpa11 file has been created there is no need to backup the data base database files There are a few configurations files in data like data pg hba conf which should be included in a file system backup because they are not in the pg_dumpa1 file Pg_dump can dump a single POSTGRESQL database To restore using a pg_dumpall file POSTGRESQL must be initialized any configuration files restored to data and the database dump file run by psql1 This will recreate and reload all databases Individual databases can be reloaded from pg_dump files by creating a new database and loading it using psql For example figure 20 3 creates an exact copy of the test database It dumps the contents of the pg_dump test gt tmp test dump createdb newtest CREATE DATABASE psql newtest lt tmp test dump Figure 20 3 Making a new copy of database test database into a file A new database called newtest is created then the dump file is loaded into the new database Dump files contain ordinary SQL queries and COPY commands Because the files contain database information they should be created so only authorized users have permission to read them See pg_dump and pg_dumpal 1 manual pages for more informati
202. find all rows that end with g See section 9 2 for complete coverage on character data types 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 4 10 REGULAR EXPRESSIONS 29 4 10 Regular Expressions Regular expressions allow more powerful comparisons than the more standard LIKE and NOT LIKE Regular expression comparisons are a unique feature of POSTGRESQL They are very common in UNIX such as in the UNIX grep command Table 4 4 shows the regular expression operators and table 4 5 shows the regular expression special Comparison Operator regular expression 7 regular expression case insensitive Tk not equal to regular expression 17 not equal to regular expression case insensitive 19 Table 4 4 Regular expression op
203. gle step mode Single line mode Suppress readi Set variable ng psqlrc 151 Argument Additional argument database hosiname port user separator separator tags option or option value e C query f file 0 file S S X V var or var value Table 16 8 psql command line arguments Database Obj PostgreSQL access ect Help Tables Queries Views Sequences Functions Reports Forms Scripts Users Schema New Open Design account jaggtest alltypes lalterdemo larray_test ichild_test icopytest customer defertest duptest lemployee fforeigntest foreigntest2 friend friend2 fruit igrandchild_test matchtest localhost test Figure 16 3 Pgaccess opening window 152 CHAPTER 16 DATABASE QUERY TOOLS Filter conditions Reload Close firstname lastname city state a Nichols Tampa 20 Middleton Indianapolis Burger 2 Figure 16 4 Pgaccess table window 16 3 Summary This chapter covered psql and pgaccess These are the most popular POSTGRESQL query tools 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600
204. gt COPY copytest FROM tmp copytest out COPY test gt SELECT FROM copytest intcol numcol textcol boolcol t 1 23 99 fresh spring water t 2 55 23 bottled soda t 2 rows Figure 15 1 Example of COPY TO and COPY FROM test gt q cat tmp copytest out 1 23 99 fresh spring water t 2 55 23 bottled soda t sed s lt TAB gt g tmp copytest out the gap between is a TAB 1 lt TAB gt 23 99 lt TAB gt fresh spring water lt TAB gt t 2 lt TAB gt 55 23 lt TAB gt bottled soda lt TAB gt t Figure 15 2 Example of COPY FROM 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 108
205. h Sandy Gleason Ocean City Victor Tabor Williamsport 3 rows test gt SELECT test gt FROM friend test gt WHERE age BETWEEN 22 AND 25 test gt ORDER BY firstname firstname lastname city fs Sa nar o E PEIA AN AS EEE Dean Yeager Plymouth Sandy Gleason Ocean City Victor Tabor Williamsport 3 rows state age Sas A A MA 24 NJ 25 PA 22 state age T Pozos MA 24 NJ 25 PA 22 Figure 4 15 Selecting a range of values 27 28 CHAPTER 4 CUSTOMIZING QUERIES lt and gt so the age comparisons included the limiting ages of 22 and 25 If we used lt and gt the ages 22 and 25 would not have been included in the output The second query uses BETWEEN to generate the same comparison BETWEEN comparisons include the limiting values in the result 4 9 LIKE Comparison Greater than and less than comparisons are possible as shown in table 4 2 Even more complex comparisons are available Users often need to compare character strings to see if they match a certain pattern For example sometimes they only want fields that begin with a certain letter or contain a certain word The LIKE keyword allows such comparisons The query in figure 4 16 returns rows where the firstname begins with D The percent is interpreted to mean any characters can follow the D The query performs the test test gt SELECT FROM friend test gt WHERE firstname LIKE D test gt ORDER BY firstname f
206. he file are separated by TABs These TABs are called delimiters because they delimit or separate columns However TABs are hard to see They look like multiple spaces The next command processes the file using sed to display TABs as lt TAB gt This clearly shows the TABs in the file Notice TABs are different from spaces The columns do not line up as they do in psql This is because the columns are of different lengths The value of textcol in the first line is longer than value in the the second line The lack of alignment is expected INon UNIX operating system users would use the type command Sed is an operating system command that replaces one string with another See the sed 1 manual page for more information 139 140 CHAPTER 15 IMPORTING AND EXPORTING DATA test gt CREATE TABLE copytest test gt intcol INTEGER test gt numcol NUMERIC 16 2 test gt textcol TEXT test gt boolcol BOOLEAN test gt CREATE test gt INSERT INTO copytest test gt VALUES 1 23 99 fresh spring water t INSERT 174656 1 test gt INSERT INTO copytest test gt VALUES 2 55 23 bottled soda t INSERT 174657 1 test gt SELECT FROM copytest intcol numcol textcol boolcol 1 23 99 fresh spring water t 2 55 23 bottled soda t 2 rows test gt COPY copytest TO tmp copytest out COPY test gt DELETE FROM copytest DELETE 2 test
207. his contains include files used by various programming languages lib This contains libraries used by various programming languages It also contains files used during initialization and sample configuration files that can be copied to data and modified 20 2 Creating Users New users are created by running createuser from an operating system prompt Initially only the POST GRESQL super user typically postgres can create new users Other users can be given permission to create new users and databases POSTGRESQL usernames do not have to exist as operating system users For installations using database password authentication a createuser flag is available so passwords can be assigned Users are removed with dropuser CREATE USER ALTER USER and DROP USER commands are available in SQL POSTGRESQL also allows the creation of groups using CREATE GROUP in SQL GRANT permissions can be specified using these groups Figure 20 1 shows examples of user administration commands It creates one user from the command line a second user in psql and alters a user It then creates a group and gives table permissions to the 185 186 CHAPTER 20 ADMINISTRATION 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 createuser demouserl 13808 Shall the new user be allowed to create databases y n n 13999 13810 Shall the new user be allowed to create more new users y n n 13811 CREATE USER 13812 13813
208. host the source tree One thousand mailing list subscribers were moved to the new list A server was configured giving a few people login accounts to apply patches to the source code using cvs Ingres Corp was later purchased by Computer Associates Tlustra was later purchased by Informix and integrated into Informix s Universal Server cvs sychronizes access by developers to shared program files 1 2 CHAPTER 1 HISTORY OF POSTGRESQL JOLLY CHEN had stated This project needs a few people with lots of time not many people with a little time With 250 000 lines of C code we understood what he meant In the early days there were four major people involved MARC FOURNIER THOMAS LOCKHART in Pasadena California VADIM MIKHEEV in Krasnoyarsk Russia and myself in Philadelphia Pennsylvania We all had full time jobs so we were doing this in our spare time It certainly was a challenge Our first goal was to scour the old mailing list evaluating patches that had been posted to fix various problems The system was quite fragile then and not easily understood During the first six months of development there was fear that a patch would break the system and we would be unable to correct the problem Many bug reports had us scratching our heads trying to figure out not only what was wrong but how the system even performed many functions We inherited a huge installed base A typical bug report was When I do this it crashes the data
209. hows these comment styles Notice how the multi line comment is marked by a psql command prompt of gt It is a reminder you are in a multi line comment just as gt is a reminder you are in a multi line statement and gt is a reminder you are in a multi line quoted string test gt a single line comment test gt a multi line test gt comment Figure 4 9 Comment styles 4 7 AND OR Usage Up to this point there have been only simple WHERE clause tests In the next few sections we will show how to do more complex WHERE clause testing Complex WHERE clause tests are done by connecting simple tests using the words AND and OR For illustration I have inserted new people into the friend table as shown in figure 4 10 Selecting certain test gt SELECT FROM friend ORDER BY firstname firstname lastname city state age Dean Yeager Plymouth MA 24 Dick Gleason Ocean City INJ 19 Ned Millstone Cedar Creek MD 27 Sandy Gleason Ocean City INJ 25 Sandy Weber Boston MA 33 Victor Tabor Williamsport PA 22 6 rows Figure 4 10 New friends rows from the table will require more complex WHERE conditions For example if we wanted to select Sandy Gleason by name it would be difficult with only one comparison in the WHERE clause If we tested for firstname Sandy we would select both Sandy Gleason and Sandy Weber If we tested for lastn
210. ies yield the same result only if each customer row joins to exactly one statename row If there were customer rows that did not join to any statename row or joined to many statename rows the results would be different Also because the second query executes the SQL function for every row in customer it is slower 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12300 12801 12802 12803 12804 18 2 SQL FUNCTIONS 171 12805 12806 12807 12808 test gt CREATE FUNCTION getstatename text 12809 12810 test gt RETURNS text 12811 test gt AS SELECT CAST name AS TEXT 12812 test gt FROM statename 12813 12814 test gt WHERE code 1 12815 test gt LANGUAGE sql 12816 CREATE 12817 PE 12818 test gt SELECT getstatename AL 12819 getstatename 12820 12821 12822 Alabama 12823 1 row 12824 12825 12826 12827 Figure 18 5 SQL function getstatename 12828 12829 12830 12831 12832 12833 12834 12835 12836 test gt SELECT customer name statename name o test gt FROM customer statename 12839 test gt WHERE customer state
211. ility to type at an operating system prompt The book starts with a short history of POSTGRESQL It leads the reader through their first query and teaches the most important database commands Common problems are covered early like placing quotes inside quoted strings This should prevent users from getting stuck with queries that fail I have seen many bug reports in the past few years and try to cover the common pitfalls With a firm foundation established additional commands are introduced Finally specialty chapters outline complex topics like multi user control and performance While coverage of these complex topics is not exhaustive I try to show common real world problems and their solutions At each step the purpose of each command is clearly illustrated I want readers to understand more than query syntax I want them to know why each command is valuable so they will use the proper commands in their real world database applications A novice should read the entire book while skimming over the later chapters The complex nature of database systems should not prevent readers from getting started Test databases are a safe way to try queries As readers gain more experience later chapters will start to make sense Experienced database users can skip the chapters on basic SQL functionality The cross referencing of sections should allow you to quickly move from general to more specific information Much information has been moved out of th
212. into a format that is understood by the CPU inside the computer This process is usually performed by a compiler often called cc or gcc Several distribution formats automatically perform these steps for the user Installation This process involves copying all compiled programs into a directory that will serve as the home of all POSTGRESQL activity It will also contain all POSTGRESQL programs databases and log files The directory is typically usr local pgsql 195 196 APPENDIX B INSTALLATION Initialization Initialization creates a database called templatel in the POSTGRESQL home directory This database is uses to create all other databases Initdb performs this initialization step Starting the Server Once templatel is created the database server can be started This is typically done by running the program called postmaster Creating a Database Once the database server is running databases can be created by running createdb from the operating system prompt Chapter 20 covers POSTGRESQL administration in detail 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515
213. ion of the company tables from figure 6 3 page 48 using primary and foreign keys There are a variety of foreign key options listed below that make foreign keys even more powerful 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 14 4 FOREIGN KEY REFERENCES 131 test gt INSERT INTO customer state test gt VALUES AL INSERT 148732 1 test gt INSERT INTO customer state test gt VALUES XX ERROR lt unnamed gt referential integrity violation key referenced from customer not found in statename Figure 14 8 Foreign key constraints test gt CREATE TABLE customer
214. ires twice the storage of INTEGER and is slower OID is used to store POSTGRESQL object identifiers While INTEGER could be used for this purpose OID helps document the meaning of the value stored in the column NUMERIC precision decimal allows user defined digits of precision rounded to decimal places This type is slower than the other number types FLOAT and FLOAT4 allow storage of floating point values Numbers are stored using fifteen FLOAT or six FLOAT4 digits of precision The location of the decimal point is stored separately so large values like 4 78145e 32 can be represented FLOAT and FLOAT4 are fast and have compact storage but can produce imprecise rounding during computations When complete accuracy of floating point values is required NUMERIC should be used lASCH is the standard encoding used to map symbols to values For example uppercase A maps to the internal value 65 Lowercase a maps to the value 97 Period maps to 46 Space maps to 32 90 CHAPTER 9 DATA TYPES Temporal Temporal types allow storage of date time and time interval information While these can be stored in character strings it is better to use temporal types for reasons outlined earlier in this chapter The four temporal types are DATE TIME TIMESTAMB and INTERVAL DATE allows storage of a single date consisting of year month and day The format used to input and display dates is controlled by the DATESTYLE setting covered in section 4
215. irstname lastname city state age Dean Yeager Plymouth MA 24 Dick Gleason Ocean City INJ 19 2 rows Figure 4 16 Firstname begins with D firstname LIKE D The test firstname LIKE D returns rows where firstname contains a D anywhere in the field not just at the beginning The effect of the having a before and after a character allows the character to appear anywhere in the string More complex tests can be performed with LIKE as shown in table 4 3 While percent matches an Comparison Operation begins with D LIKE D contains a D LIKE D has D in second position LIKE D begins with D and contains e LIKE D e begins with D contains e then f LIKE D e f begins with non D NOT LIKE D Table 4 3 LIKE comparison unlimited number of characters the underscore _ matches only a single character The underscore allows any single character to appear in its position To test if a field does not match a pattern use NOT LIKE To test for an actual percent sign use An actual underscore _ is tested with two underscores Attempting to find all character fields that end with a certain character can be difficult For char columns like firstname there are trailing spaces that make such trailing comparisons difficult with LIKE Other character column types don t use trailing spaces Those can use the test colname LIKE g to
216. ks Inc AND test gt salesorder customer_id customer customer_id order_id Figure 6 7 Finding order number for customer name items is not important in these clauses 6 5 Three and Four Table Joins You can perform a three table join as shown in figure 6 8 The first printed column is the customer name test gt SELECT customer name employee name test gt FROM salesorder customer employee test gt WHERE salesorder customer id customer customer id AND test gt salesorder employee id employee employee id AND test gt salesorder order id 14673 name name SA E ENEE e E ee aie 2S A AA Fleer Gearworks Inc Lee Meyers 1 row Figure 6 8 Three table join The second column is the employee name Both columns are labeled name You could use AS to give the columns unique labels Figure 6 9 shows a four table join using AS to make each column label unique The four table join matches the arrows in figure 6 2 with the arrows of the salesorder table pointing to the other three tables 52 CHAPTER 6 JOINING TABLES test gt SELECT customer name AS customer_name test gt employee name AS employee name test gt part name AS part_name test gt FROM salesorder customer employee part test gt WHERE salesorder customer id customer customer id AND test gt salesorder employee id employee employee id AND test gt salesorder part id part part id AND test gt salesorder order id 14673 customer _name
217. l listing commands s ca annae RA E dee he REE a 150 psql large object commands so sossa oeo ee ee es 150 psql command line arguments eee 151 Interac ce BOUMAN e aa en a Sw ae A Ae A ek oe Be a a 153 XXIV LIST OF TABLES 20 1 Commonly used system tables eee eee 192 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 Chapter 1 History of POSTGRESQL 1 1 Introduction POSTGRESQL is the most advanced open source database server In this chapter you will learn about databases open source software and the history of POSTGRESQL There are three basic office productivity applications word processors spreadsheets and databases Word processors produce text documents critical to any business Sprea
218. l with from changed to to 7617 convert col to NUMERICO based on mask 7618 convert col to DATE based on mask 7619 convert col to TIMESTAMP based on mask 1640 round to an integer 7622 NUMERIC col rounded to len decimal places 7623 truncate to an integer 7624 NUMERICO col truncated to len decimal places oso absolute value 7627 factorial 7628 square root 7629 cube root 7630 exponential es natural logarithm 7633 base 10 logarithm 7634 convert col to a string based on mask 7635 units part of col 939 same as date_part ee col rounded to units 7639 BOOLEAN indicating if col is a valid date 7640 TIMESTAMP representing current date and tini641 string showing date time in UNIX format 7642 BOOLEAN indicating if col s overlap in time a convert col to string based on mask 7645 see psql s df for a list of geometric functions 7646 broadcast address of col 7647 host address of col 7648 netmask of col teas 7650 mask length of col 7651 network address of col 7652 return NULL if coll equals col2 else return oe return first non NULL argument is 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722
219. le test gt EXPLAIN SELECT FROM tabl tab2 WHERE coll col2 NOTICE QUERY PLAN Merge Join cost 139 66 164 66 rows 10000 width 8 gt Sort cost 69 83 69 83 rows 1000 width 4 gt Seq Scan on tab2 cost 0 00 20 00 rows 1000 width 4 gt Sort cost 69 83 69 83 rows 1000 width 4 gt Seq Scan on tabl cost 0 00 20 00 rows 1000 width 4 EXPLAIN Figure 11 5 EXPLAIN example using joins tabl and tab2 are joined on coll and col2 Each table is sequentially scanned and the result sorted The two results are then merge joined to produce output POSTGRESQL also supports hash join and nested loop join methods POSTGRESQL chooses the join method it believes to be the fastest 11 7 Summary There are a variety of tools available to speed up POSTGRESQL queries While their use is not required they can produce huge improvements in query speed Section 20 8 outlines more steps database administrators can take to improve performance 110 CHAPTER 11 PERFORMANCE 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 Chapter 12 Controlling Results When a SELECT query is issued from psql it t
220. le The other commands in the figure show the new table s structure and contents SELECT INTO tablename can also be written as CREATE TABLE tablename AS SELECT The above query can be rewritten as CREATE TABLE newfriend AS SELECT firstname lastname city state FROM friend 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 88 SUMMARY 85 8 8 Summary This chapter has shown how to combine queries in ways you probably never anticipated It showed how queries could be chained and placed inside other queries It showed how FROM can be used by UPDATE and how SELECT can create its own tables While these features are confusing they are also very powerful In most cases you will need only the simplest features from this chap
221. m the database 11808 11809 11810 return 0 11811 11812 11813 11814 Figure 17 4 Libpq sample program 156 CHAPTER 17 PROGRAMMING INTERFACES e Display results to the user e Terminate database connection All interaction with the database is done using libpq functions The libpq functions called by the sample program are PQconnectdb Connects to the database PQexec Sends the query to the database PQntuples Returns number of rows tuples in the result PQgetvalue Returns a specific row and column of the result PQclear Frees resources used by the result PQfinish Closes database connection These are the most common libpq functions The Programmer s Manual covers all libpg functions and shows additional examples 17 2 Pgeasy LIBPGEASY Libpgeasy is a simplified C interface It hides some of the complexity of libpg Figure 17 5 shows a libpgeasy version of the same application No error checking is required because libpgeasy automatically terminates the program if an error occurs This can be changed using on_error_continue 17 3 Embedded C ECPG Rather than using function calls to perform SQL queries ecpg allows SQL commands to be embedded in a C program The ecpg preprocessor converts lines marked by EXEC SQL to native SQL calls The resulting file is then compiled as a C program Figure 17 6 shows an ecpg version of the same application Ecpg implements the ANSI embedded SQL C standard which is s
222. marytest2 CREATE Figure 14 6 Example of a multi column primary key are foreign or outside the table For example suppose a table contains customer addresses and part of that address is the United States two character state code If a table existed with all valid state codes a foreign key constraint could be created to prevent invalid state codes from being entered Figure 14 7 shows the creation of a primary key foreign key relationship Foreign key constraints are test gt CREATE TABLE statename code CHAR 2 PRIMARY KEY name CHAR 30 test gt test gt CREATE test gt INSERT INTO statename VALUES AL Alabama INSERT 18934 1 test gt CREATE TABLE customer test gt test gt test gt test gt test gt test gt test gt test gt test gt CREATE customer_id INTEGER name telephone street city state zipcode country CHAR 30 CHAR 20 CHAR 40 CHAR 25 CHAR 2 REFERENCES statename CHAR 10 CHAR 20 Figure 14 7 Foreign key creation created by using REFERENCES to refer to the PRIMARY KEY of another table Foreign keys link the tables together and prevent invalid data from being inserted or updated Figure 14 8 shows how foreign keys constrain column values AL is a primary key value in statename so the INSERT is accepted XX is not a primary key value in statename so the INSERT is rejected by the foreign key constraint Figure 14 9 shows the creat
223. me Gleason Millstone Ned Sandy Tabor Victor Weber Yeager 10 rows Figure 8 1 Combining two columns with UNION single output column 71 72 CHAPTER 8 COMBINING SELECTS UNION allows an unlimited number of SELECT statements to be combined to produce a single result Each SELECT must return the same number of columns If the first SELECT returns two columns the other SELECTs must return two columns The column types must be similar also If the first SELECT returns an INTEGER value in the first column the other SELECTs must return an INTEGER in their first columns With UNION an ORDER BY clause can be used only at the end of the last SELECT The ordering applies to the output of the entire query In the previous figure 8 1 the ORDER BY clause specifies the ordering column by number Instead of a number we could use ORDER BY firstname because UNION s output labels are the same as the column labels of the first SELECT As another example suppose we have two tables that hold information about various animals One table holds information about aquatic animals and another contains information about terrestrial animals Two separate tables are used because each table records information specific to a class of animal The aquatic_ animal table holds information meaningful only for aquatic animals like preferred water temperature The terrestrial_animal table holds information meaningful only for terrestrial animals like running speed
224. me for the index but it is good to use the table and column names as part of the index name i e customer customer id idx or 1_customer_custid This index is only useful for finding rows in customer for specific customer ids It cannot help when accessing other columns because indexes are sorted by a specific column You can create as many indexes as you wish Of course an index on a seldom used column is a waste of disk space Also performance can suffer with too many indexes because row changes require an update to each index 105 106 CHAPTER 11 PERFORMANCE It is possible to create an index spanning multiple columns Multi column indexes are sorted by the first indexed column When the first column has several equal values sorting continues using the second indexed column Multi column indexes are only useful on columns with many duplicate values The command CREATE INDEX customer age gender idx ON customer age gender creates an index which is sorted by age and when several age rows have the same value then sorted on gender This index can be used by the query SELECT FROM customer WHERE age 36 AND gender F and the query SELECT FROM customer WHERE age 36 However index customer age gender idx is useless if you wish to find rows based only on gender The gender component of the index can be used only after the age value has been specified The query SELECT FROM customer WHERE gender F cannot use the index because ther
225. ments test gt INSERT INTO array_test VALUES test gt 1 test gt 1 test gt test gt INSERT 52694 1 test gt SELECT FROM array_test coll col2 col3 1 2 3 4 5 1 row test gt SELECT col1 4 FROM array test coll col2 col3 Figure 9 5 Using arrays Any data type can be used as an array If individual elements of the array are accessed frequently or updated it is better to use separate columns or tables rather than arrays 96 CHAPTER 9 DATA TYPES 9 8 Large Objects BLOBS POSTGRESQL cannot store values of more than several thousand bytes using the above data types nor can binary data be easily entered within single quotes Large objects also called Binary Large Objects or BLOBS are used to store very large values and binary data Large objects allow storage of any operating system file like images or large text files directly into the database You load the file into the database using lo import and retrieve the file from the database using lo_export Figure 9 6 shows an example that stores a fruit name and image Lo_import stores test gt CREATE TABLE fruit name CHAR 30 image OID CREATE test gt INSERT INTO fruit test gt VALUES peach To import usr images peach jpg INSERT 27111 1 test gt SELECT lo export fruit image tmp outimage jpg test gt FROM fruit test gt WHERE name peach lo_export 1 row test gt SELECT lo unlink fruit image FROM
226. mer_id finance customer_id CREATE 18910 1 Figure 13 8 Examples of views User sanders is then given SELECT access to the view Customer_address will show only address information Customer_finance is a join of customer and finance showing columns from both tables DROP VIEW removes a view Because views are not ordinary tables INSERTs UPDATEs and DELETEs on views have no effect The next section shows how rules can correct this 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 13 6 RULES 121 13 6 Rules Rules allow actions to take place when a table is accessed Rules can modify the effect of SELECT INSERT UPDATE and DELETE Figure 13 9 shows a rule that prevents INSERTs into a table The INSERT rule is named v
227. mmand line editing 8 CHAPTER 2 ISSUING DATABASE COMMANDS test gt SELECT test gt 2 10 1 test gt p SELECT 2 10 1 test gt g column 1 row test gt Figure 2 4 Backslash p demo 2 4 Exiting a Session This chapter would not be complete without showing you how to exit psql Use backslash q a to quit the session Backslash q exits psq1 Backslash g go p print r reset and q quit should be all you need for a while 2 5 Summary This chapter has shown how to use the most important features of psql This knowledge will allow you to try all the examples in this book However psql has many features that can assist you Section 16 1 covers psql in detail You may want to review that chapter while reading through the book 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 Chapter 3 Basic SQL Commands SQL stands for Structured Query Language It is the most common way of communicating with database servers and is supported by almost all database systems In this chapter you will learn about relational database systems and how to issue the most important SQL commands
228. mn Figure 4 6 shows a typical use of default values The default for the timestamp column is actually a call to an internal POSTGRESQL variable that returns the current date and time If any value is supplied for a field with a default that value is used instead 24 CHAPTER 4 CUSTOMIZING QUERIES test gt CREATE TABLE account test gt name CHAR 20 test gt balance NUMERIC 16 2 DEFAULT 0 test gt active CHAR 1 DEFAULT Y test gt created TIMESTAMP DEFAULT CURRENT_TIMESTAMP test gt CREATE test gt INSERT INTO account name test gt VALUES Federated Builders INSERT 19023 1 test gt SELECT FROM account name balance active created Federated Builders 0 00 Y Sat Nov 13 13 50 15 1994 EST 1 row Figure 4 6 Using DEFAULTs 4 5 Column Labels You might have noticed the text that appears at the top of each column in the SELECT output That is called the column label Usually the label is the name of the column being selected However you can control what text appears at the top of each column by using the AS keyword For example figure 4 7 replaces the default column label firstname with the column label buddy You might have noticed that the query in figure 2 3 on test gt SELECT firstname AS buddy FROM friend ORDER BY buddy buddy Sam 4 rows Figure 4 7 Controlling column labels page 7 has the colu
229. mn label column The database server returns this label when there is no suitable label In that case the result of an addition doesn t have an appropriate label Figure 4 8 shows the same query with an appropriate label added using AS test gt SELECT 1 3 AS total total Figure 4 8 Computation using a column label 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 4 6 COMMENTS 25 4 6 Comments POSTGRESQL allows you to place any text into psql for use as comments There are two comment styles The presence of two dashes marks all text to the end of the line as a comment POSTGRESQL also understand C style comments where the comment begins with slash asterisk and ends with asterisk slash Figure 4 9 s
230. n substring col FROM pos FOR len translate col from to to_number col mask to_date col mask to_timestamp col mask round col round col len trunc col trunc col len abs col factorial col sqrt col cbrt col exp col In col log log to_char col mask date_part units col extract units FROM col date_trunc untts col isfinite col now timeofday overlaps cl c2 c3 c4 to_char col mask GOM Network NULL broadcast host netmask masklen network nullif coalesce broadcast col host col netmask col masklen col network col nullif coll col2 coalesce coll col2 Table 9 3 Common functions CHAPTER 9 DATA TYPES Returns o length of col 7592 length of col same as length 7593 length of col including multi byte overhead 7594 col with leading and trailing spaces removed ae same as trim col with leading spaces removed a col with trailing spaces removed 7599 col with leading and trailing str removed 7600 col padded on the right to len characters ne col padded on the right using str 7603 col padded on the left to len characters 7604 col padded on the left using str 7605 col uppercased 7606 col lowercased ed col with the first letter capitalized 7609 position of str in col 7610 same as strpos 7611 col starting at position pos 7612 same as substr above T col starting at position pos for length len 7615 same as substr above 7616 co
231. n close public static void main String args try sample test new sample catch Exception exc System err printIn Exception caught n exc exc printStackTrace Figure 17 8 JAVA sample program 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 17 12 PYTHON PYGRESQL 163 12277 1 usr local bin perl 12278 12279 perl sample program 12280 12281 12282 12283 12284 12285 conn Pg connectdb dbname test connect to the database 12286 did the database connection fail pee die conn gt errorMessage unless PGRES CONNECTION OK eq conn gt status 12289 12290 print Enter a state code prompt user for a state code 12291 state_code lt STDIN gt 12292 chomp state code 12293 12294 12295 result conn gt exec send the query 12296 SELECT name 12297 FROM statename 12298 WHERE code state code 12299 12300 12301 12302 12303 while row result gt fetchrow loop through all rows returned 12304 print Grow An print the value returned 12305
232. n managerial employees using employee managers using manager and all employees including managers using employee 13 5 Views Views are pseudo tables They are not real tables but appear as ordinary tables to SELECT Views can represent a subset of a real table A view can select certain columns or certain rows from an ordinary table Views can even represent joined tables Because views have separate permissions they can be used to restrict table access so users see only specific rows or columns of a table Views are created using the CREATE VIEW command Figure 13 8 shows the creation of several views The view customer_ohio selects only customers from Ohio SELECTs on it will show only Ohio customers test gt CREATE VIEW customer_ohio AS test gt SELECT test gt FROM customer test gt WHERE state 0H CREATE 18908 1 test gt test gt let sanders see only Ohio customers test gt test gt GRANT SELECT ON customer_ohio TO sanders CHANGE test gt test gt create view to show only certain columns test gt CREATE VIEW customer_address AS test gt SELECT customer id name street city state zipcode country test gt FROM customer CREATE 18909 1 test gt test gt create view that combines fields from two tables test gt CREATE VIEW customer_finance AS test gt SELECT customer customer id customer name finance credit_limit test gt FROM customer finance test gt WHERE customer custo
233. n use these locations for new databases POSTGRESQL stores tables and indexes in operating system files Using operating system symbolic links databases tables and indexes can be moved to different disk drives often improving performance 20 9 System Tables There is a great deal of information stored in POSTGRESQL system tables These tables begin with pg They contain information about data types functions operators databases users and groups Table 20 1 shows the most commonly used tables Pg log is an binary file and not a real table Pg shadow contains user passwords and is not visible to ordinary users Pg user not shown is a view of pg shadow that does not display the password field There are several other system views available Most system tables are joined using OID s which are covered in section The psq1 dS command lists all system tables and views 192 CHAPTER 20 ADMINISTRATION Name Contents pg aggregate aggregates pg attribute columns pg class tables pg database databases pg description comments pg group groups pg index indexes pg log transaction status pg operator operators pg proc functions pg rewrite rules and views pg shadow users pg trigger triggers pg_type types Table 20 1 Commonly used system tables 20 10 Internationalization POSTGRESQL supports several features important for international use Multi byte encoding allows non ASCII character sets to be accurately stored in the
234. nctions 181 182 CHAPTER 19 EXTENDING POSTGRESQL USING C include postgres h double ctof double deg double ret palloc sizeof double ret deg 9 0 5 0 32 0 return ret Figure 19 1 C ctof function 19 2 Compile the C code The next step is to compile your C file into an object file that contains CPU instructions In fact a special object file must be created that can be dynamically linked into the POSTGRESQL server Many operating systems require special flags to create an object file that can be dynamically linked The best way to find the required flags is to go to pgsql src test regress and type make clean and then make regress so This will display the compile commands used to generate the dynamically linkable object file regress so The I compile flags allow searching for include files Some of the other flags are used for generating dynamic object files Use those flags to compile your C code into a dynamically linkable object file You may need to consult your operating system documentation for assistance in locating the proper flags 19 3 Register the New Functions Now that a dynamically linkable object file has been created its functions must be registered with POST GRESQL The CREATE FUNCTION command registers a new function by storing information in the database Figure 19 2 shows the CREATE FUNCTION command for ctof Ctof takes a float argument and returns a float test gt CREATE FUNCTION
235. nd Argument Import lo_import file Export Mo export oid file Unlink lo_unlink oid List lo_list Table 16 7 psql large object commands PSQL command line arguments and startup file You can change the behavior of psql when starting the psql session Psql is normally started from the command line with psql followed by the database name However psql accepts extra arguments between psql and the database name which modify psql s behavior For example psql f file test will read commands from file rather than from the keyboard Table 16 8 summarizes psql s command line options Consult the psql manual page for more detailed information Another way to change the behavior of psql on startup is to create a file called psqlrc in your home directory Each time psql starts it executes any backslash or SQL commands in that file 16 2 PGACCESS Pgaccess is a graphical database tool It It is used for accessing tables queries views sequences functions reports forms scripts users and schemas PGACCESS is written using the POSTGRESQL TCL TK interface The PGACCESS source code is in pgsql src bin pgaccess Figure 16 3 shows the opening pgaccess window The tabs on the left show the items that can be accessed The menu at the top allows database actions table import export and object creation deletion and renaming Figure 16 4 shows the table window This window allows table rows to be viewed and modified Pgaccess has man
236. nd store the result in a temporary table Figure 13 2 shows an example ofthis It uses SELECT INTO TEMPORARY TABLE to collect all Pennsylvania customers into a temporary table It also creates a temporary index on the temporary table Customer _ pennsylvania can then be used in subsequent SELECT queries Multiple users can do this at the same time with the same temporary names without fear of collision 13 2 ALTER TABLE ALTER TABLE allows the following operations e rename tables e rename columns 115 116 CHAPTER 13 TABLE MANAGEMENT psql test Welcome to psql the PostgreSQL interactive terminal Type copyright for distribution terms h for help with SQL commands for help on internal slash commands g or terminate with semicolon to execute query q to quit test gt CREATE TEMPORARY TABLE temptest col INTEGER CREATE test gt SELECT FROM temptest col 0 rows test gt q psql test Welcome to psql the PostgreSQL interactive terminal Type copyright for distribution terms h for help with SQL commands for help on internal slash commands g or terminate with semicolon to execute query q to quit test gt SELECT FROM temptest ERROR Relation temptest does not exist Figure 13 1 Temporary table auto destruction test gt SELECT test gt INTO TEMPORARY customer_pennsylvania test gt FROM customer test gt WHERE state PA SELECT test gt CREATE index customer_penna_cus
237. nderstood by COPY 15 6 Copy Tips Full pathnames must be used with the COPY command because the database server is running in a different directory than the psq1 client Files are read and written by the postgres user so postgres must have permission to read the file for COPY FROM and directory write permission for COPY TO Because COPY uses the local file system users connecting over a network cannot use filenames They can use stdin and stdout or psql s copy command By default the system generated OID column is not written out and loaded rows are given new OID s COPY WITH OIDS allows OID s to be written and read COPY writes only entire tables To COPY only part of a table use SELECT INTO TEMPORARY TABLE with an appropriate WHERE clause and then COPY the temporary table to a file See the COPY manual page for more detailed information 15 7 Summary COPY can be thought of as a crude INSERT and SELECT It imports and exports data in a very generic format This makes it ideal for use by other applications and for backup purposes 144 CHAPTER 15 IMPORTING AND EXPORTING DATA 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073
238. ng rules See section 18 4 for information about using triggers 13 7 LISTEN and NOTIFY POSTGRESQL allows users to send signals to each other using LISTEN and NOTIFY For example suppose a user wants to receive notification when a table is updated He can register the table name using the LISTEN command If someone updates the table and then issues a NOTIFY command all registered listeners will be notified For more information see the LISTEN and NOTIFY manual pages 13 8 Summary This chapter has covered features that give administrators and users new capabilities in managing database tables The next chapter covers restrictions that can be placed on table columns to improve data management 13 8 SUMMARY 125 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 test gt INSERT INTO view_realtable VALUES 3 9784 INSERT 407895 1 os test gt SELECT FROM view realtable 9787 col 9788 mam 9789 1 9790 9791 3 9792 2 rows 9793 9794 9795 test gt UPDATE view_realtable be test gt SET col 4 9798 UPDATE 2 9799 test gt SELECT FROM view realtable 9800 col 9801 9802 9803 4 9804 9805 o 9806 2 rows 9807 en test gt DELETE FROM view realtable 9810 DELETE 2 9811 test gt SELECT FROM view realtable 9812 9813 col 9814 wee 9815 0 rows 9816 9817 9818 9819 Figure 13 14 Rules handle view modifications 9820 9821 9822 9823 982
239. nly Values that do not match the dimensions specified at column creation are not rejected Figure 9 4 creates a table with one two and three dimensional INTEGER columns The first and last columns have sizes specified test gt CREATE TABLE array test test gt coll INTEGER 5 test gt col2 INTEGER test gt col3 INTEGER 2 2 test gt CREATE Figure 9 4 Creation of array columns 9 7 ARRAYS 95 The first column is a one dimensional array also called a list or vector Values inserted into that column look like 3 10 9 32 24 or 20 8 9 1 4 Each value is a list of integers surrounded by curly braces The second column col2 is a two dimensional array Typical values for this column are 2 9 3 43 5 or 18 6 132 5 Notice double braces are used The outer brace surrounds two one dimensional arrays You can think of it as a matrix with the first one dimensional array representing the first row of the array and the second representing the second row of the array Commas separate the individual elements and each pair of braces The third column of the array_test table is a three dimensional array holding values like 3 1 1 9 1 45 8 2 This is a three dimensional matrix made up of two 2x2 matrices Arrays of any size can be constructed Figure 9 5 shows a query inserting values into array_test and several queries selecting data from the table Brackets are used to access individual array ele
240. nsure data integrity This chapter explores these database capabilities 10 1 Transactions Though you may not have heard the term transaction before you have already used them Every SQL query is executed in a transaction Transactions give databases an all or nothing capability when making modifications For example suppose the query UPDATE trans test SET col 3 is in the process of modifying 700 rows And suppose after it has modified 200 rows the user types control C or the computer reset button is pressed When the user looks at trans_test he will see that none of the rows have been updated This might surprise you Because 200 of the 700 rows had already updated you might suspect 200 rows had been modified However POSTGRESQL uses transactions to guarantee queries are either completed or have no effect This feature is valuable Suppose you were executing a query to add 500 to everyone s salary And suppose you kicked the power cord out of the wall while the update was happening Without transactions the query may have updated half the salaries but not the rest It would be difficult to know where the UPDATE stopped You would wonder Which rows were updated and which ones were not You can t just re execute the query because some people have already received their 500 increase With transactions you can check to see if any of the rows were updated If one was updated they all were updated If not simply re execute the qu
241. nt If we add an employee id column to the customer table the column could store the identification number of the employee assigned to manage the customer s account Figure 6 11 shows how to perform the join between customer and employee tables The first query finds the test gt SELECT employee name test gt FROM customer employee test gt WHERE customer employee id employee employee id AND test gt customer customer_id 648 test gt SELECT customer name test gt FROM customer employee test gt WHERE customer employee_id employee employee id AND test gt employee employee_id 24 test gt ORDER BY customer name Figure 6 11 Joining customer and employee employee name assigned to manage customer number 648 The second query shows the customer names managed by employee 24 Notice the salesorder table is not involved in this query Suppose you wanted to assign an employee to be responsible for answering detailed questions about parts Add an employee_id column to the part table place valid employee identifiers in the column and perform similar queries as shown in figure 6 12 Adding columns to existing tables is covered in section 13 2 test gt find the employee assigned to part number 14673 test gt SELECT employee name test gt FROM part employee test gt WHERE part employee id employee employee id AND test gt part part_id 153 test gt find the parts assigned to employee 24 test gt SELECT p
242. nt in a comparison e Take the place of a constant yet vary based on the row being processed e Return a list of values for use in a comparison Subqueries as Constants A subquery also called a subselect can take the place of a constant in a query While a constant never changes a subquery s value is recomputed every time the query is executed As an example we will use the friend table from the previous chapters Suppose we want to find friends who are not in the same state as Dick Gleason We could place his state in the query using the constant string NJ but if he moves to another state the query would have to be changed Using his state column is more reliable Figure 8 7 shows two ways to generate the correct result One query uses a self join to do the comparison to Dick Gleason s state The last query uses a subquery which returns his state as NJ This value is used by the upper query The subquery has taken the place of a constant Unlike a constant the value is recomputed every time the query is executed Though we have used table aliases in the subquery for clarity they are not required A column name with no table specification is automatically paired with a table in the current subquery If no matching table is found in the current subquery higher parts of the query are searched for a match State firstname and lastname in the subquery refer to the instance of the friend table in the subquery The same column names in the u
243. nteractive terminal Type copyright for distribution terms h for help with SQL commands for help on internal slash commands g or terminate with semicolon to execute query q to quit test gt Figure 2 1 psql session startup 2 2 Controlling a Session Congratulations You have successfully connected to the POSTGRESQL server You can now issue commands and receive replies from the server Let s try one Type SELECT CURRENT USER and press Enter see figure 2 2 If you make a mistake just press backspace and retype This should show your login name underneath the test gt SELECT CURRENT USER getpgusername postgres 1 row test gt Figure 2 2 My first SQL query dashed line In the example the login name postgres is shown The word getpgusername is a column label The server is also reporting that it has returned one row of data The line test gt tells you that the server is done and is waiting for your next database query Let s try another one At the test gt prompt type SELECT CURRENT TIMESTAMP and press Enter It should show the current date and time Each time you execute the query the server will report the current time to you Typing in the Query Buffer Typing in the query buffer is similar to typing at an operating system command prompt However at an operating system command prompt Enter completes each command In psql commands are completed only 1A few operating systems are case insensitive
244. number of interest so there is no reason to use the salesorder table It goes directly to the orderpart table to find the parts making up the order and joins to the part table for part descriptions The second query does not have the order number It only has the customer id and order date It must use the salesorder table to find the order number and then join to the orderpart and part tables to get order quantities and part information The third query does not have the customer id but instead must join to the customer table to get the customer_id for use with the other tables Notice each query displays more columns to the user The final query computes the total cost of the order It uses an aggregate to SUM cost times quantity for each part in the order 6 13 Primary and Foreign Keys A join is performed by comparing two columns like customer customer id and salesorder customer_td Cus tomer customer_id is called a primary key because it is the unique primary identifier for the customer table Salesorder customer_id is called a foreign key because it holds a key to another foreign table 6 14 Summary Previous chapters covered query tasks This chapter dealt with technique the technique of creating an orderly data layout using multiple tables Acquiring this skill takes practice Expect to redesign your first table layouts many times as you improve them Good data layout can make your job easier Bad data layout can make queries a
245. o ark heee ar Bie aoa de eek ee beens 60 7 Numbering Rows 63 7 1 Object Identi cation Numbers ODS as mar santen A A A 63 7 2 Object Identification Number Limitations eee eee eee ee 64 To DOQUENEES 655 ree een a ad td BE A BAS ie EE at B At e 65 TA Creatine Sequences as Aaen ee a ee ee EE DR We ad ne 65 75 Using Sequences to Number ROWS ce 2 eo Se ee 4S mand aen kh 67 70 Serial Coloma Woe eoa aa dee en Hek He Bende WAA A vele heen B 68 7 7 Manually Numbering Rows eea eee 68 TO SUMMARY oe on ee ea de ee ee hi A we ee ke het AR dek ee 69 0727 0728 0729 0730 0731 0732 0733 0734 0735 0736 0737 0738 0739 0740 0741 0742 0743 0744 0745 0746 0747 0748 0749 0750 0751 0752 0753 0754 0755 0756 0757 0758 0759 0760 0761 0762 0763 0764 0765 0766 0767 0768 0769 0770 0771 0772 0773 0774 0775 0776 0777 0778 0779 0780 0781 0782 0783 0784 0785 0786 0787 0788 0789 0790 0791 0792 0793 0794 0795 0796 0797 0798 0799 0800 0801 0802 0803 0804 0805 0806 0807 0808 0809 0810 0811 0812 0813 0814 0815 0816 0817 0818 0819 0820 0821 0822 0823 0824 0825 0826 0827 0828 0829 0830 0831 0832 0833 0834 0835 0836 0837 0838 0839 0840 0841 0842 0843 0844 0845 0846 0847 0848 0849 0850 0851 0852 0853 0854 0855 0856 0857 0858 CONTENTS 8 Combining SELECTs 8 1 UNION EXCEPT INTERSECT Clauses aoe a osn a ee eee ae Boe 82
246. of POSTGRESQL 1 Li ri za 4 44 5 EEE OO AK 1 1 2 UNIVERSITY OF CALIFORNIA AT BERKELEY a ce a od wR RARA 1 a Development Leaves BERRELEY poro a vann one adem aen ee ee ee 4 1 1 4 POSTGRESQL Global Development Team 2 2 es 2 Lo Open Source Sonware ata she ew a we Pee ea Sw ah a dw WO e 3 IES DUNE coa AI ERA re DAA A BSR 3 2 Issuing Database Commands 5 21 DAS Database SESSO e aen a e ede a A A 5 22 Controlling a Se AR EA EE 6 23 Geine He ans a AI oe ER IRA EAS EA 7 24 Exiting a Session eo crad See ESR A ER SSS SPREE EE ea E R 8 Oo PUM e e ek ee ee aa See wee Boa i a ead ees a eee ae Ras 8 3 Basic SQL Commands 9 3 1 Relational Databases a a 6 6 GaSe RGR OR ds a wR WE RS HEE 9 22 CNE AAA 10 33 Ane Data With INSERT 22 04 Leeder atadewea ies 44 6444 44040445 11 24 Viewing Data With SELECT o a e se pesis aada ed a eenn AA ee a 12 3 5 Selecting Specific Rows with WHERE 1 0 ee ee ee es 13 3 6 Removing Data with DELETE anar REE ARA ROK 14 3 7 Modifying Data with UPDATE lt occorirnir cient ric AAA 14 238 Ote Data Vh ORDER BY gt sms AR 14 29 DOE MEN sosu anane er UA A GR E Bas RRA A See 4 17 AlO SOM sad e rr a a a beters ears we dk G 17 4 Customizing Queries 19 DL DADES oe niina e atra BEE Boe a VOELEN WR BE AOR iA 3 19 12 Quotes meide Et oaeen ew Gee ees HA aal moe BR a a G 19 do Using NULL AI 21 xi xii CONTENTS da Controlling DEFAULT Values a anar A eS 23 A5 Colum lbabels a e a BON A ETE a Ba GE S
247. om the function Many other PL PGSQL features are covered in the User s Manual mentioned in section A 3 Figure 18 11 shows a PL PGSQL function that provides a server side interface for maintaining the statename table Function change_statename performs INSERT UPDATE and DELETE operations on the statename table Change statename is called with a state code and state name If the state code is not in the table it iS inserted If it already exists the state name is updated If the function is called with an empty state name the state is deleted from the table The function returns true t if statename was changed and false Cf if the statename table was unmodified Figure 18 12 shows examples of its use 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12382 12883 12884 12885 12386 12887 12888 12889 12390 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 18 3 PL PGSQL FUNCTIONS 173 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 test gt CREATE FUNCTION spread text 12951 test gt RETURNS text 12952 12953 test gt AS DECLARE 12954 test gt str text 12999 test gt ret text
248. ome so popular that other scripting languages use it as their graphical interface library 17 12 PYTHON PYGRESQL PYTHON is an object oriented scripting language It is considered to be a well designed language with code that is easy to read and maintain Figure 17 11 shows the same application written in PYTHON The PYTHON interface source code is located in pgsql src interfaces python 162 CHAPTER 17 PROGRAMMING INTERFACES pe Java sample program ed import java io import java sql public class sample Connection conn holds database connection Statement stmt holds SQL statement String state_code holds state code entered by user public sample throws ClassNotFoundException FileNotFoundException IOException SQLExcep tion Class forName org postgresql Driver load database interface connect to the database conn DriverManager getConnection jdbc postgresql test testuser stmt conn createStatement System out print Enter a state code prompt user for a state code System out flush BufferedReader r new BufferedReader new InputStreamReader System in state_code r readLine ResultSet res stmt executeQuery send the query SELECT name FROM statename WHERE code state code if res null while res next String state name res getString 1 System out printIn state_name res close stmt close con
249. on about these commands 20 6 Server Startup and Shutdown The POSTGRESQL server uses two distinct programs postmaster and postgres Postmaster accepts all requests for database access It does authentication and starts a postgres process to handle the connection The postgres process executes user queries and returns results Figure 20 4 illustrates this relationship POSTGRESQL sites normally have only one postmaster process but many postgres processes There is one postgres process for every open database session Administrators only need to start the postmaster and the postmaster will start postgres backends as connection requests arrive The postmaster can be started from the command line or from a script Another way to start the postmaster is using pg_ctl The pg_ct1 utility allows easy starting and stopping of the postmaster See the pg_ctl manual page for more information The operating system startup scripts can even be modified to start the postmaster automatically The postmaster can be stopped by sending the process a signal using kill or by using pg_ct1 190 CHAPTER 20 ADMINISTRATION Connection Requests se Postmaster Queries gt Results Ss Postgres Postgres Postgres Figure 20 4 Postmaster and postgres processes 20 7 Monitoring Postmaster and postgres produce useful information for administrators They have many flags to control the information they output They can show user
250. oped in the 1970 s SAI the files mentioned in this chapter are available as part of the POSTGRESQL distribution or at http www postgresql org docs Frequently Asked Questions 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1 5 OPEN SOURCE SOFTWARE 3 styles were also quite varied We wrote a tool to reformat the entire source tree in a consistent manner We wrote a script to find functions that could be marked as static or never called functions that could be removed completely These are run just before each release A release checklist reminds us of the items to be changed for each release As we gained knowledge of the code we were able to perform more complicated fixes and feature additions We redesigned poorly
251. order table using each row s OID as a join key test gt CREATE TABLE salesorder test gt order_id INTEGER test gt customer oid OID joins to customer oid test gt employee oid OID joins to employee oid test gt part o d OID joins to part oid Figure 7 2 Columns with OIDs A column of type OID is similar to an INTEGER column but defining it as type OID documents that the column holds OID values Don t confuse a column of type OID with a column named OID Every row has a normally invisible column named OID A row can have zero one or more user defined columns of type OID A column of type OID is not automatically assigned any special value from the database Only the column named OID is specially assigned during INSERT Also the order id column in the salesorder table could be eliminated The salesorder oid column could represent the unique order number 7 2 Object Identification Number Limitations This section covers three limitations of object identification numbers Non Sequential Numbering The global nature of object identification assignment means most OIDs in a table are not sequential For example if you insert a customer today and another one tomorrow the two customers will not get sequential OIDs The two customer OIDs could differ by thousands This is because INSERTs into other tables between 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 7 3 SEQUENCES 65 the two customer
252. ore performing UPDATE 4420 or DELETE do a SELECT or SELECT COUNT with the same WHERE clause Make sure the SELECT result is ee reasonable before doing the UPDATE or DELETE 44 CHAPTER 5 SQL AGGREGATES 5 5 Summary Sometimes users want less output rather than more They want a total count average maximum or minimum value for a column Aggregates make this possible They collect or aggregate data into fewer rows and send the result to the user 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 Chapter 6 Joining Tables This chapter shows how to store data using multiple tables Multi table storage and multi table queries are fundamental to relational databases We start this chapter with table and column refer
253. ows Figure 10 9 shows the same query using SELECT FOR UPDATE Another user cannot modify the James row between the SELECT FOR UPDATE and UPDATE You can also manually control locking using the LOCK command It allows specification of a transaction s lock type and scope See the LOCK manual page for more information 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 10 6 DEADLOCKS test gt BEGIN test gt test gt test gt test gt id Sache Pose A AAA 521 1 row test gt test gt test gt test gt test gt test gt UPDATE test gt COMMIT BEGIN WORK SELECT FROM lock test WHERE name James FOR UPDATE James the SELECTed row is locked UPDATE lock test SET name
254. ows how COPY can be used to unload and load database tables The remainder of the chapter covers topics of interest to those using COPY to share data with other applications The last section contains tips for using COPY 15 1 Using COPY Copy TO allows the contents of a table to be copied out to a file The file can later be read in using COPY FROM Figure 15 1 illustrates this It shows the creation of a table with columns of various types Two rows are then inserted into copytest SELECT shows the contents of the table and COPY TO writes the table to file tmp copytest out The rows are then deleted and COPY FROM reloads the table as shown by the last SELECT COPY provides a quick way to load and unload tables It is used for database backup as covered in section 20 5 The following sections cover various COPY features that are important when reading or writing COPY files in other applications 15 2 Copy File Format Copy TO can export data to be loaded into other applications and COPY FROM can import data from other applications If you are constructing a file to be used by COPY or you are reading a COPY file in another application it is important to understand COPY s file format Figure 15 2 shows the contents of the COPY file from figure 15 1 First q exits psql to an operating system prompt Then the UNIX cat command displays the file tmp copytest out The file contains one line for every row in the table Columns in t
255. ows storage of an IP address with or without a netmask A typical INET value with netmask is 172 20 90 150 255 255 255 0 CIDR stores IP network addresses It allows a subnet mask to specify the size of the network segment A typical CIDR value is 172 20 90 150 24 MACADDR stores MAC Media Access Control addresses These are assigned to Ethernet network cards at the time of manufacture A typical MACADDR value is 0 50 4 1d f6 db Internal There are a variety of types used internally Psql s dT command shows all data types 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 9 3 TYPE CONVERSION USING CAST 91 9 3 Type Conversion using CAST In most cases values of one type are converted to another type automatically In rare
256. pco 23 Sam Jackson Allentown PA 22 Mike Nichols Tampa FL 20 3 rows test gt SELECT FROM friend WHERE age IS NULL ORDER BY age DESC firstname lastname city state age Mark Middleton Indianapolis IN 1 row Figure 4 3 NULL handling test gt INSERT INTO friend test gt VALUES Jack Burger NULL NULL 27 INSERT 19053 1 test gt SELECT FROM friend WHERE city state firstname lastname city state age 0 rows Figure 4 4 Comparison of NULL fields CUSTOMIZING QUERIES 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 4 4 CONTROLLING DEFAULT VALUES 23 There is one more
257. pper query automatically refer to the friend instance in the upper query If a column name matches two tables in the same subquery an error is returned indicating the column is ambiguous Subqueries can eliminate table joins also For example consider the parts order company in figures 6 3 and 6 4 on page 48 To find the customer name for order number 14673 we join the salesorder and customer 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 8 2 SUBQUERIES test gt SELECT FROM friend ORDER BY firstname firstname lastname city state age Hen non on Dean Yeager Plymouth MA 24 Dick Gleason Ocean City NJ 19 Ned Millstone Cedar Creek MD 27 Sandy Gleason Ocean City NJ 25 Sandy We
258. prefer SET DATESTYLE TO POSTGRES EUROPEAN The ISO DATESTYLE and GERMAN DATESTYLE are not affected by any of the other options TIMEZONE defaults to the timezone of the server or the PGTZ environment variable The psql client might be in a different timezone and SET TIMEZONE allows this to be changed inside psql See the SET manual page for a full list of SET options The SHOW command is used to display current database session parameters RESET allows session parameters to be reset to their default values Figure 4 24 shows an example of this test gt SHOW DATESTYLE NOTICE DateStyle is Postgres with US NonEuropean conventions SHOW VARIABLE test gt SET DATESTYLE TO SQL EUROPEAN SET VARIABLE test gt SHOW DATESTYLE NOTICE DateStyle is SQL with European conventions SHOW VARIABLE test gt RESET DATESTYLE RESET VARIABLE test gt SHOW DATESTYLE NOTICE DateStyle is Postgres with US NonEuropean conventions SHOW VARIABLE Figure 4 24 SHOW and RESET examples 4 15 Summary This chapter has shown how simple commands can be enhanced using features like DISTINCT NULL and complex WHERE clauses These features give users great control over how queries are executed They were chosen by committees to be important features that should be in all SQL databases While you may never use all the features listed in this chapter many of them will be valuable when solving real world problems Your site defaults may be dif
259. quotes you might get to a point where your backslash commands don t work anymore and your prompt will appear as test gt Notice the single quote before the greater than sign Just type another single quote to get out of this mode use r to clear the query buffer and start again Notice that the 19 doesn t have quotes It doesn t need them because the column is a numeric column not a character column When you do your inserts be sure to match each piece of data to the receiving column Use the INSERT query in figure 3 4 as a sample and complete the insertion of the three friends shown in table 3 1 2A character string is a group of characters strung together 12 CHAPTER 3 BASIC SQL COMMANDS test gt INSERT INTO friend VALUES test gt Mike test gt Nichols test gt Tampa test gt ELA test gt 19 test gt INSERT 18720 1 Figure 3 4 Insert 3 4 Viewing Data with SELECT You have seen how to store data in the database Let s show you how to retrieve data Surprisingly there is only one command to get data out of the database and that command is SELECT You have already used SELECT in your first database query in figure 2 2 on page 6 SELECT has many variations We are going to use it to show the rows in the table friend The query is shown in figure 3 5 In this case I put the entire query test gt SELECT FROM friend firstname lastname city state age
260. r backslash g to finish For example SELECT 4 10 would return 40 Addition is performed using plus subtraction using minus multiplication using asterisk and division using forward slash If you have readline installed psq1 will even allow you to use your arrow keys Your left and right arrow keys allow you to move around and the up and down arrows retrieve previously typed queries Displaying the Query Buffer You can continue typing indefinitely until you use a semicolon or backslash g Everything you type will be buffered by psql until you are ready to send the query If you use backslash p p you see everything accumulated in the query buffer In figure 2 4 three lines of text are accumulated and displayed by the user using backslash p After display we use backslash g to execute the query which returns the value 21 This comes in handy with long queries Erasing the Query Buffer If you don t like what you have typed use backslash r r to reset or erase the buffer 2 3 Getting Help You might ask Are these backslash commands documented anywhere If you look at figure 2 1 you will see the answer is printed every time psql starts Backslash prints all valid backslash commands Backslash h displays help for SQL commands SQL commands are covered in the next chapter 2Don t be concerned about column We will cover that in section 4 7 3Readline is an open source library that allows powerful co
261. r example dt sec displays all table names beginning with sec and dt x shows all table names containing an x Regular expressions are covered in section 4 10 When using listing commands the descriptions of data types and functions are called comments POST GRESQL predefines many comments and the COMMENT command allows users to define their own The dd command and others display these comments See the COMMENT manual page for more information Many of the commands allow an optional plus sign which shows additional information For example aT lists all data types while dT includes the size of each type df shows addition information about functions When using the other commands a plus sign causes the comments for the object to be displayed Large Object Commands Psq1 has a local large object interface that allows large object operations using files local to the computer running psq1 rather than local to the computer running the database server Table 16 4 shows the local large object commands supported by psql 150 CHAPTER 16 DATABASE QUERY TOOLS Listing Command Argument Table index view or sequence d name Tables dt name Indexes di name Sequences ds name Views dv name Permissions zor dp name System tables dS name Large Objects dl name Types dT name Functions df name Operators do name Aggregates da name Comments dd name Databases l Table 16 6 psql listing commands Large Objects Comma
262. ravels to the POSTGRESQL server is executed and the result sent back to psql to be displayed POSTGRESQL allows fine grained control over which rows are returned This chapter explores the methods available 12 1 LIMIT The LIMIT and OFFSET clauses of SELECT allow the user to specify which rows should be returned For example suppose customer has 1000 rows with customer id values from 1 to 1000 Figure 12 1 shows queries using LIMIT and LIMIT OFFSET The first query sorts the table by customer_id and uses LIMIT to test gt SELECT customer id FROM customer ORDER BY customer id LIMIT 3 customer _id 3 rows test gt SELECT customer id FROM customer ORDER BY customer id LIMIT 3 OFFSET 997 customer id 999 1000 3 rows Figure 12 1 Examples of LIMIT and LIMIT OFFSET return the first three rows The second query is similar except it skips to the 997th row before returning three rows Notice each query uses ORDER BY While this is not required LIMIT without ORDER BY returns random rows from the query which is useless LIMIT improves performance because it reduces the number of rows returned to the client If an index matches the ORDER BY sometimes LIMIT can even produce correct results without executing the entire query 111 112 CHAPTER 12 CONTROLLING RESULTS 12 2 Cursors Ordinarily all rows generated by a SELECT are returned to the client Cursors allow a SELECT query to be named and individual result rows fetched
263. rder border 0 1 or 2 Display NULLs null null_string HTML table tags tableattr tags Page output pager command Table 16 3 psql pset options rows suppressing table headings and row counts Tuples_only does not take a second argument It is an on off parameter The first pset tuples_only turns it on and another one turns it off The second pset in the figure causes psq to display NULL as null Output Format Shortcuts In addition to using pset some output format options have shortcuts as shown in table 16 4 Variables The set command sets a variable and lunset removes a variable Variables are accessed by preceeding the variable name with a colon The set command used alone lists all defined variables Figure 16 2 shows the use of psql variables The first variable assigned is num_var It is accessed in the SELECT query by preceeding the variable name with a colon The second set command places the word SELECT into a variable and uses that variable to perform a SELECT query The next example uses backslash quotes to create a string that contains single quotes This variable can then be used in place of a quoted string in queries Date_var shows that grave accents allow a command to be run and the result 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 1118
264. re are new possibilities In open source software there is no company Capable programmers with interest and some free time get together via the Internet and exchange ideas Someone writes a program and puts it in a place everyone can access Other programmers join and make changes When the program is sufficiently functional they advertise the program s availability to other Internet users Users find bugs or missing features and report them back to the developers who enhance the program It sounds like an unworkable cycle but in fact it has several advantages A company structure is not required so there is no overhead and no economic restrictions e Program development is not limited to a hired programming staff but taps the capabilities and experi ence of a large pool of Internet programmers e User feedback is facilitated allowing program testing by a large number of users in a short period of time e Program enhancements can be rapidly distributed to users 1 6 Summary This chapter has explored the long history of POSTGRESQL starting with its roots in university research POSTGRESQL would not have grown to the success it is today without the Internet The ability to commu nicate with people around the world has allowed a community of unpaid developers to enhance and support 7A static function is a function that is used by only one program file 8Linux is a popular UNIX like open source operating system 4 CHAPTER 1 HISTORY
265. re quite different The sample programs perform SELECTs on a CHAR 30 column Because query results are returned as character strings returned values can be assigned directly to program variables However non character string columns like INTEGER and FLOAT can not be assigned directly to integer or floating point variables A conversion might be required For example using libpq or libbq a SELECT on an INTEGER column does not return an integer from the database but a character string that must be converted to an integer by the application An INTEGER is returned as the string 983 rather than the integer value 983 To assign this to an integer variable the C library function atoi must be used i e var atoi colval One exception to this is BINARY cursors which return binary representations of column values Results from BINARY cursors can be assigned directly to program variables However because they return column values in binary format the application and database server must be running on the same computer or computers with the same CPU architecture See the DECLARE manual page for more information on BINARY cursors Libpgeasy uses fetch to return values directly into program variables Fetch should place results into character string variables or use BINARY cursors if possible Ecpg automatically converts data returned by POSTGRESQL to the proper format before assignment to program variables The interpreted languages
266. revious commands Mike had a birthday so we want to update his age in this table Figure 3 12 shows an example The example shows the word UPDATE the table name friend followed by SET then the column name the equals sign and the new value The WHERE clause restricts the number of rows affected by the update as in DELETE Without a WHERE clause all rows are updated Notice that the Mike row has moved to the end of the list The next section will show you how to control the order of the row display 3 8 Sorting Data with ORDER BY In a SELECT query rows are displayed in an undetermined order If you want to guarantee the rows are returned from SELECT in a specific order you need to add the ORDER BY clause to the end of the SELECT Figure 3 13 shows the use of ORDER BY You can reverse the order by adding DESC as seen in figure 3 14 If the query were to use a WHERE clause too the ORDER BY would appear after the WHERE clause as in figure 3 15 You can ORDER BY more than one column by specifying multiple column names or labels separated by commas It would sort by the first column specified For rows with equal values in the first column it would sort based on the second column specified Of course this does not make sense in the friend example because all column values are unique 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
267. row 64 UPDATE row 64 Transaction 2 must wait to see if first transaction commits COMMIT WORK Transaction 1 commits Transaction 2 returns from UPDATE COMMIT WORK Transaction 2 commits Table 10 3 Waiting for a lock action must wait to see if the other transaction commits or rolls back If these had been using SERIALIZABLE isolation level transaction 2 would have been rolled back automatically if transaction 1 committed The only time users must wait for other users is when they are trying to modify the same row If they modify different rows there is no waiting SELECT queries never have to wait Locking is done automatically by the database However there are cases when locking must be controlled manually For example figure 10 8 shows a query that first SELECTs a row then performs an UPDATE The test gt BEGIN WORK BEGIN test gt SELECT test gt FROM lock_test test gt WHERE name James id name pao A sets 521 James 1 row test gt test gt the SELECTed row is not locked test gt test gt UPDATE lock_test test gt SET name Jim test gt WHERE name James UPDATE 1 test gt COMMIT WORK COMMIT Figure 10 8 SELECT with no locking problem is another user can modify the James row between the SELECT and UPDATE To prevent this you can use SERIALIZABLE isolation In this mode one of the UPDATEs would fail A better solution is to use SELECT FOR UPDATE to lock the selected r
268. s done the Java JDBC on Interface 0611 0612 Nikolaidis Byron in Baltimore Maryland byron nikolaidis home com rewrote and maintains the 0613 ODBC interface for Windows a 0616 0617 f 0618 e Teodorescu Constantin in Braila Romania teo flex ro has done the PgAccess DB Interface 0619 0620 Thyni G ran in Kiruna Sweden goran kyla kiruna se has worked on the UNIX socket code 0621 0622 0623 Non code contributors 0624 0625 e Bartunov Oleg in Moscow Russia oleg sai msu su introduced the locale support ie 0628 0629 0630 All developers listed in alphabetical order 0631 0632 0633 0634 0635 0636 0637 0638 0639 0640 0641 0642 0643 0644 0645 0646 0647 0648 0649 0650 0651 0652 0653 0654 0655 0656 0657 0658 0659 0660 e Owen Lamar in Pisgah Forest North Carolina USA damar owen wgcr org RPM package maintainer e Vielhaber Vince near Detroit Michigan USA vev michvhf com maintains our website 0661 0662 0663 0664 0665 0666 0667 0668 0669 0670 0671 0672 0673 0674 0675 0676 0677 0678 0679 0680 0681 0682 0683 0684 0685 0686 0687 0688 0689 0690 0691 0692 0693 0694 0695 0696 0697 0698 0699 0700 0701 0702 0703 0704 0705 0706 0707 0708 0709 0710 0711 0712 0713 0714 0715 0716 0717 0718 0719 0720 0721 0722 0723 0724 0725 0726 Contents Note to Reviewers iii Foreword Preface Vii Acknowledgements ix 1 History
269. s made by customer Fleer Gearworks Inc The numbers after DELETE and UPDATE indicate the number of rows affected by the queries 82 SELECT name order_id FROM customer salesorder WHERE customer customer_id UNION ALL SELECT name NULL FROM customer WHERE customer customer_id ORDER BY name test gt DELETE FROM customer CHAPTER 8 COMBINING SELECTS salesorder customer_id NOT IN SELECT customer_id FROM salesorder Figure 8 14 Simulating outer joins test gt WHERE customer_id NOT IN test gt test gt test gt DELETE 0 test gt UPDATE salesorder test gt SET test gt WHERE test gt test gt test gt test gt UPDATE 1 customer_id SELECT customer_id FROM salesorder J ship_date 11 16 96 SELECT customer_id FROM customer WHERE name Fleer Gearworks Inc Js Figure 8 15 Subqueries with UPDATE and DELETE 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7
270. s the use of backslash quotes and grave accents to run the date command and surround it with single quotes The final SELECT shows that date_var2 holds a quoted date string that can be used in queries Psql predefines a number of variables They are listed in table 16 5 The variables in the first group Meaning Variable Name Argument Database DBNAME Multibyte encoding ENCODING Host HOST Previously assigned OID LASTOID Port PORT User USER Echo queries ECHO all Echo d queries ECHO_HIDDEN noexec History control HISTCONTROL ignorespace ignoredups or ignoreboth History size HISTSIZE command_count Terminate on end of file IGNOREEOF eof_count lobject transactions LO TRANSACTION rollback commit nothing Stop on query errors ON_ERROR_STOP Command prompt PROMPT1 PROMPT2 PROMPTS string Suppress output QUIET Single line mode SINGLELINE Single step mode SINGLESTEP Table 16 5 psql predefined variables contain useful information The rest affect the behavior of psq1 Some of the predefined variables do not take an argument They are activated using set and deactivated using unset Listing Commands You can find a great deal of information about the current database using psql s listing commands as shown in table 16 6 They show information about tables indexes functions and other objects defined in the database Most listing commands take an optional name parameter This parameter can be specified as a regular expression Fo
271. s these rows next to each other on disk speeding indexed lookups CLUSTER can also speed ORDER BY processing See the CLUSTER manual page for more information 11 4 Vacuum When POSTGRESQL updates a row it keeps the old copy of the row in the table file and writes a new one The old row is marked as expired and used by other transactions still viewing the database in its prior state Deletions are similarly marked as expired but not removed from the table file The VACUUM command removes expired rows from the file While 1t removes them 1t moves rows from the end of the table into the expired spots thereby compacting the table file The VACUUM command should be run periodically to clean out expired rows For tables that are heavily modified 1t is useful to run VACUUM every night in an automated manner For tables with few modifications VACUUM should be run only periodically VACUUM exclusively locks the table while processing There are two ways to run VACUUM VACUUM alone vacuums all tables in the database VACUUM tablename vacuums a single table 11 5 Vacuum Analyze The VACUUM ANALYZE command is like VACUUM except it also collects statistics about each column s pro portion of duplicate values and the maximum and minium values This information is used by POSTGRESQL when deciding how to efficiently execute complex queries VACUUM ANALYZE should be run when a table is initially loaded and when the table data dramatically changes The V
272. sn t make sense to add a number to three symbols Similarly the character string 3 8 1992 is eight symbols starting with 3 and ending with 2 If you store it in a character string data type it is not a date You cannot sort it with other values and expect them to be in chronological order The string 1 4 1998 is less than 3 6 1992 when these are sorted as character strings because 1 is less than 3 This illustrates why the other data types are valuable The other types have a predefined format for their data and can do more appropriate operations on the stored information Still there is nothing wrong with storing numbers or dates in character strings when appropriate The street address 100 Maple Avenue is best stored in a character string type even though a number is part of the street address It makes no sense to store the street number in a separate INTEGER field Also part numbers like G8223 9 must be stored in character strings because of the G and dash In fact part numbers that are always five digits like 32911 or 00413 should be stored in character strings too They are not real numbers but symbols Leading zeros cannot be displayed by INTEGER fields but are easily displayed in character strings Number Number types allow the storage of numbers The number types are INTEGER INT2 INT8 OID NUMERICO FLOAT and FLOAT4 INTEGER INT2 and INT8 store whole numbers of various ranges Larger ranges require more storage Le INT8 requ
273. st gt customer_id INTEGER test gt name CHAR 30 test gt telephone CHAR 20 test gt street CHAR 40 test gt city CHAR 25 test gt state CHAR 2 REFERENCES statename test gt ON UPDATE CASCADE test gt ON DELETE SET NULL test gt zipcode CHAR 10 test gt country CHAR 20 test gt CREATE Figure 14 10 Customer table with foreign key actions ON UPDATE CASCADE specifies that if statename s PRIMARY KEY is updated customer state should be updated with the new value too The foreign key ON DELETE SET NULL option specifies that if someone tries to delete astatename row that is referenced by another table the delete should set the foreign key to NULL The possible ON UPDATE and ON DELETE actions are NO ACTION UPDATEs and DELETEs to the PRIMARY KEY are prohibited if referenced by a foreign key row This is the default CASCADE UPDATEs to the PRIMARY KEY cause UPDATEs to all foreign key columns that reference it DELETEs on the PRIMARY KEY cause DELETES of all foreign key rows that reference it SET NULL UPDATEs and DELETEs to the PRIMARY KEY row cause the foreign key to be set to NULL SET DEFAULT UPDATEs and DELETEs to the PRIMARY KEY row cause the foreign key to be set to its DEFAULT Figure 14 11 illustrates the use of CASCADE and NO ACTION rules The figure first shows the creation of primarytest which was used in figure 14 5 It then creates a foreigntest table with ON UPDATE CASCADE and O
274. st gt order id INTEGER test gt customer id INTEGER joins to customer customer id test gt employee id INTEGER joins to employee employee id test gt part id INTEGER joins to part part id test gt order date DATE test gt ship date DATE test gt payment NUMERIC 8 2 test gt CREATE Figure 6 3 Creation of company tables 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 6 3 CREATING JOINED TABLES 49 4753 4754 4755 4756 4757 4758 4759 4760 o test gt INSERT INTO customer VALUES es test gt 648 4764 test gt Fleer Gearworks Inc ca test gt 1 610 555 782 4767 test gt 830 Winding Way 4768 test gt Millersville 4769 ae ia test gt oi o 4771 test gt 35041 4772 test gt USA 4773 4774 test gt 4775 INSERT 18838 1 4776 test gt INSERT INTO employee VALUES 4777 4778 test gt 24 4779 test gt Lee Meyers 4780 test gt 10 16 1989 4781 4782 test gt 4783 INSERT 18839 1 he test gt INSERT INTO part VALUES 4786 test gt 153 4787 test gt Garage Door Spring 4788
275. state_code 3 holds state code entered by user char state_name NULL holds value returned by query char query string 256 holds constructed SQL query EXEC SQL END DECLARE SECTION EXEC SQL CONNECT TO test connect to the database printf Enter a state code prompt user for a state code scanf 2s state code sprintf query string create an SQL query string SELECT name FROM statename WHERE code s state code EXEC SQL PREPARE s statename FROM query string EXEC SQL DECLARE c statename CURSOR FOR s statename DECLARE a cursor EXEC SQL OPEN c_statename send the query EXEC SQL WHENEVER NOT FOUND DO BREAK while 1 loop through all rows returned EXEC SQL FETCH IN c_statename INTO state name printf s n state name print the value returned state name NULL free state name free result EXEC SQL CLOSE c_statename CLOSE the cursor EXEC SQL COMMIT EXEC SQL DISCONNECT disconnect from the database return 0 Figure 17 6 Echg sample program 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 1200
276. straints UNIQUE prevents duplicates and NOT NULL prevents NULL values in the column Figure 14 5 shows the creation of a PRIMARY KEY column Notice an index is created automatically test gt CREATE TABLE primarytest col INTEGER PRIMARY KEY NOTICE CREATE TABLE PRIMARY KEY will create implicit index primarytest pkey for table primarytest CREATE test gt d primarytest Table primarytest Attribute Type Modifier zee A ee eee een col integer not null Index primarytest_pkey Figure 14 5 Creation of PRIMARY KEY column and the column defined as NOT NULL Just as with UNIQUE a multi column PRIMARY KEY constraint must be specified on a separate line Figure 14 6 shows an example of this It shows coll and col2 are combined to form a primary key There cannot be more than one PRIMARY KEY specification per table PRIMARY KEYs have special meaning when using foreign keys which are covered in the next section 14 4 FOREIGN KEY REFERENCES Foreign keys are more complex than primary keys Primary keys make a column UNIQUE and NOT NULL Foreign keys constrain based on columns in other tables They are called foreign keys because the constraints 130 test gt CREATE TABLE primarytes test gt test gt test gt test gt t2 CHAPTER 14 CONSTRAINTS coll INTEGER col2 INTEGER PRIMARY KEY coll col2 NOTICE CREATE TABLE PRIMARY KEY will create implicit index primarytest2 pkey for table pri
277. structured code We moved into a mode where each release had major new features instead of just bug fixes We improved SQL conformance added sub selects improved locking and added missing SQL functionality We added commercial style telephone support The Usenet discussion group archives started touting us In the previous year we searched for POST GRESQL and found many people were recommending other databases even though we were addressing user concerns as rapidly as possible One year later many people were recommending us to users who needed transaction support complex queries commercial grade SQL support complex data types and reli ability This more clearly portrayed our strengths Other databases were recommended when speed was the overriding concern REDHAT S shipment of POSTGRESQL as part of their LINUX distribution quickly multiplied our user base Every release is now a major improvement over the last Our global development team now has mastery of the source code we inherited from Berkeley Finally every module is understood by at least one development team member We are now easily adding major features thanks to the increasing size and experience of our world wide development team 1 5 Open Source Software POSTGRESQL is open source software The term open source software often confuses people With commercial software a company hires programmers develops a product and sells it to users With Internet communi cation the
278. t FROM aquatic_animal test gt UNION test gt SELECT name test gt FROM terrestrial_animal name penguin swordfish tiger 3 rows Figure 8 3 UNION with duplicates test gt SELECT name test gt FROM aquatic_animal test gt UNION ALL test gt SELECT name test gt FROM terrestrial_animal name swordfish penguin tiger penguin 4 rows Figure 8 4 UNION ALL with duplicates test gt SELECT name test gt FROM aquatic_animal test gt EXCEPT test gt SELECT name test gt FROM terrestrial_animal name swordfish 1 row Figure 8 5 EXCEPT restricts output from the first SELECT 73 74 CHAPTER 8 COMBINING SELECTS test gt SELECT name test gt FROM aquatic_animal test gt INTERSECT test gt SELECT name test gt FROM terrestrial_animal name penguin 1 row Figure 8 6 INTERSECT returns only duplicated rows columns to populate a single result column Without the ability to chain SELECTs using UNION EXCEPT and INTERSECT it would be impossible to generate the desired results SELECT chaining can do other sophisticated things like joining a column to one table in the first SELECT and joining the same column to another table in the second SELECT 8 2 Subqueries Subqueries are similar to SELECT chaining While SELECT chaining combines SELECTs on the same level in a query subqueries allow SELECTs to be embedded inside other queries Subqueries can e Take the place of a consta
279. t SELECT FROM friend 2561 firstname lastname city state age 2562000 Bresdin Wee So Sees ateseee desen hegeosterdeenss homo 2 Cindy Anderson Denver cO 23 2565 Sam Jackson Allentown PA 22 2566 Mike Nichols Tampa FL 20 2567 DE 3 rows 2569 2570 2571 Figure 3 12 My first UPDATE 2572 2573 2574 16 CHAPTER 3 BASIC SQL COMMANDS test gt SELECT FROM friend ORDER BY state firstname lastname city state age Cindy Anderson Denver co 23 Mike Nichols Tampa FL 20 Sam Jackson Allentown PA 22 3 rows Figure 3 13 Use of ORDER BY test gt SELECT FROM friend ORDER BY age DESC firstname lastname city state age Cindy Anderson Denver pco 23 Sam Jackson Allentown PA 22 Mike Nichols Tampa FL 20 3 rows Figure 3 14 Reverse ORDER BY test gt SELECT FROM friend WHERE age gt 21 ORDER BY firstname firstname lastname city state age Cindy Anderson Denver co 23 Sam Jackson Allentown PA 22 2 rows Figure 3 15 Use of ORDER BY and WHERE 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608
280. t plus the additional test gt CREATE TABLE parent test coll INTEGER CREATE test gt CREATE TABLE child test col2 INTEGER INHERITS parent test CREATE test gt d parent test Table parent test Attribute Type Modifier A s AA E coll integer test gt d child test Table child test Attribute Type Modifier pateo ais A O A eae coll integer col2 integer Figure 13 5 Creation of inherited tables columns it defines In the example child_test gets coll from parent_test plus the column col2 Inheritance also links rows in parent and child tables If the parent table is referenced with an asterisk suffix rows from the parent and all children are accessed Figure 13 6 shows insertion into two tables related by inheritance The figure then shows that while parent_test access only the parent_test rows parent_test accesses both parent_test and child_test rows Parent_test accesses only columns common to all tables Child_test col2 is not in the parent table so it is not displayed Figure 13 7 shows inherited tables can be layered on top of each other 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368
281. t 507 nuts 508 cat 507 nuts 6 rows Figure 6 16 Unjoined tables column in vegetable causing every value in animal to be paired with every value in vegetable This effect is called a Cartesian product and is usually not intended When a query returns many more rows than expected look for an unjoined table in the query 6 10 Table Aliases and Self Joins In section 6 1 you saw how to refer to specific tables in the FROM clause using a shorter name Figure 6 17 shows a rewrite of the query in figure 6 14 using aliases A c is used as an alias for the customer table and s test gt SELECT order_id test gt FROM customer c salesorder s test gt WHERE c code FLEOO1 AND test gt c customer_id s customer_id Figure 6 17 Using table aliases is used as an alias for the salesorder table Table aliases are handy in these cases However with table aliases you can even join a table to itself Such joins are called self joins The same table is given two different alias names Each alias then represents a different instance of the table This might seem like a concept of questionable utility but it can prove useful Figure 6 18 shows practical examples For simplicity results are not shown for these queries 58 CHAPTER 6 JOINING TABLES test gt SELECT c2 name test gt FROM customer c customer c2 test gt WHERE c customer id 648 AND test gt c zipcode c2 zipcode test gt SELECT c2 name s order_id test gt
282. t a valid column name you will get an error message ERROR attribute mycolname not found If you try selecting from a table that does not exist you will get an error message like ERROR Relation mytablename does not exist POSTGRESQL is using the formal relational database terms relation and attribute in these error messages 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 3 5 SELECTING SPECIFIC ROWS WITH WHERE 13 3 5 Selecting Specific Rows with WHERE Let s take the next step in controlling the output of SELECT In the previous section we showed how to select only certain columns from the table Now we will show how to select only certain rows The additional thing needed to do this is the WHERE clause Without a WHER
283. tandard Addison Wesley Date Introduction Date C J An Introduction to Database Systems Addison Wesley Celko Celko Joe SQL For Smarties Morgan Kaufmann Hilton Hilton Craig and Jeff Willis Building Database Applications on the Web Using PHP3 Addison Wesley User s Guide POSTGRESQL User s Guide http www postgresql org docs user Tutorial POSTGRESQL Tutorial http www postgresql org docs tutorial Administrator s Guide POSTGRESQL Administrators Guide http www postgresql org docs admin Programmer s Guide POSTGRESQL Programmer s Guide http www postgresql org docs programmer Appendices POSTGRESQL Appendices http www postgresql org docs postgres part appendix htm 201
284. te code getresult sys stdout write s n name print the value returned Figure 17 11 PYTHON sample program 17 13 PHP PHP allows web browser access to POSTGRESQL Using PHP database commands can be embedded in web pages Two web pages are required for the sample application one for data entry and another for display Figure 17 12 shows a web page that allows entry of a state code Figure 17 13 shows a second web page that lt PHP sample program Input gt lt HTML gt lt BODY gt lt prompt user for a state code gt lt FORM ACTION lt echo SCRIPT NAME gt pg sample2 phtml state code method POST gt Client Number lt INPUT TYPE text name state_code value lt echo state code gt maxlength 2 size 2 gt lt BR gt lt INPUT TYPE submit value Continue gt lt FORM gt lt BODY gt lt HTML gt Figure 17 12 PHP sample program Input performs a SELECT and displays the results Normal web page commands HTML tags begin with lt and end with gt PHP code begins with lt and ends with gt The PHP interface is not shipped with POSTGRESQL It can be downloaded from http www php net 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12
285. te name test gt WHERE code state code test gt END IF test gt RETURN t test gt ELSE is DELETE test gt SELECT INTO statename_rec test gt FROM statename test gt WHERE code state code test gt IF FOUND test gt THEN DELETE FROM statename test gt WHERE code state code test gt RETURN t test gt ELSE RETURN f test gt END IF test gt END IF test gt END IF test gt END test gt LANGUAGE plpgsql Figure 18 11 PL PGSQL change statename function 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 18 3 PL PGSQL FUNCTIONS 177 13201 13202 13203 13204 13205 13206 2 3 13207 test gt DELETE FROM statename 13208 DELETE 1 13209 test gt SELECT change_statename AL Alabama 13210 13211 change_statename 1321200 enneneeeeeeeeeneen 13213 t 13214 13215 1 row 13216 13217 test gt SELECT FROM statename 13218 13219 code name 1322000 tee Fresca poison ece ee ceeds 13221 1329 AL Alabama 13223 1 row 13224 13225 E ENE i 13256 test
286. ter However you may get that one in a thousand request that requires one of the more complicated queries covered in this chapter Hopefully this chapter was clear enough so you will recognize that query and return to this chapter to refresh your memory 86 CHAPTER 8 COMBINING SELECTS 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 Chapter 9 Data Types Data types have been used in previous chapters This chapter covers them in detail 9 1 Purpose of Data Types It is tempting to think databases would be easier to use if there was only one data type a type that could hold any type of information numbers character strings or dates While a single data type would certainly make table creation simpler there are d
287. test gt test gt test gt test gt test gt test gt test gt test gt test gt CREATE customer id INTEGER PRIMARY KEY name CHAR 30 telephone CHAR 20 street CHAR 40 city CHAR 25 state CHAR 2 zipcode CHAR 10 country CHAR 20 test gt CREATE TABLE employee test gt test gt test gt test gt CREATE employee id INTEGER PRIMARY KEY name CHAR 30 hire_date DATE test gt CREATE TABLE part test gt test gt test gt test gt test gt CREATE part_id INTEGER PRIMARY KEY name CHAR 30 cost NUMERIC 8 2 weight FLOAT test gt CREATE TABLE salesorder test gt test gt test gt test gt test gt test gt test gt test gt CREATE order id INTEGER customer id INTEGER REFERENCES customer employee id INTEGER REFERENCES employee part_id INTEGER REFERENCES part order_date DATE ship_date DATE payment NUMERIC 8 2 Figure 14 9 Creation of company tables using primary and foreign keys 132 CHAPTER 14 CONSTRAINTS Modification of Primary Key Row If a foreign key constraint references a row as its primary key and the primary key row is updated or deleted the default foreign key action is to prevent the operation Foreign key options ON UPDATE and ON DELETE allow a different action to be taken Figure 14 10 shows the use of these options The new customer table s test gt CREATE TABLE customer te
288. test gt THEN RETURN statename_rec code test gt END IF test gt test gt WHILE 1 lt len LOOP test 2 4 6 chars for match test gt search str trim substr state str 1 1 test gt SELECT INTO matches COUNT test gt FROM statename test gt WHERE name LIKE search str test gt test gt IF matches count 0 no matches failure test gt THEN RETURN NULL test gt END IF test gt IF matches count 1 exactly one match return it test gt THEN test gt SELECT INTO statename rec test gt FROM statename test gt WHERE name LIKE search str test gt IF FOUND test gt THEN RETURN statename_rec code test gt END IF test gt END IF test gt i 2 gt 1 match try 2 more chars test gt END LOOP test gt RETURN test gt END test gt LANGUAGE plpgsql Figure 18 9 PL PGSQL getstatecode function 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 1308
289. the file was used 15 4 COPY without files COPY can be used without files COPY can use the same input and output locations used by psql The special name stdin represents the psql input and stdout represents the psql output Figure 15 5 shows how stdin can be used to supply COPY input directly from your keyboard For clarity text typed by the user is in bold The gaps in second line typed by the user were generated by pressing the TAB key The user types to exit COPY FROM COPY to stdout displays the COPY output on your screen This can be useful when using psq 1 in automated scripts 142 CHAPTER 15 IMPORTING AND EXPORTING DATA test gt COPY copytest FROM stdin Enter data to be copied followed by a newline End with a backslash and a period on a line by itself test gt 3 77 43 coffee f test gt test gt COPY copytest TO stdout 1 23 99 fresh spring water t 2 55 23 bottled soda t 3 77 43 coffee f test gt Figure 15 5 COPY using stdin and stdout 15 5 Backslashes and NULLs There is potential confusion if the character used as a column delimiter also exists in user data If they appeared the same in the file COPY FROM would be unable to determine if the character was a delimiter or user data COPY avoids any confusion by specially marking delimiters appearing in user data It preceedes them with a backslash 1 If pipe is the delimiter COPY TO uses pipes for delimiters and backslash pipes for pip
290. tid_idx ON customer_pennsylvania customer_id CREATE Figure 13 2 Example of temporary table use 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 13 3 GRANTAND REVOKE 117 e add columns e add column defaults e remove column defaults Figure 13 3 shows examples of all of these test gt CREATE TABLE altertest coll INTEGER CREATE test gt ALTER TABLE altertest RENAME TO alterdemo ALTER test gt ALTER TABLE alterdemo RENAME COLUMN coll TO democol ALTER test gt ALTER TABLE alterdemo ADD COLUMN col2 INTEGER ALTER test gt show renamed table renamed column and new column test gt d alterdemo Table alterdemo Attribute Type Modifier as Fp EIERE ER ea me E democol integer col2 integ
291. tiple values using SETOR Function actions can contain INSERTS UPDATES and DELETEs too Function actions can also contain multiple queries separated by semicolons The function action in ftoc uses SELECT to perform a computation It does not access any tables The 1 in the SELECT is automatically replaced by the first argument of the function call If there were a second argument it would be represented as 2 Constants in the function contain decimal points so floating point computations are performed Without them division would be performed using integers For example the query SELECT 1 4 returns 0 while SELECT 1 0 4 0 returns 0 25 When the query SELECT ftoc 68 is executed it calls ftoc Ftoc replaces 1 with 68 and the computation in ftoc is executed In a sense this is a SELECT inside a SELECT The outer SELECT calls ftoc and ftoc uses its own SELECT to perform the computation Figure 18 2 shows an SQL server side function to compute tax The casts to NUMERIC 8 2 are required 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672
292. tname city state age Dean Yeager Plymouth MA 24 Ned Mi lstone Cedar Creek MD 27 2 rows test gt firstname contains b B c or C test gt SELECT FROM friend test gt WHERE firstname bc test gt ORDER BY firstname firstname lastname A Dick Gleason Victor Tabor 2 rows test gt firstname does city state age Ocean City INJ 19 Williamsport PA 22 not contain s or S test gt SELECT FROM friend test gt WHERE firstname x Ig test gt ORDER BY firstname firstname lastname city state age Hon t Dean Yeager Plymouth MA 24 Dick Gleason Ocean City INJ 19 Ned Millstone Cedar Creek MD 27 Victor Tabor Williamsport PA 22 4 rows Figure 4 17 Regular expression sample queries 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585
293. to create functions in languages other than C This chapter covers C functions and the creation of custom operators data types and aggregates that behave just like the ones already in POSTGRESQL Extending POSTGRESQL in this way involves several steps e Write C code to implement the new functionality e Compile the C code into an object file that contains CPU instructions e Issue CREATE FUNCTION commands to register the new functions e Issue the proper commands if creating operators data types or aggregates CREATE OPERATOR CREATE TYPE CREATE AGGREGATE The full details of extending POSTGRESQL are beyond the scope of this book This chapter is just an overview The Programmer s Manual mentioned in section A 3 has more detailed information 19 1 Writing C code The best way to add a new function operator data type or aggregate is to start with a copy of a file from the POSTGRESQL source directory pgsql src backend utils adt Start with a file that has functions similar to the ones you need Make sure your new function names are unique For example the previous chapter had a ftoc SQL function that converted Fahrenheit to centigrade Figure 19 1 shows a C function that converts centigrade to Faharenheight While writing C functions you may find it necessary to execute SQL queries from inside the function The Server Programming Interface SPI allows C functions to execute SQL queries and process results from within C fu
294. tors addition subtraction multiplication division modulo remainder and exponentiation honor the standard precedence rules Exponentiation is done first multiplication division and modulo are second and addition and subtraction are performed last Parentheses can be used to alter this precedence Other operators are evaluated left to right unless parentheses are present 4 14 SET SHOW and RESET The SET command allows the changing of various POSTGRESQL parameters The changes remain in effect for the duration of the database connection Table 4 7 shows various parameters that can be controlled with SET 34 CHAPTER 4 CUSTOMIZING QUERIES test gt SELECT state FROM friend ORDER BY state state PA 6 rows test gt SELECT DISTINCT state FROM friend ORDER BY state state PA 4 rows test gt SELECT DISTINCT city state FROM friend ORDER BY state city city state O O eS EE Boston MA Plymouth MA Cedar Creek MD Ocean City NJ Williamsport PA 5 rows Figure 4 21 DISTINCT prevents duplicates Function SET option DATESTYLE DATESTYLE TO POSTGRES SQU ISO GERMAN US NONEUROPEAN EUROPEAN TIMEZONE TIMEZONE TO value Table 4 7 SET options Output for Style Optional Ordering February 1 1983 POSTGRES us or NONEUROPEAN 02 01 1983 SQL US or NONEUROPEAN 02 01 1983 ISO 1983 02 01 German 01 02 1983 Table 4 8 DATESTY
295. trimming down the bloat caused by much experimentation and research We had a lot of fun reworking the internals At the time we had no idea where we were going with the project The POSTGRES95 exercise was not research but simply a bit of engineering housecleaning By the spring of 1995 1t occurred to us that there was a need for an open source SQL based multi user database in the Internet user community Our first release was met with great enthusiasm We are very pleased to see the project continuing Obtaining information about a complex system like POSTGRESQL is a great barrier to its adoption This book fills a critical gap in the documentation of the project This book provides an excellent overview of the system It covers a wide range of topics from the basics to the more advanced and unique features of POSTGRESQL In writing this book Bruce Momjian has drawn on his experience in helping beginners with POSTGRESQL The text is easy to understand and full of practical tips Momjian captures database concepts using simple and easy to understand language He also presents numerous real life examples throughout the book He does an outstanding job and covers many advanced POSTGRESQL topics Enjoy reading the book and have fun exploring POSTGRESQL It is our hope this book will not only teach you about using PostgreSQL but also inspire you to delve into its innards and contribute to the ongoing POSTGRESQL development effort JOLLY CHEN and ANDREW YU
296. ue NULLis a special value that is valid in any column It is used when a valid entry for a field is not known or not applicable In the previous example we wanted to add Mark to the database but we didn t know his age It is hard to imagine what numeric value could be used for Mark s age column Zero or minus one would be strange age values NULL is the perfect value for his age Suppose we had a spouse column What value should be used if someone is not married A NULL value would be the proper value for that field If there were a wedding anniversary column unmarried people would have a NULL value in that field NULL values are very useful Before databases supported NULL values users would put special values in columns like 1 for unknown numbers and 1 1 1900 for unknown dates NULLs are much clearer NULLs have a special behavior in comparisons Look at figure 4 3 First notice the age column for Mark is empty It is really a NULL In the next query because NULL values are unknown the NULL row does not appear in the output The third query really confuses people Why doesn t the Mark row appear The age is NULL or unknown meaning the database doesn t know if it equals 99 or not so it doesn t guess It refuses to print it In fact there is no comparison that will produce the NULL row except the last query shown The tests IS NULL and IS NOT NULL are designed specifically to test for the existence of NULL values NULLs often confuse new users
297. uld enter the column as CustomerId but POSTGRESQL converts all identifiers like column and table names to lowercase so the actual column name becomes customerid which is not very clear You can t put spaces in table or column names either unless you put double quotes around the name like customer id Double quotes also preserve any capitalization you supply If you decide to use this feature you have to put double quotes around the table or column name every time you reference it This can be cumbersome Keep in mind that all table and column names not protected by double quotes should be made up of only letters numbers and the underscore character Each name must start with a letter not a number Don t use punctuation except underscore in your names either For example address office and zipcode9 are valid names while 2pair and my are not The example also shows the existence of a column named customer_1d in two tables This is done because the two columns contain the same type of number a customer identification number Naming them the same clearly shows which columns join the tables together If you wanted to use unique names you could name the column salesorder_customer_id or sales cust id This makes the column names unique but still documents the columns to be joined Figure 6 4 shows the insertion of a row into the customer employee and part tables It also shows the insertion of a row into the salesorder table using the sam
298. uletest insert and test gt CREATE TABLE ruletest col INTEGER CREATE test gt CREATE RULE ruletest insert AS rule name test gt ON INSERT TO ruletest INSERT rule test gt DO INSTEAD DO INSTEAD type rule test gt NOTHING ACTION is NOTHING CREATE 18932 1 test gt INSERT INTO ruletest VALUES 1 test gt SELECT FROM ruletest col 0 rows Figure 13 9 Rule that prevents INSERT the action is NOTHING NOTHING is a special rule keyword that does nothing There are two types of rules DO rules perform SQL commands in addition to the submitted query Do INSTEAD rules replace the user query with the rule action Figure 13 10 shows how rules can track table changes The figure creates service_request to hold current service requests and service request log to record changes in the service request table The figure also creates two DO rules on service request Rule service request update causes an INSERT into service request log each time service request is updated The special keyword old is used to insert the pre UPDATE column values into service request log The keyword new would refer to the new query values The second rule tracks deletions to service request by inserting into service request log To distinguish updates from deletes in service request log updates are inserted with a mod type of U and deletes with a mod_type of D DEFAULT was used for the username and timestamp fields A column s de
299. upported by many database systems 17 4 C LIBPQ Libpq is POSTGRESQL s C interface Figure 17 7 shows the same application using libpq Libpq allows database access using object methods rather than function calls 17 5 Compiling Programs The above interfaces are based on C or C Each interface requires certain include and library files to generate an executable version of the program Interface include files are usually installed in usr local pgsql include The compiler flag I is needed so the compiler searches that directory for include files i e I usr local pgsql include Interface libraries are usually installed in usr local pgsql lib The compiler flag L is needed so the compiler searches that directory for library files i e L usr local pgsql lib 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11385 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912
300. vious transactions still exist By understanding POSTGRESQUS multi user behavior you are now prepared to create robust queries Overlapping transactions and locking must always be considered POSTGRESQL has a powerful set of features to allow the construction of reliable multi user queries 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 Chapter 11 Performance In an ideal world users would never need to be concerned about performance The system would tune itself However databases don t live in an ideal world An untuned database can be thousands of times slower than a tuned one so it pays to take steps to improve performance This chapter shows how to get optimal performance from your database 11 1 Indexes When ac
301. we aS JT SURE saa ai e eai aet is AA EEE ek RES SRE 12 Controlling Results 12 1 LIMIT 122 CUESOTS ae an a AAA Adr Bld Aoi eland Bd AR edn A PER oca paar Taa eS Oh ee ehs bemad dh a 13 Table Management 13 1 Temporary lables aaan renem dan aaa ae doe wm See os ee da Pe TABUE one Ae a ia oe ee a a eee We 4 133 GRANT and REVOKE ces ee en ee ee RAN OS ES WR ele G 134A ae AA xiii 71 71 74 81 81 83 83 84 85 87 87 87 91 91 91 94 94 96 96 97 97 97 99 100 101 103 103 105 105 106 106 107 107 107 109 111 111 112 112 XIV CONTENTS 135 VIEWS aen de mana ee RE RGR eee Rd dee We Hd 120 0859 Ee BE en ee Aes eeen dean Seen ordende Oet ende he Ren de ee eee pee ter 121 0860 13 7 LISTEN and NOTIFY zoa ea ea te denn a ae A a 124 Hee 138 SUMEN 4 sa eerden he BY sbs bekent hing 124 0863 0864 14 Constraints 127 eee HAT NOT NULL os a een ed we Ba Ae do hee GR Bee BR wee at we wd 127 0867 EZ UNIQUE oo oe is wars Ge Wm ale ended dw Oe dw Se eee WE dele ws Sears ds 128 0868 14 3 PRIMARY en Se Rae aen EE REAR Rede BN Oe Da 129 ed 14 4 FOREIGN KRWREDERENGES ot po ven neme A a Hae Oe bee A ED 129 0871 EEE A Rees eee SESH Re ESS SESE ekeren 137 0872 EA ae ee eS WE OEE ER SHES HEH ES SSeS ES EE ed 137 ne 0875 15 Importing and Exporting Data 139 0876 IL a oe ee es eae a ee ere a 139 eee 15 2 COPY File Format 4002 00 600666 64 ob bb ew eee eae Eee ew ee ds 139 0879 15 3 DEUMITERS 6454 pa ma OSH Da
302. within specified limits With small databases constraints are of marginal benefit With databases holding millions of rows constraints help keep database information organized and complete 138 CHAPTER 14 CONSTRAINTS 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 Chapter 15 Importing and Exporting Data Copy allows rapid loading and unloading of user tables COPY can write the contents of a table to an ASCII file and it can load a table from an ASCII file These files can be used for backup or to transfer data between POSTGRESQL and other applications The first section of this chapter sh
303. x Carvers INSERT 19005 1 test gt INSERT INTO customer name VALUES Pipe Fitters INSERT 19008 1 test gt SELECT FROM customer customer_id name A es A E A AE 1 Bread Makers 2 Wax Carvers 3 Pipe Fitters 3 rows Figure 7 4 Numbering customer rows using a sequence ment creates a sequence counter named customer_seg The second command creates the customer table and defines nextval customer seq as the default for the customer id column The first INSERT manually supplies the sequence value for the column The nextval customer_seq function call will return the next available sequence number and increment the sequence counter The second and third INSERTs allow the nextval customer_seq DEFAULT be used for the customer 1d column Remember a column s DEFAULT value is used only when a value is not supplied by an INSERT statement This is covered in section 4 4 The SELECT shows the sequence has sequentially numbered the customer rows 68 CHAPTER 7 NUMBERING ROWS 7 6 Serial Column Type There is an easier way to use sequences If you define a column of type SERIAL a sequence will be automatically created and a proper DEFAULT assigned to the column Figure 7 5 shows an example of this The first NOTICE line indicates a sequence was created for the SERIAL column Do not be concerned about test gt CREATE TABLE customer test gt customer_id SERIAL test gt name CHAR 30 test gt NOTICE C
304. y help screens which cover its capabilities in more detail 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 16 2 PGACCESS Option Connection Controlling Output Automation Capability Database optional Hostname Port User Force password prompt Version Field alignment Field separator Record separator Rows only Extended outp ut format Echo d queries Quiet mode HTML output HTML table tags Set pset options List databases Disable readline Echo all queries from scripts Echo queries Execute query Get queries from file Output to file Sin
305. zone The final SELECT uses psql s x display mode Without the x the SELECT would have displayed too much information to fit on one line The fields would have wrapped around the edge of the display making it hard to read The columns would still line up but there would be other data in the way Of course another solution to field wrapping is to select fewer columns Remember you can select any columns from the table in any order Section 9 2 covers column types in more detail 4 2 Quotes Inside Text Suppose you want to insert the name O Donnell You might be tempted to enter this in psql as 0 Donnell but this will not work The presence of a single quote inside a single quoted string generates a parse error This is the format generated by typing the command date at the UNIX command prompt See section 16 1 for a full list of the psq backslash commands 19 20 CHAPTER 4 CUSTOMIZING QUERIES test gt CREATE TABLE alltypes test gt state CHAR 2 test gt name CHAR 30 test gt children INTEGER test gt distance FLOAT test gt budget NUMERIC 16 2 test gt born DATE test gt checkin TIME test gt started TIMESTAMP test gt CREATE test gt INSERT INTO alltypes test gt VALUES test gt PA test gt Hilda Blairwood test gt 3 test gt 10 7 test gt 4308 20 test gt 9 8 1974 test gt 9 00 test gt 07 03 1996 10 30 00 INSERT 1854
Download Pdf Manuals
Related Search
Related Contents
Nokia 2160 Cell Phone User Manual THE 74 ANNUAL MILITARY POLICE EXPO 2015 300204 - Cadence Meter Instructions Rev C_fre.pmd XTnano Configuration Manual 取扱説明書(PDF) - 株式会社シービジョン 取扱説明書の表示 Copyright © All rights reserved.
Failed to retrieve file