0% found this document useful (0 votes)
136 views6 pages

PostgreSQL Database Operations Guide

The document shows SQL commands for creating and managing databases and tables on PostgreSQL. It creates a database and table, performs CRUD operations like INSERT, SELECT, UPDATE, DELETE. It also shows aggregation functions and creating a login table with sample data.

Uploaded by

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

PostgreSQL Database Operations Guide

The document shows SQL commands for creating and managing databases and tables on PostgreSQL. It creates a database and table, performs CRUD operations like INSERT, SELECT, UPDATE, DELETE. It also shows aggregation functions and creating a login table with sample data.

Uploaded by

Prashant Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

Password: Megamind@123

---------------------------------------------------------------------
postgres=# \l //to view all databases
postgres=# \c SQL-Lab1 //switch to SQL-Lab1 database
SQL-Lab1=# \i D:/Gallery/Downloads/[Link]

----------------------------------------------------------------------

postgres=# CREATE DATABASE webmonth;


CREATE DATABASE

postgres=# \l //to see list of all database

postgres=# DROP DATABASE webmonth2;


DROP DATABASE

postgres=# \c webmonth
You are now connected to database "webmonth" as user "postgres".

//Create a table inside database


webmonth=# CREATE TABLE users(name text, age smallint, birthday date);
CREATE TABLE

//To see the tables that exits in my database


webmonth=# \d
List of relations
Schema | Name | Type | Owner
--------+-------+-------+----------
public | users | table | postgres
(1 row)

//Insert the data in table


webmonth=# INSERT INTO users (name, age, birthday) values ('Prashant', '18', '2002-
12-21');
INSERT 0 1

//Displaying the data


webmonth=# SELECT name, age,birthday from users;
name | age | birthday
----------+-----+------------
Prashant | 18 | 2002-12-21
(1 row)

webmonth=# SELECT * from users;


name | age | birthday
----------+-----+------------
Prashant | 18 | 2002-12-21
(1 row)

//Create a new column


webmonth=# ALTER TABLE users ADD score smallint;
ALTER TABLE
webmonth=# SELECT * from users;
name | age | birthday | score
----------+-----+------------+-------
Prashant | 18 | 2002-12-21 |
(1 row)

//Added data indivisually


webmonth=# UPDATE users set score = 10 WHERE name = 'Prashant';
UPDATE 1
webmonth=# SELECT * from users;
name | age | birthday | score
----------+-----+------------+-------
Prashant | 18 | 2002-12-21 | 10
(1 row)

//Added a new user into TABLE users


webmonth=# INSERT INTO users (name, age, birthday) values ('kishan', '21', '1999-
12-24');
INSERT 0 1
webmonth=# SELECT * from users;
name | age | birthday | score
----------+-----+------------+-------
Prashant | 18 | 2002-12-21 | 10
kishan | 21 | 1999-12-24 |
(2 rows)

//Displaying the data of a indivisual user


webmonth=# SELECT * from users WHERE name = 'Prashant';
name | age | birthday | score
----------+-----+------------+-------
Prashant | 18 | 2002-12-21 | 10
(1 row)

//Added gender to both the users


webmonth=# UPDATE users set gender = 'male' WHERE name = 'Prashant'or name =
'kishan';
UPDATE 2
webmonth=# SELECT * from users;
name | age | birthday | score | gender
----------+-----+------------+-------+--------
Prashant | 18 | 2002-12-21 | 10 | male
kishan | 21 | 1999-12-24 | | male
(2 rows)

//Selecting users whose name is starting from 'P'


webmonth=# SELECT * from users WHERE name like 'P%';
name | age | birthday | score | gender
----------+-----+------------+-------+--------
Prashant | 18 | 2002-12-21 | 10 | male
Pranay | 18 | 2002-12-24 | |
(2 rows)

//Displaying the users data in decending order on basis of score


webmonth=# SELECT * from users order by score desc
webmonth-# ;
name | age | birthday | score | gender
----------+-----+------------+-------+--------
kishan | 21 | 1999-12-24 | | male
Prashant | 18 | 2002-12-21 | 10 | male
Pranay | 18 | 2002-12-24 | 8 |
(3 rows)

//Aggregation operators like:


AVG() – return the average value.
COUNT() – return the number of values.
MAX() – return the maximum value.
MIN() – return the minimum value.
SUM() – return the sum of all or distinct values.

webmonth=# SELECT avg(score) from users;


avg
--------------------
9.0000000000000000
(1 row)

=================================================
webmonth=# SELECT SUM(age) from users;
sum
-----
57
(1 row)
=================OR==============================
webmonth=# SELECT SUM(age) as TOTAL from users;
total
-------
57
(1 row)
=================================================

//Creating a new login TABLE


========================================================================
CREATE TABLE login(ID serial not NULL primary key, name text,email_id varchar(50)
unique not NULL, secret varchar(100) not NULL);

webmonth=# SELECT * from login;


id | secret | name
----+--------+------
(0 rows)

webmonth=# INSERT INTO login(secret,name) values ('abc','Prashant');


INSERT 0 1
webmonth=# INSERT INTO login(secret,name) values ('def','Jack');
INSERT 0 1
webmonth=# SELECT * from login;
id | secret | name
----+--------+----------
1 | abc | Prashant
2 | def | Jack
(2 rows)

webmonth=# INSERT INTO login(secret,name) values ('gfg','Devil');


INSERT 0 1
webmonth=# SELECT * from login;
id | secret | name
----+--------+----------
1 | abc | Prashant
2 | def | Jack
3 | gfg | Devil
(3 rows)

webmonth=# DELETE FROM login WHERE name = 'Devil';


DELETE 1
webmonth=# SELECT * from login;
id | secret | name
----+--------+----------
1 | abc | Prashant
2 | def | Jack
(2 rows)

webmonth=# INSERT INTO login(secret,name) values ('gfg','Devil');


INSERT 0 1
webmonth=# INSERT INTO login(secret,name) values ('qwerty','Angel');
INSERT 0 1
webmonth=# SELECT * from login;
id | secret | name
----+--------+----------
1 | abc | Prashant
2 | def | Jack
4 | gfg | Devil
5 | qwerty | Angel
(4 rows)
=====================================================================

Common questions

Powered by AI

Dynamically updating a database structure involves several challenges, including ensuring data integrity, handling existing applications that depend on the schema, and maintaining performance. When adding new columns, as with ALTER TABLE to add 'score', care must be taken to ensure that existing queries are updated accordingly. Introducing new users or data must involve validation processes to maintain uniqueness and constraints, as illustrated with the unique 'email_id' in the 'login' table. Addressing these challenges requires thorough testing, appropriate fallback mechanisms before changes, and potential re-indexing for large datasets to maintain performance.

To retrieve users ordered by specific criteria, a SQL query with an ORDER BY clause is used. For example, to order users by 'score' in descending order, the query was: SELECT * from users ORDER BY score DESC; This command arranges the result set so that users with the highest scores appear first. The use of DESC specifies descending order, while ASC can be used for ascending order. Such ordering allows for organized data viewing and analysis.

To add a new column to an existing table in PostgreSQL, the ALTER TABLE command is used. For instance, to add a column 'score' to the 'users' table, the command was: ALTER TABLE users ADD score smallint; Adding new columns can affect data retrieval by requiring adjustments to queries that select data from the table. Without adjusting existing queries, new columns may not be included in the output, potentially leading to incomplete data sets in query results.

When using wildcard characters in SQL queries, especially with conditions like LIKE, several considerations must be done. Wildcards, such as '%' in LIKE 'P%', help filter data based on patterns, but they can affect query performance due to lack of index use. With large datasets, queries might slow down substantially. Security precautions are also critical, as wildcard usage can lead to SQL injection vulnerabilities if input is unsanitized. Optimizing these queries involves proper indexing strategies and validating inputs to protect against injection attacks.

To create a table in a PostgreSQL database, you use the CREATE TABLE command followed by specifying the table schema. For instance, in the 'webmonth' database, a table named 'users' was created with the columns 'name', 'age', and 'birthday': CREATE TABLE users(name text, age smallint, birthday date); Once the table is created, data can be inserted using the INSERT INTO command. For example, an entry was added to the 'users' table: INSERT INTO users (name, age, birthday) values ('Prashant', '18', '2002-12-21')

Aggregate functions in PostgreSQL are used to perform calculations on a set of values and return a single value. The AVG() function calculates the average of specified columns, while SUM() adds up the values. For example, to find the average 'score' in the 'users' table, the query was: SELECT avg(score) from users; resulting in an average of 9.0000000000000000. Similarly, to calculate the total 'age' of users, the query was: SELECT SUM(age) from users; returning a sum of 57.

To manage deletion and insertion of data within a PostgreSQL table effectively, you need to follow a structured approach. Deletion of obsolete or irrelevant entries is done using the DELETE command followed by a condition, as with deleting a row where name was 'Devil': DELETE FROM login WHERE name = 'Devil';. Simultaneously, insertion of new relevant data is done using the INSERT INTO command specifying the columns and values. For example, adding new users with: INSERT INTO login(secret,name) values ('qwerty','Angel');. This approach ensures that the database remains current and relevant, reflecting accurate states of real-world entities.

To update data in a PostgreSQL table, the UPDATE command is used along with a condition to specify which row(s) should be modified. For instance, to update the 'score' for user 'Prashant' in the 'users' table, the command was: UPDATE users set score = 10 WHERE name = 'Prashant'; To retrieve specific data, the SELECT command is used with a WHERE clause. For example, to get data of a user named 'Prashant', the query was: SELECT * from users WHERE name = 'Prashant';

Using serial numbers for primary keys in SQL databases is important for ensuring uniqueness and efficient indexing. Serial numbers automatically increment with each new row addition, providing an easy mechanism for generating unique identifiers. This eliminates the risk of manual entry errors and simplifies database management by maintaining orderly and sequential entries. In the 'login' table, 'ID serial not NULL primary key' ensures that each new entry has a unique identifier, which is critical for relational integrity and query performance.

In PostgreSQL, unique constraints and primary keys ensure data integrity by preventing duplicate entries and establishing row uniqueness. When creating a table, unique constraints are added to ensure that values in specified columns are unique across the table, as seen with the 'email_id' field: varchar(50) unique not NULL. A primary key, such as 'ID serial not NULL primary key' in the 'login' table, uniquely identifies each row and is a specific case of a unique constraint that also prevents NULL values. These constraints are critical in maintaining data consistency and integrity.

You might also like