Numberedheadings | |||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| |||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
Note keywords or statements like SELECT, FROM and WHERE are not case case sensitive (SELECT = select = SeLecT), but by convention we use uppercase for all SQL keywords in order to make queries easier to read. Queries can be composed as a single line, or spread over a number of lines to ease reading. A semicolon ( ; ) is used to signal to PostgreSQL the end of an SQL statement.
Single Quotes quotes contain string values e.g. name = ‘Epsom’. Only use these with string data types such as text and character varying.
String values are case sensitive so SELECT * FROM general settlement WHERE name like 'Epsom';
and SELECT * FROM general settlement WHERE name like 'ePsOm';
will produce different results. If the string itself includes a quote, replace the single quotes with $$, e.g. name = $$St.
David’s$$David's$$
Double quote quotes must enclose database object names that:
include a space
use upper case characters
use ‘special’ characters like punctuation
are a reserved SQL word
Open pgAdmin and explore the hierarchy of tables within schemas of your training database
Identify the school table within the general schema
Click on the SQL tab and note SQL commands necessary to create the table
Right-click > school > View/Edit Data > First 100 Rows to display all the data for the first 100 records within the school table
SELECT
. The syntax is as follows
SELECT
[select_list]FROM
[table_name];
[select_list] can be a single column
,or a list of columns
from the table you want to retrieve data from. A comma ( , ), where a comma is used to separate the individual columns.
If you want toTo return all columns of the table
you can, use an asterisk ( * ) in place of [select_list]. The [select_list] may also contain an expressions or literal values.
The FROM clause
is optional andspecifies the name of the table from which you want to
queryselect data
.The SELECT statement can be used to form incredibly flexible queries extended by including additional clauses:
Select distinct rows using
DISTINCT
operator.Sort rows using
ORDER BY
clause.Filter rows using
WHERE
clause.Select a subset of rows from a table using
LIMIT
orFETCH
clause.Group rows into groups using
GROUP BY
clause.Filter groups using
HAVING
clause.Join with other tables using joins such as
INNER JOIN
,LEFT JOIN
,FULL OUTER JOIN
,CROSS JOIN
clauses.Perform set operations using
UNION
,INTERSECT
, andEXCEPT
.
Retrieve data from a table
Examine the structure of the general.school table in pgAdmin
Open the Query Tool
Compose a query
to return the name of the school, postcode, and phase of education then, Execute (F5 or play button), for example
SELECT "EstablishmentName","Postcode","PhaseOfEducation (name)"
FROM general.school;
Try different variation of column names, noting the order of the the column names in the query
impacts the
sequence of columns in the results
SELECT DISTINCT
The DISTINCT clause is used in a SELECT statement to remove duplicate values. It can be applied to one or more columns in the [select_list]. The DISTINCT clause is often used with the COUNT() function in order to determine the quantity of records of a particular type
sql[select_list] can be a single column, or a list of columns from the table
COUNT() function can be used to determine number of records
The keyword AS can be used to set a column alias which is more meaningful to the reader
Exercise - use of SELECT DISTINCT
a table.
Retrieve unique values from a table
In the Query Tool compose a query to produce a list of wards
The the COUNT() function to determine how many records meet this condition
Use the AS keyword to give the column a sensible name, note you made need to put this in double quotes if you are including spaces of
in the general.school table, with no duplicates
SELECT DISTINCT "administrativeward (name)" AS "Ward" FROM general.school;
Sorting results
The ORDER BY clause allows you to sort rows returned by a SELECT clause in ascending or descending order using ASC or DESC options. It is possible to sort based on multiple columns by separating expressions with a comma ( , ).
The syntax employed follows this format;
sqlExercise - ORDER BY
In your query window amend your previous query to add an ORDER BY clauseSort data
Create a query to list all schools by Trust, in order of largest capacity down to smallest
Try sorting in ascending and descending order
SELECT "Trusts (name)","EstablishmentName", "SchoolCapacity" FROM general.school ORDER BY "Trusts (name)" ASC, "SchoolCapacity" DESC;
Note you can
sort by more than one column
WHERE
Operator | Description | =Operator | EqualDescription | ||
---|---|---|---|---|---|
> | Greater than | ||||
< | Less than | ||||
>= | Greater than or equal | ||||
<= | Less than or equalOperator | Description | |||
= | Equal | <> or != | Not equal | ||
AND | Logical operator AND | ||||
OR | Logical operator OR | ||||
Return true if a value matches any value in a list | Return true if a value is between a range of values | ||||
> | Greater than | AND | Logical operator AND | Return true if a value matches a pattern | |
< | Less than | OR | Logical operator OR | Return true if a value is NULL | |
>= | Greater than or equal | Return true if a value matches any value in a list | NOT | Negate the result of other operators |
Exerci
In your query window amend your previous query to add a WHERE clause
Which school has an establishment_number of 7014 (WHERE establishment_number='7014')
<= | Less than or equal |
Identify records that meet conditions
Run the following query, to answer the question ‘which current schools have the DFEE code of 6386’?
SELECT "EstablishmentNumber","EstablishmentName","EstablishmentStatus (name)"
FROM general.school
WHERE "EstablishmentNumber" = 6386 AND "EstablishmentStatus (name)" like 'Open';
Write a new query to list all the primary schools in the parliamentary constituency of Guildford
Write a query to identify all primary schools that
LIMIT
LIMIT is an option clause of the SELECT statement that constrains the number of rows returned by the query. This is useful as it provides a sample of the data and with large data sets generally executes quicker than without the clause.
You can optionally use the ORDER BY clause to return the first or last records in a series e.g. the largest or smallest values.
Optionally you can also use the OFFSET clause to start from the nth record.
sqlSQL in QGIS
pgAdmin has a query window to use for interaction with the database with user-defined SQL. You can access it through the Tools menu or the right click menu.
Name
Description
character varying(n), varchar(n)
variable-length with limit
character(n), char(n)
fixed-length, blank padded
text
are currently open and have a capacity between 300 and 500
SQL in QGIS
QGIS can be used as an alternative interface to pgAdmin for running SQL queries.
Display the distribution of data
Launch QGIS and open the SQL Window in the DB Manager
Run the last query above in the the DB Manager, then ensure Load as new layer is checked, and Execute
The result of the query will be shown on the map