0% found this document useful (0 votes)
9 views21 pages

CS232L-Lab#02

The document provides an overview of PostgreSQL, focusing on the WHERE clause and its usage in SQL statements, including arithmetic, logical, and comparison operators. It also covers the use of NULL values, column aliases, DISTINCT clause, and commands for updating, deleting, dropping, and truncating tables. The document includes examples and instructions for practicing these commands in a lab setting.

Uploaded by

bushrahzulfiqar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views21 pages

CS232L-Lab#02

The document provides an overview of PostgreSQL, focusing on the WHERE clause and its usage in SQL statements, including arithmetic, logical, and comparison operators. It also covers the use of NULL values, column aliases, DISTINCT clause, and commands for updating, deleting, dropping, and truncating tables. The document includes examples and instructions for practicing these commands in a lab setting.

Uploaded by

bushrahzulfiqar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

CS232L – Database Management System

INTRO TO DBMS AND


POSTGRESQL

Ghulam Ishaq Khan Institute of Engineering


Sciences
CS232-L – LAB 2

Faculty of Computer Science & Engineering

CS232L – Database Management system Lab

Lab 2 –Clauses and Basic Operations on PostgreSQL Data

Objective
The objective of this session is to

 PostgreSQL WHERE clause overview


 Perform the Arithmetic Operations on PostgreSQL Data using Where Clause
 Use the Logical and Comparison operators in SQL statements.
 Null Value, defining a Column alias, DISTINCT clause, IS NULL operator
 Using the update query
 Use of delete, drop and truncate.

Instructions
 Open the handout/lab manual in front of a computer in the lab during the session.
 Practice each new command by completing the examples and exercise.
 Turn-in the answers for all the exercise problems as your lab report.
 When answering problems, indicate the commands you entered and the output displayed.

1
CS232-L – LAB 2

PostgreSQL WHERE clause overview


The SELECT statement returns all rows from one or more columns in a table. To select rows
that satisfy a specified condition, you use a WHERE clause.

The syntax of the PostgreSQL WHERE clause is as follows:

The WHERE clause appears right after the FROM clause of the SELECT statement.
The WHERE clause uses the condition to filter the rows returned from the SELECT clause.

The condition must evaluate to true, false, or unknown. It can be a boolean expression or a
combination of boolean expressions using the AND and OR operators.

The query returns only rows that satisfy the condition in the WHERE clause. In other words,
only rows that cause the condition evaluates to true will be included in the result set.

PostgreSQL evaluates the WHERE clause after the FROM clause and before the SELECT:

If you use column aliases in the SELECT clause, you cannot use them in the WHERE clause.

Besides the SELECT statement, you can use the WHERE clause in
the UPDATE and DELETE statement to specify rows to be updated or deleted.

PostgreSQL Arithmetic Operators


You may need to modify the way in which data is displayed, perform calculation, or look at
what-if scenarios. This is possible using arithmetic expressions. An arithmetic expression may
contain column names, constant numeric values, and the arithmetic operators.
PostgreSQL provided many Mathematical operators for common mathematical conventions.
List of arithmetic operators available in SQL are Addition (+), Subtraction (-), Multiplication
(*), Division (/). You can use arithmetic operators in any clause of a SQL statement except
the FROM clause. If an arithmetic expression contains more than one operator then
multiplication and division are evaluated first. If operators within an expression are of same
priority, then evaluation is done from left to right. You can use parentheses to force the
expression within parentheses to be evaluated first.

2
CS232-L – LAB 2

PostgreSQL Arithmetic operator example

PostgreSQL Logical Operators


A logical operator combines the result of two component conditions to produce a single
result based on them or to invert the result of a single condition. Three logical operators are
available in PostgreSQL.
• AND Returns TRUE if both component conditions are TRUE
• OR Returns TRUE if either component condition is TRUE
• NOT negate the result of other operators

3
CS232-L – LAB 2

Using WHERE clause with the AND operator example


We will use the customer table

The following example finds customers whose first name and last name are Jamie and rice by
using the AND logical operator to combine two Boolean expressions:

Output:

Using the WHERE clause with the OR operator example


This example finds the customers whose last name is Rodriguez or first name is Adam by
using the OR operator:

Output:

You can use several conditions in one WHERE clause using the AND and OR operators.

4
CS232-L – LAB 2

Let’s suppose we have an Employee Table then the query given above will return the
employee number , employee name , job and salalry form employee table where the salary of
the employee is greater than and equal to 1100 and job title is ’CLERK’.

PostgreSQL Comparison Operators


Comparison operators are used in conditions that compare one expression to another. The
operators are

Using WHERE clause with the equal (=) operator example


The following statement uses the WHERE clause customers whose first names are Jamie:

Output:

5
CS232-L – LAB 2

Using the WHERE clause with the not equal operator (<>) example
This example finds customers whose first names are Brand or Brandy and last names are
not Motley:

Output:

Other Comparison Operators:


Other comparison operators are

Using WHERE clause with the IN operator example

If you want to match a string with any string in a list, you can use the IN operator.

For example, the following statement returns customers whose first name is Ann, or Anne,
or Annie:

Output:

6
CS232-L – LAB 2

Using the WHERE clause with the LIKE operator example


To find a string that matches a specified pattern, you use the LIKE operator. The following
example returns all customers whose first names start with the string Ann:

Output:

The % is called a wildcard that matches any string. The 'Ann%' pattern matches any string
that starts with 'Ann'.
Using the WHERE clause with the BETWEEN operator example

The following example finds customers whose first names start with the letter A and contains
3 to 5 characters by using the BETWEEN operator.

The BETWEEN operator returns true if a value is in a range of values.

7
CS232-L – LAB 2

In this example, we used the LENGTH() function gets the number of characters of an input
string.

Null value
If a row lacks the data value for a particular column, that value is said to be null, or to contain
null. A null value is a value that is unavailable, unassigned, unknown, or inapplicable. A null
value is not the same as zero or a space. Zero is a number and space is a character. If any
column value in an arithmetic expression is null, the result is null. For example if you attempt
to perform division with zero, you get an error. However if you divide a number by null, the
result is a null or unknown.

PostgreSQL Column Alias

A column alias allows you to assign a column or an expression in the select list of
a SELECT statement a temporary name. The column alias exists temporarily during the
execution of the query.

The following illustrates the syntax of using a column alias:

8
CS232-L – LAB 2

In this syntax, the column_name is assigned an alias alias_name. The AS keyword is optional
so you can omit it like this:

The following syntax illustrates how to set an alias for an expression in the SELECT clause:

The main purpose of column aliases is to make the headings of the output of a query more
meaningful.

PostgreSQL column alias examples


Assigning a column alias to a column example
If you want to retrieve first_name and last_name and rename the last_name heading, you can
assign it a new name using a column alias like this:

This query assigned the surname as the alias of the last_name column:

9
CS232-L – LAB 2

Or you can make it shorter by removing the AS keyword as follows:

Column aliases that contain spaces


If a column alias contains one or more spaces, you need to surround it with double quotes like
this:

PostgreSQL SELECT DISTINCT

The DISTINCT clause is used in the SELECT statement to remove duplicate rows from a
result set. The DISTINCT clause keeps one row for each group of duplicates.
The DISTINCTclause can be applied to one or more columns in the select list of
the SELECT statement.

The following illustrates the syntax of the DISTINCT clause:

In this statement, the values in the column1 column are used to evaluate the duplicate.

If you specify multiple columns, the DISTINCT clause will evaluate the duplicate based on
the combination of values of these columns.

10
CS232-L – LAB 2

PostgreSQL SELECT DISTINCT examples

Let’s create a new table called distinct_demo and insert data into it for practicing
the DISTINCT clause.
First, use the following CREATE TABLE statement to create the distinct_demo table that
consists of three columns: id, bcolor and fcolor.

Second, insert some rows into the distinct_demo table using the following INSERT statement:

Third, query the data from the distinct_demo table using the SELECT statement:

Output:

11
CS232-L – LAB 2

PostgreSQL IS NULL operator

In the database world, NULL means missing information or not applicable. NULL is not a
value, therefore, you cannot compare it with any other values like numbers or strings. The
comparison of NULL with a value will always result in NULL, which means an unknown
result.

In addition, NULL is not equal to NULL so the following expression returns NULL:

NULL = NULL

Assuming that you have a contacts table that stores the first name, last name, email, and
phone number of contacts. At the time of recording the contact, you may not know the
contact’s phone number.

To deal with this, you define the phone column as a nullable column and insert NULL into
the phone column when you save the contact information.

The following statement inserts two contacts, one has a phone number and the other does not:

12
CS232-L – LAB 2

To find the contact who does not have a phone number you may come up with the following
statement:

The statement returns no row. This is because the expression phone = NULL in
the WHERE clause always returns false.

Even though there is a NULL in the phone column, the expression NULL = NULL returns
false. This is because NULL is not equal to any value even itself.

To check whether a value is NULL or not, you use the IS NULL operator instead:

value IS NULL

The expression returns true if the value is NULL or false if it is not.

So to get the contact who does not have any phone number stored in the phone column, you
use the following statement instead:

Here is the output:

13
CS232-L – LAB 2

PostgreSQL UPDATE
The PostgreSQL UPDATE statement allows you to modify data in a table. The following
illustrates the syntax of the UPDATE statement:

UPDATE table_name
SET column1 = value1,
column2 = value2,
...
WHERE condition;

In this syntax:

 First, specify the name of the table that you want to update data after
the UPDATE keyword.
 Second, specify columns and their new values after SET keyword. The columns that
do not appear in the SET clause retain their original values.
 Third, determine which rows to update in the condition of the WHERE clause.

The WHERE clause is optional. If you omit the WHERE clause, the UPDATE statement will
update all rows in the table.

When the UPDATE statement is executed successfully, it returns the following command tag:

UPDATE count
The count is the number of rows updated including rows whose values did not change.
PostgreSQL UPDATE examples
Let’s take some examples of using the PostgreSQL UPDATE statement.

The following statements create a table called courses and insert some data into it:

The following statement returns the data from the courses table:
SELECT * FROM courses;

14
CS232-L – LAB 2

PostgreSQL UPDATE – updating one row

The following statement uses the UPDATE statement to update the course with id 3. It
changes the published_date from NULL to '2020-08-01'.

The DELETE Statement


The DELETE statement is used to delete rows in a table.

Delete All Rows


It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
Syntax:
15
CS232-L – LAB 2

DELETE FROM table table_name;


Or
DELETE * FROM table table_name;

PostgreSQL DROP TABLE

To drop a table from the database, you use the DROP TABLE statement as follows:

DROP TABLE [IF EXISTS] table_name ;

In this syntax:

 First, specify the name of the table that you want to drop after the DROP
TABLE keywords.
 Second, use the IF EXISTS option to remove the table only if it exists.

If you remove a table that does not exist, PostgreSQL issues an error. To avoid this situation,
you can use the IF EXISTS option.

In case the table that you want to remove is used in other objects such as views, triggers,
functions, and stored procedures, the DROP TABLE cannot remove the table. In this case,
you have two options:

 The CASCADE option allows you to remove the table and its dependent objects.
 The RESTRICT option rejects the removal if there is any object depends on the table.
The RESTRICT option is the default if you don’t explicitly specify it in the DROP
TABLE statement.

To remove multiple tables at once, you can place a comma-separated list of tables after
the DROP TABLE keywords:

DROP TABLE [IF EXISTS]


table_name_1,
table_name_2,
...
[CASCADE | RESTRICT];
Note that you need to have the roles of the superuser, schema owner, or table owner in order
to drop tables.
PostgreSQL DROP TABLE examples

Let’s take some examples of using the PostgreSQL DROP TABLE statement

16
CS232-L – LAB 2

2) Drop a table that has dependent objects

The following creates new tables called authors and pages:

17
CS232-L – LAB 2

PostgreSQL TRUNCATE TABLE

To remove all data from a table, you use the DELETE statement. However, when you use
the DELETE statement to delete all data from a table that has a lot of data, it is not efficient.
In this case, you need to use the TRUNCATE TABLE statement:

TRUNCATE TABLE table_name;

The TRUNCATE TABLE statement deletes all data from a table without scanning it. This is
the reason why it is faster than the DELETE statement.

18
CS232-L – LAB 2

Remove all data from one table

The simplest form of the TRUNCATE TABLE statement is as follows:

TRUNCATE TABLE table_name;


Code language: SQL (Structured Query Language) (sql)

The following example uses the TRUNCATE TABLE statement to delete all data from
the invoices table:

TRUNCATE TABLE invoices;


Remove all data from multiple tables

To remove all data from multiple tables at once, you separate each table by a comma (,) as
follows:

TRUNCATE TABLE
table_name1,
table_name2,
...;
Code language: SQL (Structured Query Language) (sql)

For example, the following statement removes all data from invoices and customers tables:

TRUNCATE TABLE invoices, customers;


Remove all data from a table that has foreign key references

In practice, the table you want to truncate often has the foreign key references from other
tables that are not listed in the TRUNCATE TABLE statement.

By default, the TRUNCATE TABLE statement does not remove any data from the table that
has foreign key references.

To remove data from a table and other tables that have foreign key reference the table, you
use CASCADE option in the TRUNCATE TABLE statement as follows :

TRUNCATE TABLE table_name


CASCADE;
Code language: SQL (Structured Query Language) (sql)

The following example deletes data from the invoices table and other tables that reference
the invoices table via foreign key constraints:

TRUNCATE TABLE invoices CASCADE;


Code language: SQL (Structured Query Language) (sql)

The CASCADE option should be used with further consideration or you may potentially
delete data from tables that you did not want.

19
CS232-L – LAB 2

By default, the TRUNCATE TABLE statement uses the RESTRICT option which prevents
you from truncating the table that has foreign key constraint references.

20

You might also like