2 # basics.py - basic SQL commands tutorial
3 # inspired from the Postgres95 tutorial
4 # adapted to Python 1995 by Pascal ANDRE
7 __________________________________________________________________
8 MODULE BASICS.PY : BASIC POSTGRES SQL COMMANDS TUTORIAL
10 This module is designed for being imported from python prompt
12 In order to run the samples included here, first create a connection
13 using : cnx = basics.DB(...)
15 The "..." should be replaced with whatever arguments you need to open an
16 existing database. Usually all you need is the name of the database and,
17 in fact, if it is the same as your login name, you can leave it empty.
19 then start the demo with: basics.demo(cnx)
20 __________________________________________________________________
31 # table creation commands
32 def create_table(pgcnx):
33 print "-----------------------------"
34 print "-- Creating a table:"
35 print "-- a CREATE TABLE is used to create base tables. POSTGRES"
36 print "-- SQL has its own set of built-in types. (Note that"
37 print "-- keywords are case-insensitive but identifiers are "
38 print "-- case-sensitive.)"
39 print "-----------------------------"
41 print "Sending query :"
42 print "CREATE TABLE weather ("
43 print " city varchar(80),"
49 pgcnx.query("""CREATE TABLE weather (city varchar(80), temp_lo int,
50 temp_hi int, prcp float8, date date)""")
52 print "Sending query :"
53 print "CREATE TABLE cities ("
54 print " name varchar(80),"
55 print " location point"
57 pgcnx.query("""CREATE TABLE cities (
61 # data insertion commands
62 def insert_data(pgcnx):
63 print "-----------------------------"
64 print "-- Inserting data:"
65 print "-- an INSERT statement is used to insert a new row into"
66 print "-- a table. There are several ways you can specify what"
67 print "-- columns the data should go to."
68 print "-----------------------------"
70 print "-- 1. the simplest case is when the list of value correspond to"
71 print "-- the order of the columns specified in CREATE TABLE."
73 print "Sending query :"
74 print "INSERT INTO weather "
75 print " VALUES ('San Francisco', 46, 50, 0.25, '11/27/1994')"
76 pgcnx.query("""INSERT INTO weather
77 VALUES ('San Francisco', 46, 50, 0.25, '11/27/1994')""")
79 print "Sending query :"
80 print "INSERT INTO cities "
81 print " VALUES ('San Francisco', '(-194.0, 53.0)')"
82 pgcnx.query("""INSERT INTO cities
83 VALUES ('San Francisco', '(-194.0, 53.0)')""")
86 print "-- 2. you can also specify what column the values correspond "
87 print " to. (The columns can be specified in any order. You may "
88 print " also omit any number of columns. eg. unknown precipitation"
90 print "Sending query :"
91 print "INSERT INTO weather (city, temp_lo, temp_hi, prcp, date)"
92 print " VALUES ('San Francisco', 43, 57, 0.0, '11/29/1994')"
93 pgcnx.query("INSERT INTO weather (date, city, temp_hi, temp_lo)" \
94 "VALUES ('11/29/1994', 'Hayward', 54, 37)")
96 # direct selection commands
97 def select_data1(pgcnx):
98 print "-----------------------------"
99 print "-- Retrieving data:"
100 print "-- a SELECT statement is used for retrieving data. The "
101 print "-- basic syntax is:"
102 print "-- SELECT columns FROM tables WHERE predicates"
103 print "-----------------------------"
105 print "-- a simple one would be the query:"
106 print "SELECT * FROM weather"
108 print "The result is :"
109 q = pgcnx.query("SELECT * FROM weather")
112 print "-- you may also specify expressions in the target list (the "
113 print "-- 'AS column' specifies the column name of the result. It is "
114 print "-- optional.)"
116 print " SELECT city, (temp_hi+temp_lo)/2 AS temp_avg, date "
117 print " FROM weather"
119 print pgcnx.query("""SELECT city, (temp_hi+temp_lo)/2
120 AS temp_avg, date FROM weather""")
122 print "-- if you want to retrieve rows that satisfy certain condition"
123 print "-- (ie. a restriction), specify the condition in WHERE. The "
124 print "-- following retrieves the weather of San Francisco on rainy "
128 print "WHERE city = 'San Francisco' "
129 print " and prcp > 0.0"
130 print pgcnx.query("""SELECT * FROM weather WHERE city = 'San Francisco'
133 print "-- here is a more complicated one. Duplicates are removed when "
134 print "-- DISTINCT is specified. ORDER BY specifies the column to sort"
135 print "-- on. (Just to make sure the following won't confuse you, "
136 print "-- DISTINCT and ORDER BY can be used separately.)"
137 print "SELECT DISTINCT city"
139 print "ORDER BY city;"
140 print pgcnx.query("SELECT DISTINCT city FROM weather ORDER BY city")
142 # selection to a temporary table
143 def select_data2(pgcnx):
144 print "-----------------------------"
145 print "-- Retrieving data into other classes:"
146 print "-- a SELECT ... INTO statement can be used to retrieve "
147 print "-- data into another class."
148 print "-----------------------------"
151 print "SELECT * INTO TABLE temptab "
153 print "WHERE city = 'San Francisco' "
154 print " and prcp > 0.0"
155 pgcnx.query("""SELECT * INTO TABLE temptab FROM weather
156 WHERE city = 'San Francisco' and prcp > 0.0""")
157 print "Fills the table temptab, that can be listed with :"
158 print "SELECT * from temptab"
159 print pgcnx.query("SELECT * from temptab")
161 # aggregate creation commands
162 def create_aggregate(pgcnx):
163 print "-----------------------------"
164 print "-- Aggregates"
165 print "-----------------------------"
167 print "Let's consider the query :"
168 print "SELECT max(temp_lo)"
169 print "FROM weather;"
170 print pgcnx.query("SELECT max(temp_lo) FROM weather")
172 print "-- Aggregate with GROUP BY"
173 print "SELECT city, max(temp_lo)"
174 print "FROM weather "
175 print "GROUP BY city;"
176 print pgcnx.query( """SELECT city, max(temp_lo)
177 FROM weather GROUP BY city""")
179 # table join commands
180 def join_table(pgcnx):
181 print "-----------------------------"
182 print "-- Joining tables:"
183 print "-- queries can access multiple tables at once or access"
184 print "-- the same table in such a way that multiple instances"
185 print "-- of the table are being processed at the same time."
186 print "-----------------------------"
188 print "-- suppose we want to find all the records that are in the "
189 print "-- temperature range of other records. W1 and W2 are aliases "
190 print "--for weather."
192 print "SELECT W1.city, W1.temp_lo, W1.temp_hi, "
193 print " W2.city, W2.temp_lo, W2.temp_hi"
194 print "FROM weather W1, weather W2"
195 print "WHERE W1.temp_lo < W2.temp_lo "
196 print " and W1.temp_hi > W2.temp_hi"
198 print pgcnx.query("""SELECT W1.city, W1.temp_lo, W1.temp_hi,
199 W2.city, W2.temp_lo, W2.temp_hi FROM weather W1, weather W2
200 WHERE W1.temp_lo < W2.temp_lo and W1.temp_hi > W2.temp_hi""")
202 print "-- let's join two tables. The following joins the weather table"
203 print "-- and the cities table."
205 print "SELECT city, location, prcp, date"
206 print "FROM weather, cities"
207 print "WHERE name = city"
209 print pgcnx.query("""SELECT city, location, prcp, date FROM weather, cities
210 WHERE name = city""")
212 print "-- since the column names are all different, we don't have to "
213 print "-- specify the table name. If you want to be clear, you can do "
214 print "-- the following. They give identical results, of course."
216 print "SELECT w.city, c.location, w.prcp, w.date"
217 print "FROM weather w, cities c"
218 print "WHERE c.name = w.city;"
220 print pgcnx.query("""SELECT w.city, c.location, w.prcp, w.date
221 FROM weather w, cities c WHERE c.name = w.city""")
223 # data updating commands
224 def update_data(pgcnx):
225 print "-----------------------------"
226 print "-- Updating data:"
227 print "-- an UPDATE statement is used for updating data. "
228 print "-----------------------------"
230 print "-- suppose you discover the temperature readings are all off by"
231 print "-- 2 degrees as of Nov 28, you may update the data as follow:"
233 print "UPDATE weather"
234 print " SET temp_hi = temp_hi - 2, temp_lo = temp_lo - 2"
235 print " WHERE date > '11/28/1994'"
237 pgcnx.query("""UPDATE weather
238 SET temp_hi = temp_hi - 2, temp_lo = temp_lo - 2
239 WHERE date > '11/28/1994'""")
241 print "SELECT * from weather"
242 print pgcnx.query("SELECT * from weather")
244 # data deletion commands
245 def delete_data(pgcnx):
246 print "-----------------------------"
247 print "-- Deleting data:"
248 print "-- a DELETE statement is used for deleting rows from a "
250 print "-----------------------------"
252 print "-- suppose you are no longer interested in the weather of "
253 print "-- Hayward, you can do the following to delete those rows from"
256 print "DELETE FROM weather WHERE city = 'Hayward'"
257 pgcnx.query("DELETE FROM weather WHERE city = 'Hayward'")
259 print "SELECT * from weather"
261 print pgcnx.query("SELECT * from weather")
263 print "-- you can also delete all the rows in a table by doing the "
264 print "-- following. (This is different from DROP TABLE which removes "
265 print "-- the table in addition to the removing the rows.)"
267 print "DELETE FROM weather"
268 pgcnx.query("DELETE FROM weather")
270 print "SELECT * from weather"
271 print pgcnx.query("SELECT * from weather")
273 # table removal commands
274 def remove_table(pgcnx):
275 print "-----------------------------"
276 print "-- Removing the tables:"
277 print "-- DROP TABLE is used to remove tables. After you have"
278 print "-- done this, you can no longer use those tables."
279 print "-----------------------------"
281 print "DROP TABLE weather, cities, temptab"
282 pgcnx.query("DROP TABLE weather, cities, temptab")
292 create_aggregate(pgcnx)