0% found this document useful (0 votes)
16 views62 pages

Lecture 4

Uploaded by

animkiyoko
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)
16 views62 pages

Lecture 4

Uploaded by

animkiyoko
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/ 62

Lecture 4

Data Types in PostgreSQL. DML.


DQL. Functions. Filtering Data.
Conditional Expressions &
Operators.

Senior Lecturer: Tulebayev Yersultan


Data Types in PostgreSQL. DML. DQL.
Functions. Filtering Data. Conditional
Expressions & Operators.

PART I. Data Types in PostgreSQL.


PART II. Data Manipulation Language. DQL.
PART III. String Functions. Filtering Data.
Conditional Expressions & Operators.
PART I. Data Types in PostgreSQL.
PostgreSQL Data Types
• Boolean
• Character types such as char, varchar, and text.
• Numeric types such as integer and floating-point number.
• Temporal types such as date, time, timestamp, and interval UUID for
storing Universally Unique Identifiers
• Array for storing array strings, numbers, etc.
• JSON stores JSON data
• hstore stores key-value pair
• Special types such as network address and geometric data.
Boolean
A Boolean data type can hold one of three possible values: true,
false and NULL. You use boolean or bool keyword to declare a
column with the Boolean data type.
Character
The following table illustrate the character types in PostgreSQL:
Numeric
PostgreSQL provides two distinct types of numbers:
- integers
- floating-point numbers
Integer
The following table illustrates the specification of each integer type:
Floating-point number
There three main types of floating-point numbers:

- float(n) is a floating-point number whose precision, at least, n,


up to a maximum of 8 bytes.
- Real or float8 is a 4-byte floating-point number.
- numeric or numeric(p,s) is a real number with p digits with s
number after the decimal point. The numeric(p,s) is the exact
number.
Example of Numeric(p,s)
DROP TABLE IF EXISTS products;

CREATE TABLE products (


id SERIAL KEY,
name VARCHAR(100) NOT NULL,
price NUMERIC(5,2)
);

INSERT INTO products (name, price)


VALUES ('Phone',500.215),
('Tablet',500.214);
Temporal data types
• DATE stores the dates only.
• TIME stores the time of day values.
• TIMESTAMP stores both date and time values.
• TIMESTAMPTZ is a time zone-aware timestamp data type. It is
the abbreviation for timestamp with the time zone.
• INTERVAL stores periods of time.
The following table illustrates the ISO 8601 interval unit
abbreviations:
PART II. Data Manipulation Language.
DQL.
Data Manipulation Language
A data manipulation language (DML) is a family of computer
languages including commands permitting users to manipulate
data in a database.
This manipulation involves inserting data into database tables,
retrieving existing data, deleting data from existing tables and
modifying existing data. DML is mostly incorporated in SQL
databases.
Commands for DML:
• UPDATE: This command modifies data of one or more records.

• INSERT: This command adds one or more records to a


database table.

• DELETE: This command removes one or more records from a


table according to specified conditions.
PostgreSQL INSERT
The PostgreSQL statement allows you to insert a new row into a
table. The following illustrates the most basic syntax of the
INSERT statement:

INSERT INTO table_name(column1, column2, ...)


VALUES (value1, value2, …);
PostgreSQL INSERT Multiple Rows
To insert multiple rows into a table using a single INSERT
statement, you use the following syntax:

INSERT INTO table_name (column_list)


VALUES
(value_list_1),
(value_list_2),
...
(value_list_n);
PostgreSQL INSERT statement examples

DROP TABLE IF EXISTS links;

CREATE TABLE links ( Inserting a single row into a table

id SERIAL PRIMARY KEY, INSERT INTO links (url, name)


url VARCHAR(255) NOT NULL, VALUES('https://www.postgresqltutorial.com','PostgreSQL
Tutorial');
name VARCHAR(255) NOT NULL,
description VARCHAR (255),
last_update DATE
);
Inserting multiple rows and returning inserted rows

INSERT INTO
links (url, name)
VALUES
('https://www.google.com','Google'),
('https://www.yahoo.com','Yahoo'),
('https://www.bing.com','Bing');
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;
PostgreSQL UPDATE examples
DROP TABLE IF EXISTS courses;
CREATE TABLE courses (
course_id serial primary key,
course_name VARCHAR(255) NOT NULL,
description VARCHAR(500),
published_date date
);
INSERT INTO
courses(course_name, description, published_date)
VALUES
('PostgreSQL for Developers','A complete PostgreSQL for Developers','2020-07-13'),
('PostgreSQL Admininstration','A PostgreSQL Guide for DBA',NULL), 'PostgreSQL High
Performance',NULL,NULL),
('PostgreSQL Bootcamp','Learn PostgreSQL via Bootcamp','2013-07-11'),
('Mastering PostgreSQL','Mastering PostgreSQL in 21 Days','2012-06-30');
PostgreSQL UPDATE – updating one row

UPDATE courses
SET published_date = ’2020-08-01’
WHERE course_id = 3;
PostgreSQL DELETE
The PostgreSQL DELETE statement allows you to delete one or
more rows from a table. The following shows basic syntax of the
DELETE statement:

DELETE FROM table_name


WHERE condition;
PostgreSQL DELETE statement examples

DROP TABLE IF EXISTS links;

CREATE TABLE links (


id serial PRIMARY KEY,
url varchar(255) NOT NULL,
name varchar(255) NOT NULL,
description varchar(255),
last_update date DEFAULT now()
);
PostgreSQL DELETE statement examples

INSERT INTO
links
VALUES
('1', 'https://www.postgresqltutorial.com', 'PostgreSQL Tutorial', 'Learn
PostgreSQL fast and easy' , '2013-06-02'),
('2', 'http://www.oreilly.com', 'O''Reilly Media', 'O''Reilly Media', '2013-06-02'),
('3', 'http://www.google.com', 'Google', 'Google' , '2013-06-02'),
('4', 'http://www.yahoo.com', 'Yahoo', 'Yahoo' , '2013-06-02'),
('5', 'http://www.bing.com', 'Bing', 'Bing' , '2013-06-02'),
('6', 'http://www.facebook.com', 'Facebook', 'Facebook' , '2013-06-01'),
('7', 'https://www.tumblr.com/', 'Tumblr', 'Tumblr' , '2013-06-02'),
('8', 'http://www.postgresql.org', 'PostgreSQL', 'PostgreSQL', '2013-06-02');
1) Using PostgreSQL DELETE to delete one row from
the table:

DELETE FROM links WHERE id = 8;

2) Using PostgreSQL DELETE to delete a row and


return the deleted row:

DELETE FROM links WHERE id = 7 RETURNING *;

3) Using PostgreSQL DELETE to delete all rows from


the table:

DELETE FROM links;


PostgreSQL DQL (SELECT statement)
One of the most common tasks, when you work with the database, is to query data from
tables by using the SELECT statement.
The SELECT statement is one of the most complex statements in PostgreSQL. It has many
clauses that you can use to form a flexible query.

Let’s start with the basic form of the SELECT statement that retrieves data from a single
table. The following illustrates the syntax of the SELECT statement:
SELECT
select_list
FROM
table_name;
PostgreSQL SELECT examples
1) Using PostgreSQL SELECT statement to query data from one column example:

SELECT first_name FROM customer;

2) Using PostgreSQL SELECT statement to query data from multiple columns example:

SELECT
first_name,
last_name,
email
FROM
customer;

3) Using PostgreSQL SELECT statement to query data from all columns of a table example:

SELECT * FROM customer;


PostgreSQL SELECT examples
4) Using PostgreSQL SELECT statement with expressions example:

SELECT
first_name || ‘ ’ || last_name,
email
FROM
customer;

5) Using PostgreSQL SELECT statement with expressions example:

SELECT 5 * 3;

SELECT now();
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:

SELECT column_name AS alias_name


FROM table_name;
PostgreSQL column alias examples
1) Assigning a column alias to a column example:

SELECT
first_name,
last_name AS surname
FROM
customer;

2) Assigning a column alias to an expression example:

SELECT
first_name || ' ' || last_name AS full_name
FROM
customer;
PostgreSQL Table Aliases
Table aliases temporarily assign tables new names during the
execution of a query.

The following illustrates the syntax of a table alias:

table_name AS alias_name;
PostgreSQL ORDER BY
The ORDER BY clause allows you to sort rows returned by a SELECT
clause in ascending or descending order based on a sort expression.
The following illustrates the syntax of the ORDER BY clause:

SELECT
select_list
FROM
table_name
ORDER BY
sort_expression1 [ASC | DESC],

sort_expressionN [ASC | DESC];
PostgreSQL ORDER BY examples
1) Using PostgreSQL ORDER BY clause to sort rows by one column:
SELECT
first_name,
last_name
FROM
customer
ORDER BY
first_name ASC;
2) Using PostgreSQL ORDER BY clause to sort rows by multiple columns:
SELECT
first_name,
last_name
FROM
customer
ORDER BY
first_name ASC,
last_name DESC;
PostgreSQL ORDER BY examples
The LENGTH() function accepts a string and returns the length of that string.
The following statement selects the first names and their lengths. It sorts the rows by the
lengths of the first names:

SELECT
first_name,
LENGTH(last_name) as len
FROM
customer
ORDER BY
len DESC;
PostgreSQL SELECT DISTINCT
The DISTINCT clause is used in the SELECT statement to
remove duplicate rows from a result set.
The following illustrates the syntax of the clause:

SELECT
DISTINCT column1
FROM
table_name;
PostgreSQL SELECT DISTINCT examples
CREATE TABLE distinct_demo (
id serial NOT NULL PRIMARY KEY,
bcolor VARCHAR,
fcolor VARCHAR
);

INSERT INTO distinct_demo (bcolor, fcolor)


VALUES
'red', 'red'),
'red', 'red'),
'red', NULL),
NULL, 'red'),
'red', 'green'),
'red', 'blue'),
'green', 'red'),
'green', 'blue'),
'green', 'green'),
'blue', 'red'),
'blue', 'green'),
'blue', 'blue');
PostgreSQL SELECT DISTINCT examples

SELECT
DISTINCT bcolor
FROM
distinct_demo
ORDER BY
bcolor;
PART III. String Functions. Filtering Data.
Conditional Expressions & Operators.
PostgreSQL String Functions
Introduction to PostgreSQL CONCAT function
PostgreSQL introduced a built-in string function named CONCAT
to concatenate two or more strings into one.

The following illustrates the syntax of the CONCAT function:

CONCAT(str_1, str_2, ...)


PostgreSQL CONCAT function examples:
1) SELECT CONCAT ('CONCAT',' ', 'function’);

2) SELECT
CONCAT (first_name, ' ', last_name) AS "Full name”
FROM
customer

3) SELECT
first_name,
CONCAT (‘Your first name ‘, length(first_name), ‘ characters’)
FROM
customer
PostgreSQL FORMAT Function
PostgreSQL FORMAT() function formats arguments based on a format
string.

The syntax of the PostgreSQL FORMAT() function is as follows:

FORMAT(format_string [, format_arg [, ...] ])


Examples
1) SELECT FORMAT('Hello, %s','PostgreSQL’);

2) SELECT
FORMAT('%s, %s’, last_name, first_name) full_name
FROM
customer
ORDER BY full_name;
PostgreSQL Letter Case Functions
• PostgreSQL LOWER function
• PostgreSQL UPPER function
• PostgreSQL INITCAP function
Examples
1) LOWER() FUNCTION
SELECT
LOWER(last_name)
FROM
customer
ORDER BY last_name;
2) UPPER() FUNCTION
SELECT
UPPER(last_name)
FROM
customer
ORDER BY last_name;
3)INITCAP() FUNCTION
SELECT
INITCAP(CONCAT (first_name, ‘ ’, last_name))
FROM
customer
ORDER BY first_name;
PostgreSQL LEFT Function
The PostgreSQL LEFT() function returns the first n characters in
the string.

The following illustrates the syntax of the PostgreSQL LEFT()


function:
LEFT(string, n)
Examples
1)SELECT LEFT('ABC',1);

2)SELECT LEFT('ABC',2);

3)SELECT LEFT('ABC',-2);
PostgreSQL RIGHT Function
The PostgreSQL RIGHT() function returns the last n characters in
a string.

The following shows the syntax of the PostgreSQL RIGHT()


function:
RIGHT(string, n)
Examples
1)SELECT RIGHT('XYZ', 2);

2)SELECT RIGHT('XYZ', - 1);

3) SELECT last_name
FROM customer
WHERE RIGHT(last_name,3) = ‘son’;
PostgreSQL TRIM Function
• The LTRIM() function removes all characters, spaces by
default, from the beginning of a string.
• The RTRIM() function removes all characters, spaces by
default, from the end of a string.
• The BTRIM() function is the combination of the LTRIM() and
RTRIM() functions.
Examples
1)SELECT
LTRIM('enterprise', 'e’);

2)SELECT
RTRIM('enterprise', 'e’);

3)SELECT
BTRIM('enterprise', 'e');
PostgreSQL POSITION Function
The PostgreSQL POSITION() function returns the location of a
substring in a string.

The following illustrates the syntax of the PostgreSQL


POSITION() function:

POSITION(substring in string)
Example
1) SELECT POSITION('Tutorial' IN 'PostgreSQL Tutorial’);

2) SELECT POSITION('tutorial' IN 'PostgreSQL Tutorial');


PostgreSQL REPLACE Function
To search and replace all occurrences of a string with a new one,
you use the REPLACE() function.

The following illustrates the syntax of the PostgreSQL


REPLACE() function:

REPLACE(source, old_text, new_text );


Examples
1) SELECT
REPLACE ('ABC AA', 'A', 'Z’);

2) UPDATE
customer
SET
email = REPLACE (
email,
‘qwerty1.org’,
‘postgressqltutorial.com’
);
PostgreSQL Substring Function
The substring function returns a part of string. The following
illustrates the syntax of the substring function:

SUBSTRING ( string ,start_position , length )


Examples
1)SELECT
SUBSTRING ('PostgreSQL', 1, 8); -- PostgreS

2)SELECT
SUBSTRING ('PostgreSQL', 8); -- SQL

3) SELECT
SUBSTRING ('PostgreSQL' FROM 1 FOR 8); -- PostgreS
PostgreSQL Filtering Data
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:


SELECT select_list
FROM table_name
WHERE condition
ORDER BY sort_expression;
Comparison and logical operators
PostgreSQL WHERE clause examples
PostgreSQL WHERE clause examples
PostgreSQL WHERE clause examples

You might also like