You are on page 1of 14

NEBC Database Course PostgreSQL Cheat-sheet v2

December 2008
For each example, replace mytable and mycol with your own table and column names. The
new element in each example is highlighted in bold.
SELECT
Command

What it does

SELECT * from mytable

get all entries

SELECT DISTINCT * FROM mytable

get all unique entries

SELECT mycol1, mycol2 FROM table

get only columns mycol1 and mycol2

SELECT mycol1 AS foo FROM mytable

get mycol1, but call it foo in the results

SELECT * FROM mytable ORDER BY mycol1 ASC, mycol2 DESC

sort by mycol1 if 2 rows have the same value here then


sort these by mycol2 in reverse order

SELECT * FROM mytable WHERE mycol1 = mycol2

a simple search condition based on equality

SELECT * FROM mytable WHERE mycol1 = 5 OR

find all rows where mycol1 is 5, or where mycol1 is 6 but


also mycol2 contains 'snake', 'Snake', 'sNAke' etc.

( mycol1 = 6 AND lower(mycol2) = 'snake' )


SELECT * FROM table WHERE mycol1 IS NULL

searching for NULL values with 'IS NULL'

SELECT * FROM mytable WHERE mycol1 IN (3, 4, 5)

specify that col1 must be 3, 4 or 5

SELECT * FROM mytable1 WHERE mycol1 IN

obtain the list of matches from col2 in table2

(SELECT mycol2 FROM mytable2)


SELECT * FROM my table1 t1 WHERE EXISTS
(SELECT * FROM mytable2 t2 WHERE t2.mycol2 = t1.mycol1)
SELECT t1.*, t2.* FROM mytable1 t1 INNER JOIN mytable2 t2 ON
(t1.pk_col = t2.fk_col)
SELECT t1.*, t2.* FROM mytable1 t1 LEFT OUTER JOIN mytable2 t2 ON
(t1.pk_col = t2.fk_col)
SELECT mycol1 as foo, mycol2 AS bar FROM mytable1
UNION
SELECT mycol1 as foo, mycol3 AS bar FROM mytable2

same as the previous, but using the EXISTS clause.


Choose whichever you find easiest!
inner join, where tables 1 and 2 have a one-to-many
relationship
an outer join where columns from table 1 will be
displayed even if there is no matching entry in table 2
combine two SELECTS into a single result set note the
SELECT keyword appears twice, but the ORDER BY
affects the whole result. Duplicate rows are not shown.
Use 'UNION ALL' to show all duplicate rows

ORDER BY foo
SELECT mycol1 as foo, mycol2 AS bar FROM mytable1
INTERSECT

Shows all rows common to two SELECT statements.


'INTERSECT ALL' will show all duplicate rows

SELECT mycol1 as foo, mycol3 AS bar FROM mytable2


ORDER BY foo
SELECT mycol1, sum(mycol2) FROM mytable1
WHERE mycol3 = 1

group entries in table1 by col1, showing each value of


col1 as well as the sum of col2 for those rows

GROUP BY mycol1 HAVING count(*) < 3

disregard rows where col3 is not 1, and show only results


with 1 or 2 occurrences of that value of col1 in the table

SELECT * INTO mynewtable FROM myoldtable

Create newtable from oldtable

DELETE, INSERT, UPDATE


Command

What it does

DELETE FROM mytable

delete EVERYTHING in a table

DELETE FROM mytable WHERE mycol1 != 5

delete by some condition

INSERT INTO mytable (mycol1, mycol2) VALUES ('foo', 'bar')

insert with specific values

INSERT INTO mytable2 SELECT mycol1, mycol2 FROM table1

insert values based on a SELECT statement

UPDATE mytable

update with WHERE condition

SET mycol1 = 'foo', mycol2 = mycol2 * mycol2


WHERE mycol3 IS NOT NULL

OPERATORS AND FUNCTIONS


Command

What it does

SELECT (mycol1 / mycol2) *100 AS percentage FROM mytable

perform some arithmetic on the columns (other


mathematical operators include + and -)

SELECT sqrt(mycol1) FROM mytable

Select the square root of mycol1

SELECT trunc(mycol1, 3) FROM mytable

Truncate the value of mycol3 after 3 decimal points

SELECT abs(mycol), round(mycol,2), ln(mycol1), sin(mycol), tan(mycol)

Absolute value of mycol,round mycol to 2 decimal


places, natural log mycol,sine of mycol,tangent of mycol

FROM mytable

See documentation for further mathematical functions


SELECT mycol1 || ' and ' || mycol2 FROM mytable

Concatenate mycol1 to mycol2 with the word 'and'

SELECT substr(mycol1, 2, 3) FROM mytable

Select substring of mycol1 starting at character 2, 3


characters in length

SELECT upper(mycol1) FROM mytable

Display mycol1 in upper case

SELECT lower(mycol1) FROM mytable

Display mycol1 in lower case

SELECT * FROM mytable WHERE mycol1 = 'badger'

Select rows where mycol1 exactly matches 'badger'

SELECT * FROM mytable WHERE mycol1 != 'badger'

Select rows where mycol1 does not match 'badger'

SELECT * FROM mytable WHERE mycol1 LIKE '%adg%'

Select rows where mycol1 contains the string 'adg' (note


use of '%' wildcard character)

SELECT sum(mycol1), avg(mycol1) FROM mytable

return both sum and average of mycol1

SELECT count(*) FROM mytable

Count the number of rows in specified table

SELECT mycol1, sum(mycol2) FROM mytable

group entries in mytable by mycol1, showing each value


of mycol1 as well as the sum of mycol2 for those rows

WHERE mycol3 = 1
GROUP BY mycol1 HAVING count(*) < 3

disregard rows where mycol3 is not 1, and show only


results with 1 or 2 occurrences of that value of mycol1

SELECT current_timestamp, now()

Two ways to display the current date and time

SELECT to_char(mydatecol,'DD/MM/YYYY') FROM mytable

Select mydatecol in the format


DD/MM/YYYY(eg.21/04/2008)

SELECT to_date('200425thJune','YYYYDDthmonth')

Convert the string '200425thJune' to a date

SELECT mydatecol::text FROM mytable1

Typecast date values explicitly to data type varchar

SELECT coalesce(mycol1::text, 'No value') FROM mytable1

Display 'No value' if value in mydf -h


col1 is null

SELECT CASE WHEN mycol1 = true THEN 'badger' ELSE 'mushroom' END
FROM mytable1

If boolean value in mycol1 is true print 'badger' otherwise


print 'mushroom'

Data Types
Data Type

Description

integer,int,int4

Whole number/integer

float

Floating point number

numeric(p,s)

Exact numeric type with total digits 'p' and digits after
decimal point 's'

date

Calender date

timestamp

Date and time

varchar(n), character varying(n)

Variable length character string of max length 'n'

char(n)

Fixed length character string of length 'n'

text

Variable length character of unlimited length

boolean, bool

A single true or false value (supported values:


true/false,'t'/'f','true'/'false','y'/'n','yes'/'no','1','0')

 
 

 




  
 
  
! 
  #   
 
 
 


% &     
   
&
 %

#
( 


% &
))   
+ 
 
&))
(    
 + , %   
  ,
.( /
  %
!    010 0.0&

     %
 
#
 % +  #


 2  ! 

# 2 
&
   
  
 

#   0 0 ! 
 0&&&(0+  &
3( 45 !% !  +  !#! + %

 % 67
+ 60%
0
1

 
   
 
 ! !
 +   
!   % 67(&
8 
 !
! ,, 2  + 
9
8 
   +  %   
 !% 9
:( ! #   % ! , % 67;&8   
9
7(  +  !# 
44#  <5= %
8 
 44 +    9
>(? !
  
  #
    
9

? +  , )(&&&     


+ ! 
 
     !
+  &
( 4 
   +%
 .;  &
( 
% 
 !0
 &
(< +  !#!    9
+
 00
  <5=
  
 <5= % 8?5=4 % <5=% (

#


 # %    


  #! !     &

 
 

 

M Day 1 : Advanced Querying

  


   

 
 

 
!

 
 #
   %   

      



&  
 
 


# 
 

( 
 
   
 #) 
  
 
 
!  
+ 
      
 #) 
  
 

  % 
  & 
 ,  % 
  %
 
.  / %% 
   % #   

 
 0
     & 1&0 
2034&5%   6 %  %

7  
    
0 
   

 
  % #! % 
 %  
# 

  8
9  
  
0 
  % # 

     
:      # #
 ; 

<   # 

  
)= 

6 
 >3/

?!  
      %2   
   

  
#  
  

;!
 
    

 6
 


 
 

 

  


  

 




 

   !  

 
#%
#!
!
!
%!

    


    
   
  &
    
   
        
  ( 
!
)

 

   (
)     
    

)  
 
     

+  #,+
+ 

  

 (  

 
 

!+  
     

  
  

        
 
  !
 
 
      .. 
. !
   
 
 
     

  
     
 
      
+  , 
   
  
 
!    (   
 


     (     
!

(    
      


   


       
  

        /
!0
(   

  
         
     
 

  

!
     (  
   
 
   !
1 

   2   (   


 
!

+  ,3

4(  55

! 

! ! (5 ( 


 
55!6

  .  



 
  (    
   

   
          

  


 
 
 
 

   

!&   



           


     !
0


     
     !
+     
  
 (     

  

!
7    

 


  !  
     !0    
   
  

     

 
   8

       


     
4 .
  
6!
 
 
  
 
  
        
   
 
  
!

+  %, 


  

  9
 
   

  !
 ,

   !
1      
:
   
 

   

   !
  
   (
 
  

 . 


 
   
     
!
   


  
!+   
   

   !
3                
  !


      

    
 
  !  

  

    

!
( 

   

 
 
    
 

 !
;    
 
       
  
!
    !

  
       (    <       
  

 
 !
  (         
 


( !




    
   !
  .
      (
( 







= 

>?>>>>

##>>>>

#>>>> 3 = 

  

>?#>>

###>>

##>>

)
 ; :

#>>>>

#>>>

#%>>>

#

##>>>

#>>>

#>>>

#/


 

##%>>

#%>>

#%>>

>

 ((

#>>>>

#>>>>

#/>>>>

 

#%>>>>

#>>>>

#>>>>

 

##>>>>

#>>>>

#/>>>> 3  

 ((

#>>>>

#%>>>>

#>>>>

#>


 

##>>

##>>

#?#>>

#%>>>

#%>>>

#?%>>>

)
 ; :

#%>>>

#>>>

>>>>



  

#%>>

#/%>>

#%>>

>

= 

#>>>>

#>>>>

>>>>

 
 

 

    

    
  ! !    #    
   
 %  

&

(   # 



    
 


    
) 

  # 

     

( 


(    +


  



 
   !  
  #

 
 
       
!    # #
%&&&     ! 
 !! ! 
!     (  
 

 
 %
! &#  ((((##
&#
 &  )   &   &
)&  ! +  (
! 
 ,
 
 
 ++     +   + 
+++
  +    + 
+++ 
  &    +&
!  #
 ,#
&  ! +  (

 (
 ! !(
! #. !& &#( 
#/  (#
 

 !  # ./ 0 # ! #

+ 0#     
 ++     +   + 
+++
  +    + 
+++ 
  &    +&
0  ! 
  
 
  1  #2# # 31#   4
 
 
 

      &  &  &&   &  
 &&
! &&   

 &   &     &
!  1 #02#

 


      &  &  &&   &  
 &&
! 3   

 &   &     &
!  1 #02#
 &&

5   ! 1    



  


   6
 

      &  &  &&
  &    &&
!  456
) 
 

 +&  +   &  & 
+&&
  &    &&
! + 456
7   ! 1  
 
! 
 

      &  &  &&
  &    &&
!  456
 

 

 +&  +   &  & 
+&&
  &    &&
! + 456

8 
 
 ( !9  :!  
 
+;<


4
 =>/

 
7+&78    
99
7+&:  8 
  
)       
 
)  +&  +&  
+&
 
)+    +   

+ 
 
)8   8     8 

 +80   ++      8  
9  / )  ;    +8  9   80
9  8   ;0  8;0
 
   99    7 99
 +/ 

 
#< #    5   :  99  + 

) 

 
#  #       5  99  +&

) 

 
#  #       5  99  

) 

 
# #    8    5  99   !
8  = 5

) 

 
# #    5   8   99   !
8  > 5
  8 

?   


 (( 
 
!  & 
   +&
 &  
 
& % + 



  
     
 
    !
# 
  
 !
%&

SITE

Found at

SWORD

()  
+,./ / 

       !

  
    !

   !
(
0 0 00!    
   
     !+ 
  
  !
&

EMPLOYEE

CAR

RENTAL

NAMED_DRIVER

 / # 


12,  /  / 
)2 / . / / ./  /  
 /(3 4 / / /  &. / .
 
+

    )2



/  !
(   
#  )2  
 /


15      15 !
6
    
/  789   

& )   !      
   #       !) 
 #

, / / / / .  .


:     #    !
( 
; ; ; ;
   <
!, 

/ /
 =22 
>
+
    !)#  
 

   !
   .  .
+,   .  .
)      ; !

    !)   

!
(? 
..  

#
# 
+


   #
  4

  >&!)  # 

   
!+ 
<
      !
! , 
 
 0 
0!)
  
    
  !  
    <
  <
 #   
<
 !( 
  ;    
   
!



ROUTE

runs on

SERVICE

stops at
STOP

TOWN

located in
between 2

SPECIAL_PRICE

has a

DEPOT

between 2

TIME

FARE

 )( 6         


    !

 
   
 

      
        
   
  
  
  
  ! #
 %  & #()+,

  & #()+,

  & #()+,
    +,
+./ %/012 1# % )
)3
 
& 
  ! 
& #
 
 & #4()+,

& %  & #()+,
 %    & #()+,
+./ %
& /012 1#
& % )
)3
    
     
      
& &    
  5
  !  #

& %  & #()+,
% %  & #()+,
 %   +,
& %    +,
+./% %& %  6 2##& %  789))
+./ % /012 1#% %  %  )
+./% %
& % + /:2 1#
& % )    .
& #
& % )
+./% %% % + /:2 1#% % )    .# % )
)3
;    
      
   &     
   5
  !  
% #
% %  & #()+,
 %   +,

& %  & #()+,
+./ % 
% /012 1#% %  %  
& % )
+./% 
% %
& % + /:2 1#
& % )    .
& #
& % )
+./% 
% %% % + /:2 1#% % )    .# % )
)3