Mastering PostgreSQL: Advanced SQL Commands, Security, and Administration
Tags: postgres, database
Published: 2023-04-10 00:53:23

PostgreSQL, as I mentioned in Blog 1 "Check it here: [](https://dev.to/hashemaw/postgresql-the-comprehensive-guide-2i4k), is an open-source relational database management system that has gained immense popularity in recent years. It is an enterprise-level database system that provides advanced features and high-level functionality for data storage and management. PostgreSQL has proven to be a reliable and secure option for managing data, and it is widely used in various industries and applications, including web development, data analysis, and machine learning.
This blog will extend Blog one and discuss advanced features and commands for PostgreSQL.

## **Advanced SQL Commands**

**Combining Data with JOIN**

One of the most fundamental features of a relational database is the ability to join data from multiple tables. PostgreSQL supports several types of joins, including INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN. Here is an example of an INNER JOIN:

`SELECT customers.customer_name, orders.order_date
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id;
`

**Using Subqueries**

Subqueries are an important feature of SQL that allows you to nest one query inside another. This is particularly useful when you need to perform complex calculations or filtering on a subset of data. Here is an example of a subquery:

`SELECT *
FROM products
WHERE product_id IN (SELECT product_id FROM order_details WHERE quantity > 10);`

**Conditional Expressions with CASE**

The CASE statement is a powerful tool for creating conditional expressions in SQL. It allows you to specify different outcomes based on different conditions. Here is an example of a CASE statement:

`SELECT customer_name, CASE WHEN total_spent > 1000 THEN 'Gold'
                            WHEN total_spent > 500 THEN 'Silver'
                            ELSE 'Bronze' END AS customer_type
FROM customers;`

**String Manipulation with Functions**

PostgreSQL provides a wide range of string manipulation functions that allow you to modify and manipulate text data. Here is an example of the substring function:

`SELECT substring('Hello World', 1, 5);`

**Mathematical Operations with Functions**

PostgreSQL also provides a range of mathematical functions that can be used to perform complex calculations on numeric data. Here is an example of the square root function:

`SELECT sqrt(25);`

**Handling NULL Values with COALESCE and NULLIF**

NULL values can often cause problems in SQL queries, but PostgreSQL provides several functions to help you manage them. The COALESCE function allows you to replace NULL values with a specified default value, while the NULLIF function allows you to compare two expressions and return NULL if they are equal. Here are examples of both functions:

`SELECT COALESCE(product_name, 'Unknown')
FROM products;`

`SELECT NULLIF(price, 0)
FROM products;`

**Advanced Filtering with LIKE, ILIKE, BETWEEN, and IN:**
PostgreSQL provides powerful filtering options that can be used to retrieve data that matches certain patterns or values. These options include the LIKE, ILIKE, BETWEEN, and IN operators.

- The **LIKE** operator is used to match a pattern against a string. It is case-sensitive, and the pattern can contain special wildcard characters, such as % and _.

- The **ILIKE** operator is similar to LIKE, but it is case-insensitive.

- The **BETWEEN** operator is used to retrieve rows whose values fall within a specified range.

- The **IN** operator is used to retrieve rows whose values match any of a specified set of values.
Here are some examples of using these operators:


` SELECT * FROM customers WHERE last_name LIKE 'Smi%';
-- Retrieves all customers whose last name starts with "Smi"`

`SELECT * FROM customers WHERE first_name ILIKE 'jO%';
-- Retrieves all customers whose first name starts with "jO" (case-insensitive)`

`SELECT * FROM orders WHERE order_date BETWEEN '2021-01-01' AND '2021-01-31';
-- Retrieves all orders placed in January 2021`

`SELECT * FROM products WHERE category_id IN (1, 3, 5);
-- Retrieves all products in categories 1, 3, or 5` 

## **Security and Administration:**

PostgreSQL provides various security and administration features that allow you to control access to your database and manage it effectively. Some of the important features are:

Creating and Managing Users and Roles:
PostgreSQL allows you to create and manage users and roles, which are used to control access to the database. Users are individual entities that can be granted permissions on objects, while roles are groups of users that can be managed collectively.

**To create a user in PostgreSQL, you can use the following command:
**
`CREATE USER username WITH PASSWORD 'password';`

**To create a role, you can use the following command:
**`CREATE ROLE rolename;`

**Managing Database Permissions:**
PostgreSQL provides a powerful permissions system that allows you to control access to your database objects. You can grant or revoke permissions on tables, views, and other objects to specific users or roles.

To grant SELECT permission on a table to a user, you can use the following command:

`GRANT SELECT ON tablename TO username;`

To revoke a permission, you can use the following command:

`REVOKE SELECT ON tablename FROM username;`

**Backup and Restore with pg_dump and pg_restore:**
PostgreSQL provides tools for backing up and restoring your database. The pg_dump tool can be used to create a backup of your database, while the pg_restore tool can be used to restore the backup.

To create a backup of your database, you can use the following command:
`pg_dump -U username -d databasename > backup.sql`

To restore a backup, you can use the following command:

`pg_restore -U username -d databasename backup.sql`

**Monitoring and Tuning Performance:**
PostgreSQL provides various tools and features for monitoring and tuning the performance of your database. You can use the built-in system views to monitor the activity of your database, and use the EXPLAIN command to analyze the performance of your queries. 
For example, let's say you have a table called "customers" with columns "id", "name", "email", and "created_at", and you want to retrieve all customers whose email address contains the word "gmail". You might write a query like this:

`SELECT *
FROM customers
WHERE email LIKE '%gmail%';`

To see how the database engine is executing this query, you can use the EXPLAIN command:

`EXPLAIN SELECT *
FROM customers
WHERE email LIKE '%gmail%';`

This will output information about the query plan, including the order in which tables are being accessed, the types of scans being used, and any joins or filters being applied. You can use this information to identify performance issues and optimize the query for better performance.

## **Converting CPRG-352 Lab7 to Postgres**

**CPRG-352 Lab7 Mysql Code**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0uu7oh8gv2isgj9917bw.PNG)

**Postgres Code**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ou5iso1q4alsywxzxlm8.PNG)

**Changes Made:**

- **Schema Name:** In MySQL, the backtick character is used to enclose schema and table names, while in PostgreSQL, the double quotes " are used. Therefore, the schema name is changed fromuserdb` to "userdb".

- **Data Types:** The INT data type in MySQL is equivalent to INTEGER in PostgreSQL. Therefore, the data type for columns such as role_id and role were changed to INTEGER.

- **Primary Key:** The syntax for defining primary keys is slightly different in PostgreSQL. In MySQL, the PRIMARY KEY constraint is defined after the column name, while in PostgreSQL, it is defined as a separate constraint at the end of the column definition. Therefore, the primary key constraint for the role table is changed from PRIMARY KEY (role_id) to CONSTRAINT pk_role PRIMARY KEY (role_id).

- **Foreign Key:** The syntax for defining foreign keys is also slightly different in PostgreSQL. In MySQL, the FOREIGN KEY constraint is defined after the column name, while in PostgreSQL, it is defined as a separate constraint at the end of the column definition. Therefore, the foreign key constraint for the user table is changed from CONSTRAINT fk_user_role FOREIGN KEY (role) REFERENCES userdb.role (role_id) to CONSTRAINT fk_user_role FOREIGN KEY (role) REFERENCES userdb.role (role_id).

- **String Literals:** In MySQL, single quotes are used to enclose string literals, while in PostgreSQL, either single quotes or double quotes can be used. Therefore, the string literals in the INSERT INTO statements are enclosed in single quotes in the converted PostgreSQL code.

Overall, the changes made to convert the MySQL code to PostgreSQL are mainly syntactical differences between the two database management systems.

## **Conclusion:**
PostgreSQL is a powerful and feature-rich database management system that offers numerous advantages over other databases. Its advanced filtering options, powerful security and administration features, and backup and restore tools make it an ideal choice for enterprise-level applications.

In this blog, we have covered some of the advanced SQL commands in PostgreSQL, including filtering with LIKE, ILIKE, BETWEEN, and IN, and security and administration features such as creating and managing users and roles, managing database as well as demonstrate a conversion from MySQL to Postgres.