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

Postgres Notes

The document defines PostgreSQL as an open source object relational database system. It discusses PostgreSQL's key features like being free to download, supporting various operating systems, and being highly secure and reliable. It also explains PostgreSQL concepts like MVCC and provides SQL commands examples to create databases, tables, insert, select, and delete data.

Uploaded by

aarzoo
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)
24 views21 pages

Postgres Notes

The document defines PostgreSQL as an open source object relational database system. It discusses PostgreSQL's key features like being free to download, supporting various operating systems, and being highly secure and reliable. It also explains PostgreSQL concepts like MVCC and provides SQL commands examples to create databases, tables, insert, select, and delete data.

Uploaded by

aarzoo
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
You are on page 1/ 21

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

POSTGRES---------------------------------------------------------------------------
--

DEFINITON

- It is an open source object relational database system.It allows yout to


store,process and retrieve data successfully.It was developed by world wide
team of volunteers.

KEY FEATURES

- free to download
- supports various os
- highly secure and reliable
- compatible with several data types
- supports MVCC
- supports text,image,sounds and videos

MVCC

- Stands for Multiverse Concurrency Control


- keeps our data safe and organaized, allowing multiple people to use same
database without creating chaos
- features snapshot(when a transaction begins it takes snapshot of the
database of how it looked at that particular moment,this snapshot remains
consistant throughout the transaction, even if people are making changes to some
data) and isolation(it states that each transaction gets its own snapshot
ensuring that writing of one doesn't effect the reading of other,i.e. reading
doesn't block writing and writing doesn't block reading)

INSTALLATION COMMANDS

- $sudo apt-get install postgresql postgresql-contrib

PSQL COMMANDS

- $psql - opens psql mode


- $sudo su postgres - used to switch between different users
- $sudo -i -u postgres - will change user to postgres through it we can enter
psql mode
- \l - used to list the databases present in the system
op - List of databases
Name | Owner | Encoding | Collate | Ctype | Access
privileges
-----------+----------+----------+---------+-------
+-----------------------
new | postgres | UTF8 | en_IN | en_IN |
postgres | postgres | UTF8 | en_IN | en_IN |
sql_demo | postgres | UTF8 | en_IN | en_IN |
template0 | postgres | UTF8 | en_IN | en_IN | =c/postgres
+
| | | | |
postgres=CTc/postgres
template1 | postgres | UTF8 | en_IN | en_IN | =c/postgres
+
| | | | |
postgres=CTc/postgres
(5 rows)

- \du - lists all the users present in the system


o/p - List of roles
Role name | Attributes
| Member of
-----------
+------------------------------------------------------------+-----------
postgres | Superuser, Create role, Create DB, Replication,
Bypass RLS | {}
user1 | Superuser
| {}

- \q - to quit psql mode


- \c - to got inside a database
o/p - You are now connected to database "sql_demo" as user "postgres".
- select version() - displays the version of the postgresql
o/p - version
-----------------------------------------------------------------------
---------------------------------------------------------------
PostgreSQL 10.23 (Ubuntu 10.23-0ubuntu0.18.04.2) on x86_64-pc-linux-
gnu, compiled by gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0, 64-bit
(1 row)

- help - to seek help


- \d table_name - describe the contents/columns of the table specified
syntax - #\d movies
o/p - Table "public.movies"
Column | Type | Collation | Nullable |
Default
--------------+-----------------------+-----------+----------
+---------
movie_id | integer | | |
movie_name | character varying(40) | | |
movie_genre | character varying(30) | | |
imdb_ratings | real | | |

SQL COMMANDS

- CREATE DATABASE - used to create a new database


syntax - #CREATE DATABASE sql_demo
o/p - CREATE DATABASE (tells that the database has been
successfully created )

- DROP DATABASE - used to delete a databse along with its structure(you


can't delete the database you currently are on)
syntax - DROP DATABSE [IF EXISTS] database_name
example - DROP DATABSE [IF EXISTS] new
o/p - DROP DATABASE

- CREATE TABLE - used to create a new table in the database


syntax - CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
example - CREATE TABLE persons (
id SERIAL,
first_name VARCHAR(50),
last_name VARCHAR(50),
dob DATE,
email VARCHAR(255),
PRIMARY KEY (id)
);

o/p - CREATE TABLE

- TRUNCATE TABLE - used to delete the data of a table without deleting


its structure
syntax - TRUNCATE TABLE table_name;

- DROP TABLE - used to delete the table along with its structure
syntax - DROP TABLE table_name
example - DROP TABLE person
o/p - DROP TABLE

- INSERT QUERY - used to insert data into the table


syntax - INSERT INTO TABLE_NAME (column1, column2,
column3,...columnN)
VALUES (value1, value2, value3,...valueN);
example - INSERT INTO Employee (Emp_id, Emp_name, Emp_mail,
Emp_gender, Emp_department, Emp_address, Emp_salary)
VALUES
(101, 'John Doe', '[email protected]', 'Male',
'IT', '123 Main St, City', 75000.00),
(102, 'Jane Smith', '[email protected]',
'Female', 'HR', '456 Elm Ave, Town', 60000.00),
(103, 'Michael Johnson',
'[email protected]', 'Male', 'Finance', '789 Oak Rd, Village', 80000.00),
(104, 'Emily Brown', '[email protected]',
'Female', 'Marketing', '987 Maple Ln, Suburb', 65000.00),
(105, 'David Lee', '[email protected]',
'Male', 'Sales', '654 Pine Blvd, County', 70000.00),
(106, 'Alex Turner', '[email protected]',
'Male', 'Sales', '789 Elm St, City', 72000.00),
(107, 'Sophia White', '[email protected]',
'Female', 'IT', '234 Oak Ave, Town', 68000.00),
(108, 'Daniel Harris',
'[email protected]', 'Male', 'Finance', '567 Maple Rd, Village', 85000.00),
(109, 'Olivia Martin',
'[email protected]', 'Female', 'HR', '876 Pine Ln, Suburb', 62000.00),
(110, 'William Clark',
'[email protected]', 'Male', 'Marketing', '345 Cedar Blvd, County',
71000.00),
(155, 'Emma Rodriguez',
'[email protected]', 'Female', 'IT', '123 Elm St, City', 70000.00),
(156, 'Liam Walker', '[email protected]',
'Male', 'Sales', '456 Oak Ave, Town', 63000.00),
(157, 'Ava Scott', '[email protected]',
'Female', 'Finance', '789 Maple Rd, Village', 78000.00),
(158, 'Noah Hall', '[email protected]',
'Male', 'HR', '987 Pine Ln, Suburb', 67000.00),
(159, 'Isabella Young',
'[email protected]', 'Female', 'Marketing', '654 Cedar Blvd, County',
74000.00);

- SELECT QUERY - used to display specific data froma table


syntax - SELECT * FROM table_name
example - SELECT * FROM movies
o/p - movie_id | movie_name | movie_genre |
imdb_ratings
----------+--------------------------+----------------
+--------------
101 | Vertigo | Mystry,Romance |
8.3
102 | The Shawshank Redemption | Crime,Friction |
9.3
104 | The Dark Knight | Action |
9
105 | The Matrix | Sci-fic |
8.7
106 | Se7en | Crime |
8.6
107 | Interstellar | Adventure |
8.6
103 | 12 Angry Men | Drama,Crime |
9
(7 rows)

- WHERE CLAUSE - used to specify conditions while running a command


syntax - SELECT * FROM table_name
WHERE (condition)
example - SELECT * FROM movies
WHERE imdb_ratings > 8.7
o/p - movie_id | movie_name | movie_genre |
imdb_ratings
----------+--------------------------+----------------
+--------------
102 | The Shawshank Redemption | Crime,Friction |
9.3
104 | The Dark Knight | Action |
9
103 | 12 Angry Men | Drama,Crime |
9
(3 rows)

- AND CLAUSE - used t conbine to two condition where both conditions needs
to be fullfilled
syntax - SELECT * FROM movies
WHERE condition1 AND condition2
example - SELECT * FROM movies
WHERE imdb_ratings > 8.7 and movie_genre='Action'
o/p - movie_id | movie_name | movie_genre | imdb_ratings
----------+-----------------+-------------+--------------
104 | The Dark Knight | Action | 9
(1 row)
- OR CLAUSE - used to specify multiple condition where it displays result
even if 1 cndition of them is true
syntax - SELECT * FROM movies
WHERE condition1 OR condition2
example - SELECT * FROM movies
WHERE imdb_ratings > 8.7 OR movie_genre='Action'
o/p - movie_id | movie_name | movie_genre
| imdb_ratings
----------+--------------------------+----------------
+--------------
102 | The Shawshank Redemption | Crime,Friction |
9.3
104 | The Dark Knight | Action |
9
103 | 12 Angry Men | Drama,Crime |
9
(3 rows)

- UPDATE QUERY -
syntax - UPDATE table_name
SET column1 = value1, column2 = value2...., columnN =
valueN
WHERE [condition];
example - UPDATE movies
SET imdb_ratings = 8.7
WHERE imdb_ratings = 8.6;
o/p - UPDATE TABLE

- DELETE QUERY - used to delete a table or particular enteries of the table


syntax - DELETE FROM table_name
WHERE [condition];
example - DELETE FROM movies
WHERE imdb_ratings=8.6;
o/p - DELETE 2

- LIKE CLAUSE - used to provide an approx idea of what a user is trying to


search and results in all the matching patterns
syntax - SELECT * FROM table_name
WHERE column LIKE 'pattern'
example - SELECT * FROM movies
WHERE movie_name LIKE 'THE%';
o/p - movie_id | movie_name | movie_genre |
imdb_ratings
----------+--------------------------+----------------
+--------------
102 | The Shawshank Redemption | Crime,Friction |
9.3
104 | The Dark Knight | Action |
9
105 | The Matrix | Sci-fic |
8.7
(3 rows)

- SCHEMA - used to describe the structure of the table to be made


syntax - create schema myschema;
o/p - CREATE SCHEMA
syntax - create table myschema.company(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
o/p - CREATE TABLE

- LIMIT CLAUSE - used to limit the number of enteries to be displayed by


the system
syntax - SELECT *
FROM table_name
LIMIT {no.of rows}
example - SELECT *
FROM store
LIMIT 5
o/p - store_id | store_name | product | quantity | cost
----------+------------------+---------+----------+------
1 | NIT | Iphone | 100 | 1050
1 | NIT | Macbook | 75 | 825
1 | NIT | Iwatch | 50 | 1500
2 | Select City Walk | Iphone | 120 | 1275
2 | Select City Walk | Macbook | 90 | 1000
(5 rows)

- OFFSET CLAUSE - used to tell after which row number the data is to be
displayed
syntax - SELECT *
FROM store
LIMIT {no.of rows} OFFSET {row number}
example - SELECT *
FROM store
LIMIT 5 OFFSET 2
O/P - store_id | store_name | product | quantity | cost
----------+------------------+---------+----------+------
1 | NIT | Iwatch | 50 | 1500
2 | Select City Walk | Iphone | 120 | 1275
2 | Select City Walk | Macbook | 90 | 1000
2 | Select City Walk | Iwatch | 60 | 1800
3 | Ambience | Iphone | 80 | 1100
(5 rows)

- ORDER BY - used to order the table aescending/descending based on a


certain column of the table
syntax - SELECT * FROM table_name ORDER BY colmn_name
[ASC|DESC];
example - SELECT * FROM store ORDER BY store_name ASC;
o/p - store_id | store_name | product | quantity |
cost
----------+------------------+---------+----------+------
5 | Ambala | Iphone | 95 | 975
5 | Ambala | Macbook | 70 | 1150
5 | Ambala | Iwatch | 45 | 1725
3 | Ambience | Iphone | 80 | 1100
3 | Ambience | Macbook | 60 | 950
3 | Ambience | Iwatch | 40 | 1650
6 | Chandigarh | Iphone | 130 | 1400
6 | Chandigarh | Iwatch | 70 | 1250
6 | Chandigarh | Macbook | 100 | 800
7 | Delhi | Macbook | 55 | 1200
7 | Delhi | Iphone | 75 | 1025
4 | Faridabad | Macbook | 85 | 775
4 | Faridabad | Iphone | 110 | 1325
4 | Faridabad | Iwatch | 55 | 1475
1 | NIT | Iphone | 100 | 1050
1 | NIT | Iwatch | 50 | 1500
1 | NIT | Macbook | 75 | 825
2 | Select City Walk | Iwatch | 60 | 1800
2 | Select City Walk | Macbook | 90 | 1000
2 | Select City Walk | Iphone | 120 | 1275
(20 rows)

- GROUP BY - used to group data having identical contents


syntax - SELECT * FROM table_name GROUP BY
column_name;
example - SELECT store_id, store_name,
SUM(quantity) AS total_quantity, SUM(cost) AS total_cost
FROM store GROUP BY store_id,
store_name;
o/p - store_id | store_name | total_quantity
| total_cost
----------+------------------+----------------
+------------
4 | Faridabad | 250 |
3575
7 | Delhi | 130 |
2225
6 | Chandigarh | 300 |
3450
2 | Select City Walk | 270 |
4075
1 | NIT | 225 |
3375
5 | Ambala | 210 |
3850
3 | Ambience | 180 |
3700
(7 rows)

- WITH CLAUSE - used to write subquery and main query in more


appropriate/readable manner
syntax - WITH ___ AS ____ (SELECT -----)
SELECT * FROM -----,----
example - with average_rating as (select
AVG(imdb_ratings) as avg from movies)
select * from movies as e,
average_rating as av
where e.imdb_ratings > av.avg;
o/p - movie_id | movie_name |
movie_genre | imdb_ratings | avg
----------+--------------------------
+----------------+--------------+------------------
102 | The Shawshank Redemption |
Crime,Friction | 9.3 | 8.78571442195347
104 | The Dark Knight | Action
| 9 | 8.78571442195347
103 | 12 Angry Men |
Drama,Crime | 9 | 8.78571442195347
(3 rows)

- HAVING CLAUSE - it allows us to pick out particular rows where the


function's result meets some condition.Always placed after group by clause.
The WHERE clause places conditions on the selected columns,
whereas the HAVING clause places conditions on groups created by the
GROUP BY clause.
syntax - SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2
example - SELECT name FROM employees
GROUP BY name
HAVING COUNT(name)>1;
o/p - name
-------
James
Paul
(2 rows)

-DISTINCT KEYWORD - is it used with select statement in order to remove


duplicate data and fetching only unique data
syntax - SELECT DISTINCT col_name FROM table_name;
example - SELECT DISTINCT name FROM employees;
o/p - name
-------
Mark
Teddy
Allen
James
David
Paul
Kim
(7 rows)

- NULL - used to represent a missing value, different from a column


containing value 0 (just a concept)
- ALIAS - used to rename a column or table temporarily by giving it
other name (just for a particular query)
AS is used

OPERATORS

- Arithmatic Operators - used to do arithmatic operations

Operator Function
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
^ Exponentiation
|/ Squate root
||/ Cube root
! Factorial
!! Factorial(Prefix operator)
- Comparison Operators - used to do comaprison between similar terms

Operator Function
= checks if a is equal to b
!= checks if a is not equal to b
<> checks is value of a and b are equal or not(if not
equal cndition is true)
> checks if left operand is greater than right
operand
< checks if right operand is greater than left
operand
>= checks if value of left operand is greater than or
equal to the value of right operand
<= checks if value of right operand is greater than or
equal to the value of left operand

- Logical Operators - used to define different logics between multiple


conditions

Operator Function
AND specifies that bothe the conditions mentioned should
be true then only the result will be true
NOT it is used to reverse the meaning of the logical
operator and is used as prefix
OR specifies than the result will be true even if a
single cinditon from the mentioned ones is true

- Bit Operators - these works on bits and performs bit-by-bit operations

Operator Function
& works as AND operator and copies a bit to the
redult only if it exists in both operands
| works as OR and copies a bit if it exists in
either operand
~ works as ones complement and has effect of
flippinf bits
<< works as left shift operator and moves left operands
value to the left by the number of digits specified
>> works as right shift operator and moves the the bits
to right by the numbers of digits specified
\# works as bitwise XOR and if bits same on both
operand then resultant bit 0 otherwise 1

CONSTRAINTS -
these are the rules enforced on data columns of the table and help us
prevent invalid data from being entered into the database.
can be applied at two levels i.e. Table level(apllied to whole table)
and column level (applied to specific columns of the table)

- NOT NULL - by default a column can hold null values and by applying
this constraint specifies that no part of the column can be left null.
it is a column level constraint.(null is not same as no data
it reperesents unknown data)
syntax - CREATE TABLE employees(
id PRIMARY KEY NOT NULL
);
- UNIQUE - this prevents two records from having identical values in a
particulaar column
syntax - CREATE TABLE employees(
age int NOT NULL UNIQUE
);
- PRIMARY KEY - uniquely identifies each record in a database
table,there can be more than one unique columns but only one primary key.
the column wth primary key constraint cant contain null
values and are used as foreign key when we link two tables
syntax - CREATE TABLE employees(
id int PRIMARY KEY
) ;
- FOREIGN KEY - these specify that the values in a column must match
the values appearing in some row of another table.it maintains a
refrential identity between two related tables and are also called
refrencing keys
syntax - CREATE TABLE employees(
department_id int refrences department(dept_id)
);
- CHECK - this costraint enables condition to check the values being
entered into the record, if condition evaluates to false , the record
violates the constraint and is not entred into the table
syntax - CREATE TABLE employees(
salary real CHECK(salary>0)
);
- EXCLUSION - it ensures that if any two rows are compared on the
specified columns or expressions using the specified operators , at least
one of these operator comparison will return false or null.it helps
maintain data integrity by enforcing rules that prevent
conflicting or invalid data from being entered into the database.
syntax - CREATE TABLE table_name (
column1 data_type,
column2 data_type,
...,
EXCLUDE USING gist (column_name WITH operator)
);

JOINS CLAUSE - used to combine records from two or more tables in a database, it
refers for combining fields from two tables by using values common to each.

Types of joins -

- CROSS JOIN - it matches every row of the first table with every row
of the second table(id table1 contains x column and table2 contains y
columns then cross join will contain x+y columns)
it has the capability to generate extremely large tables
syntax - SELECT .... FROM table1 CROSS JOIN table2;
example - SELECT * FROM employee CROSS JOIN department;
o/p - id | name | age | address | salary | join_date
| id | dept | emp_id
----+-------+-----+------------+--------+------------
+----+-----------------------+--------
1 | Paul | 32 | California | 20000 | 2001-07-13 |
1 | IT Billing | 1
3 | Teddy | 23 | Norway | 20000 | |
1 | IT Billing | 1
4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 |
1 | IT Billing | 1
5 | David | 27 | Texas | 85000 | 2007-12-13 |
1 | IT Billing | 1
2 | Allen | 25 | Texas | | 2007-12-13 |
1 | IT Billing | 1
8 | Paul | 24 | Houston | 20000 | 2005-07-13 |
1 | IT Billing | 1
9 | James | 44 | Norway | 5000 | 2005-07-13 |
1 | IT Billing | 1
10 | James | 45 | Texas | 5000 | 2005-07-13
| 1 | IT Billing | 1
1 | Paul | 32 | California | 20000 | 2001-07-13 |
2 | Engineering | 2
3 | Teddy | 23 | Norway | 20000 | |
2 | Engineering | 2
4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 |
2 | Engineering | 2
5 | David | 27 | Texas | 85000 | 2007-12-13 |
2 | Engineering | 2
2 | Allen | 25 | Texas | | 2007-12-13 |
2 | Engineering | 2
8 | Paul | 24 | Houston | 20000 | 2005-07-13 |
2 | Engineering | 2
9 | James | 44 | Norway | 5000 | 2005-07-13 |
2 | Engineering | 2
10 | James | 45 | Texas | 5000 | 2005-07-13
| 2 | Engineering | 2
1 | Paul | 32 | California | 20000 | 2001-07-13 |
3 | Finance | 7
3 | Teddy | 23 | Norway | 20000 | |
3 | Finance | 7
4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 |
3 | Finance | 7
5 | David | 27 | Texas | 85000 | 2007-12-13 |
3 | Finance | 7
2 | Allen | 25 | Texas | | 2007-12-13 |
3 | Finance | 7
8 | Paul | 24 | Houston | 20000 | 2005-07-13 |
3 | Finance | 7
9 | James | 44 | Norway | 5000 | 2005-07-13 |
3 | Finance | 7
10 | James | 45 | Texas | 5000 | 2005-07-13
| 3 | Finance | 7
(24 rows)
- INNER JOIN - to combine rows from two or more tables based on a
related column between them. The term "inner" refers to the fact that it
selects only the rows that have matching values in both tables.brings
together related information from different tables, showing only
the data where there's a match between the tables based on a specified condition.
syntax - SELECT .... FROM table1 INNER JOIN table2 ON
table1.col_name =table2.col_name;
example - SELECT * FROM employee AS e INNER JOIN department
AS d ON e.id =d.emp_id ;
o/p - id | name | age | address | salary | join_date
| id | dept | emp_id
----+-------+-----+------------+--------+------------
+----+----------------+--------
1 | Paul | 32 | California | 20000 | 2001-07-13
| 1 | IT Billing | 1
2 | Allen | 25 | Texas | | 2007-12-13
| 2 | Engineering | 2
(2 rows)

- THE LEFT OUTER JOIN - fetches all the records from the left table and
only the matching records from the right table based on a specified
condition, filling in NULL values for the columns from the right table where
there's no match.
syntax - SELECT .... FROM table1 LEFT OUTER JOIN table2 ON
table1.col_name=table2.col_name;
example - SELECT * FROM employee AS e INNER JOIN department
AS d ON e.id =d.emp_id ;
o/p - id | name | age | address | salary | join_date
| id | dept | emp_id
----+-------+-----+------------+--------+------------
+----+-----------------------------+--------
1 | Paul | 32 | California | 20000 | 2001-07-13 |
1 | IT Billing | 1
2 | Allen | 25 | Texas | | 2007-12-13 |
2 | Engineering | 2
10 | James | 45 | Texas | 5000 | 2005-07-13
| | |
5 | David | 27 | Texas | 85000 | 2007-12-13 |
| |
8 | Paul | 24 | Houston | 20000 | 2005-07-13 |
| |
4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 |
| |
3 | Teddy | 23 | Norway | 20000 | |
| |
9 | James | 44 | Norway | 5000 | 2005-07-13 |
| |
(8 rows)

- THE RIGHT OUTER JOIN - fetches all the records from the right table
and only the matching records from the left table based on a specified
condition, filling in NULL values for the columns from the left table
where there's no match.
syntax - SELECT .... FROM table1 RIGHT OUTER JOIN table2 ON
table1.col_name=table2.col_name;
example - SELECT * FROM employee AS e RIGHT OUTER JOIN
department AS d ON e.id =d.emp_id ;
o/p - id | name | age | address | salary | join_date
| id | dept | emp_id
----+-------+-----+------------+--------+------------
+----+-----------------------------+--------
1 | Paul | 32 | California | 20000 | 2001-07-13 |
1 | IT Billing | 1
2 | Allen | 25 | Texas | | 2007-12-13 |
2 | Engineering | 2
| | | | |
| 3 | Finance | 7
(3 rows)

- THE FULL OUTER JOIN - fetches all the records from both tables,
combining them based on a specified condition. It ensures that no data is
left out, including both matching and non-matching records from both
tables, with NULL values filling in where there are no matches.
syntax - SELECT .... FROM table1 FULL OUTER JOIN table2 ON
table1.col_name=table2.col_name;
example - SELECT * FROM employee AS e FULL OUTER JOIN
department AS d ON e.id =d.emp_id ;
o/p - id | name | age | address | salary |
join_date | id | dept | emp_id
----+-------+-----+------------+--------
+------------+----+--------------------+--------
1 | Paul | 32 | California | 20000 | 2001-07-13 |
1 | IT Billing | 1
2 | Allen | 25 | Texas | | 2007-12-13 |
2 | Engineering | 2
| | | | |
| 3 | Finance | 7
10 | James | 45 | Texas | 5000 | 2005-07-13
| | |
5 | David | 27 | Texas | 85000 | 2007-12-13 |
| |
8 | Paul | 24 | Houston | 20000 | 2005-07-13 |
| |
4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 |
| |
3 | Teddy | 23 | Norway | 20000 | |
| |
9 | James | 44 | Norway | 5000 | 2005-07-13 |
| |
(9 rows)

UNION - is used to combine the results of multiple SELECT statements into a single
result set, ensuring compatibility between the columns and removing
duplicates while preserving the order of the first SELECT statement.
syntax - SELECT statement 1
UNION
SELECT statement 2
example - SELECT * FROM employee AS e FULL OUTER JOIN department AS d ON
e.id =d.emp_id
UNION
SELECT * FROM employee AS e INNER JOIN department AS d ON e.id
=d.emp_id ;
o/p - id | name | age | address | salary | join_date | id |
dept | emp_id
----+-------+-----+------------+--------+------------+----
+-----------------------+--------
4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 | |
|
10 | James | 45 | Texas | 5000 | 2005-07-13 | |
|
| | | | | | 3 | Finance
| 7
1 | Paul | 32 | California | 20000 | 2001-07-13 | 1 | IT Billing
| 1
2 | Allen | 25 | Texas | | 2007-12-13 | 2 | Engineering
| 2
8 | Paul | 24 | Houston | 20000 | 2005-07-13 | |
|
5 | David | 27 | Texas | 85000 | 2007-12-13 | |
|
9 | James | 44 | Norway | 5000 | 2005-07-13 | |
|
3 | Teddy | 23 | Norway | 20000 | | |
|
(9 rows)

UNION ALL - works same as union in combining the sets but doesnt removes the
duplicate rows (difference)
syntax - SELECT statement 1
UNION
SELECT statement 2
example - SELECT * FROM employee AS e FULL OUTER JOIN department AS d ON
e.id =d.emp_id
UNION ALL
SELECT * FROM employee AS e INNER JOIN department AS d ON e.id
=d.emp_id ;
o/p - id | name | age | address | salary | join_date | id |
dept | emp_id
----+-------+-----+------------+--------+------------+----
+------------------------------+--------
1 | Paul | 32 | California | 20000 | 2001-07-13 | 1 | IT Billing
| 1
2 | Allen | 25 | Texas | | 2007-12-13 | 2 | Engineering
| 2
| | | | | | 3 | Finance
| 7
10 | James | 45 | Texas | 5000 | 2005-07-13 | |
|
5 | David | 27 | Texas | 85000 | 2007-12-13 | |
|
8 | Paul | 24 | Houston | 20000 | 2005-07-13 | |
|
4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 | |
|
3 | Teddy | 23 | Norway | 20000 | | |
|
9 | James | 44 | Norway | 5000 | 2005-07-13 | |
|
1 | Paul | 32 | California | 20000 | 2001-07-13 | 1 | IT Billing
| 1
2 | Allen | 25 | Texas | | 2007-12-13 | 2 | Engineering
| 2
(11 rows)

TRIGGERS - these are databse callback functions, whcih are automatically


performed/invoked when a specifies database event occurs
We can specify the moment when a trigger is to be invoked (before,after or
inplace of the query performed)
-a trigger marked for each row is called once for every row that the
operation modifies.
-a trigger marked for each statemnt execute once for any given operation ,
regardless of how many rows it modifies
syntax - CREATE TRIGGER trigger_name trigger_time trigger_event
ON table_name FOR EACH ROW
BEGIN
.....
END;
#here trigger_time-> BEFORE,AFTER |trigger_event->
INSERT,UPDATE,DELETE
example - CREATE TRIGGER orders_history_trigger
AFTER INSERT ON orders
FOR EACH ROW
EXECUTE FUNCTION log_order_history();

INDEXES - these are special look up tables that the database search engine can use
to speed up data retrieval
- in easy terms it s a pointer to data in a table and i generally made on the
column/s on which you search frequently
- these are special look up tables that database engine looks upto to speed
up database retrieval
- can only be used in table in which it fetches and for updation / insertion
the headover increases
- can created or dropped with no effect on actual data
syntax - CREATE INDEX index_name
ON table_name (column1, column2, ...);
example - CREATE INDEX idx_customer_id
ON customers (customer_id);

Types of INDEXES -
- SINGLE-COLUMN INDEXES - created based on one table column
syntax - CREATE INDEX index_name
ON table_name (column);

- MULTI-COLUMN INDEXES - created on more than one column of a table


syntax - CREATE INDEX index_name
ON table_name(col1,col2,...coln);

- UNIQUE INDEXES - used not only for performance but also for data
integrity , this doesn't allow any duplicate values to be inserted into
the table
syntax - CREATE UNIQUE INDEX index_name
ON table_name (column);

- PARTIAL INDEXES - it is a index built over a subset of a table; the


subset is defined by the conditional expression, the index contains
value of only those table rows that satisfy the
predicate
syntax - CREATE INDEX index_name
ON table_name(conditional_expression);

- IMPLICIT INDEXES - indexes automatically created by database server


when an object is created such as for primary key?unique key constraints
syntax - #CREATE INDEX salary_index ON company(salary)
to list down all the indexes present -> \d company
to list down indexes of entire databse -> \di

- DROP INDEX - used to drop an existing index


syntax - # DROP INDEX salary_index;

DONT'S of INDEX -
- not to be used on small table
- not to be used on tables that have large update or insert operations
- not to be used on columns that have high no of null values
- no to be used on columns that are frequently manipulated
ALTER TABLE COMMAND - used to add , delete, modify columns, add/drop constraints in
a table
syntax - ALTER TABLE table_name ADD column_name datatype;

DROP COLUMN - ALTER TABLE table_name DROP COLUMN column_name;


CHANGE DATA TYPE - ALTER TABLE table_name ALTER COLUMN col_name
datatype datatype_name
ADD UNIQUE CONSTRAINT - ALTER TABLE table_name ADD CONSTRAINT
MyUniqueConstraint UNIQUE(column_name)
ADD PRIMARY KEY CONSTRAINT - ALTER TABLE table_name ADD CONSTRAINT
MyPrimaryKey PRIMARY KEY(colmn_name);
DROP CONSTRAINT - ALTER TABLE table_name DROP CONSTRAINT
Constraint_name;

VIEW - these are pseudo tables i.e. they are not real tables but still appear as
table to the select statement
- it represents a subset of a real table , selecting certain columns or
certain rows from the real table
- it can also represent joined tables
- as views are assigned certain permissions, you can use them to restrict
access to the table so that the user see only specific field or data of the
column

Permissions granter to users by view -


- data can be structured in a way that users or
classes of users find natural or intuitive
- restrict access to table by allowing them to see
only specific column/data
- summarize data from various tables(can be used to
generate reports)

Creating VIEW - view can be created from a table, multiple table or from
another view
syntax - CREATE [TEMP|TEMPORARY] VIEW view_name AS
SELECT .......
# multiple select statements can be used , temp is used
we want to keep the view only in the current session
#fetched same way as a normal table

Drop VIEW - used to delete view


syntax - DROP VIEW view_name

TRANSACTIONS - it is a unit of work performed on a database


- it can be a unit or sequence of work accompalished in logical
order, either manually or automatically.
- it is important to control transaction to ensure high data
integrity and to handle database errors

Properties of transaction -
Atomicity - ensures that all operations within the work unit are
completed successfully ;if not then the transaction is aborted at
the time of failure and the previous operations are rolled back to their
former state
Consistency - ensures that the database properly changes state
upon successfully complition of transaction
Isolation - enables transactions to operate independently and
tranparently
Durabilty - ensures that the result or effect of a committed
transaction persists in case of a system failure

Transaction Control Commands - only used with the DML commands


BEGIN TRANSACTION - used to start a transaction
syntax - BEGIN | BEGIN TRANSACTION

COMMIT - used to save changes after the last commit or


rollback(you can use END TRANSACTION COMMAND)
syntax - COMMIT | END TRANSACTION

ROLLBACK - used to rollback to the last commit


syntax - ROLLBACK;

LOCKS - these prevent users from modifying a row or entire table preventing other
users from changing the row until the transaction is either committed or rolled
back , the only time when the use must wait for the other user is when they are
trying to modify the same row(if modifying different row no need to
wait,select query never have to wait),generally databse performs locking
automatically,in certain cases, locking must be controlled manuallyby using
lock command
syntax - LOCK [table] name IN lock_mode
# name - refers to the existing table we want to lock(if ONLY is
specified before lock then only that table will be locked otherwise thta
table and all its decendant tables will be locked)
# lock_mode - specifies which locks this lock conflicts with(if no lock
mode is specified then the most restrictive mode -ACCESS EXCLUSIVE is
used)other possible values - ACCESS SHARE, ROW SHARE, ROW EXCLUSIVE,SHARE
UPDATE EXCLUSIVE,SHARE,SHARE RW EXCLUSIVE.
EXCLUSIVE LOCKING - it means they're the only one allowed to make changes to
it until they're finished.

DEADLOCKS - it occurs when two transactions are waiting for each other to
finish

ADVISORY LOCKS - these are locks not strong as others but help provide with
an advisory warning(faster than flags and are automatically cleaned up at
te end of the session)

SUBQUERY - also known as inner query or nested query is a query within another
query nested inside the where clause
it returns data that will be used as a condition to further
restrict the data to be retrieved by the main query
these can be used with dml command along with different
comparison operators

Rules for subquery -


- must be enclosed withtin()
- can have only one column in the select clause unless multiple
columns are there in the main query to be compared with
- order by can't be used
- subquery that return more than one row cannot use multiple value
operator such as in, exists,not in,any/some,all operator
- between operator cannot be used with the subquery but can be used
within in
- can be used with SELECT, INSERT,UPDATE AND DELETE COMMANDS

AUTO INCREMENT -
SERIAL COLUMNS - it is a datatype when used which some column creates
special columns used to automatically generate unique numbers, often
used as identifiers for rows in a table.
Three sizes -
- smallserial is for smaller numbers.
- serial is for regular-sized numbers.
- bigserial is for really big numbers.
syntax - CREATE TABLE table_name(
colname SERIAL
)
example - CREATE TABLE COMPANY(
ID SERIAL PRIMARY KEY,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
SALARY REAL
);
# now whenever you add data into the table you dont need
to add data for column id , it will automatically be generated
o/p- id | name | age | salary
----+----------+-----+--------
1 | aarzoo | 21 | 10000
2 | abhishek | 21 | 17000
3 | sunita | 22 | 35000
4 | tanya | 21 | 15000
(4 rows)

PRIVILEDGE - it refers to the permissions a person have to manipulate or view or do


anything related to a database
wheneveran object is created in a database,an owner is assigned to it
which is usuallt the one who executes the create statement
to allow other users to use it, priviledges or permission must be
granted

Priviledges - select
insert
update
delete
truncate
refrences
trigger
create
connect
temporary
execute
usage

GRANT - allowing other user some priviledge


syntax - GRANT priviledge[,....]
ON object [,...]
TO { PUBLIC | GROUP group | username }
# priviledges could be the values mentioned above
# object can be table,view,sequence
# PUBLIC refers to all users
# GROUP group refers to the group you want to grant
priviledge to
# username when you want to provide priviledge to
particular person only

REVOKE - removing / revoking priviledge provided to someone


syntax - GRANT priviledge[,....]
ON object [,...]
TO { PUBLIC | GROUP group | username }

DATE/TIME FUNCTIONS AND OPERATORS -

OPERATOR -
- '+' - used to add different elements based on real
scenario
example
result
date '2001-09-28' + integer '7'
date '2001-10-05'
date '2001-09-28' + interval'1 hour'
timestamp'2001-09-28 01:00:00'
date '2001-09-28' + time '03:00' timestamp
'2001-09-28 03:00:00'
interval'1 day' + interval '1 hour' interval '1
day 01:00:00'

- '-' - used to do the subtraction the same way

- '*' - used to multiply the time / interwal with integer


example result
900 * interval '1 second' interval
'00:15:00'
21 * interval '1 day' interval
'21 days'

- '/' - used to divide with the integer


example result
interval '1 hour' / double precision '1.5'
interval '00:40:00'

IMPORTANT DATE TIME FUNCTIONS -


- AGE() - used to calculate the age by using the time difference
between either two time stamp or by using the time stamp and the current
date
syntax - AGE(timestamp,timestamp)

syntax - AGE(timestamp)

- CURRENT DATE/TIME - there are number of functions that return values


related to current data and time

Function Description
CURRENT_DATE delivers current date
CURRENT_TIME delivers value with time
zone
CURRENT_TIMESTAMP delivers value with time zone
CURRENT_TIME(precision) optionally takes a
precision parameter which causes the result to be rounded to that
many fractional digit in the second fields
CURRENT_TIMESTAMP(precision) same as above
LOCALTIME delivers value without time
zone
LOCALTIMESTAMP delivers value without
time zone
LOCALTIME(precision) optionally takes a
precision parameter which causes the result to be rounded to that
many fractional digit in the second fields
LOCALTIMESTAMP(precision) optionally takes a
precision parameter which causes the result to be rounded to that
many fractional digit in the second fields
transaction_timestamp() equivalent to
CURRENT_TIMESTAMP
statement_timestamp() returns start time of
the current statement
clock_timestamp() returns the actual
current time and its value changes even withtin asingle sql command
timeofday() returns actaul current
time ,but as a formatted text string rather than a timestamp
with time zone value
now() equivalent to
transaction_timestamp

- DATE_PART() -

Function Description
DATE_PART('field',source) here the field parameter
needs to be a string value not a name
DATE_TRUNC('field',source) similar to trunc for
numbers
- EXTRACT -

Function Description
EXTRACT('feild' from timestamp) used to extract
subfields from date/time values
EXTRACT('field' from interval) used to extract
from source value

- ISFINITE() -

Function Description
ISFINITE(date) tests for finite date
ISFINITE(timestamp) tests for finite
timestamp
ISFINITE(interval) tests for finite
interval

- JUSTIFY -

Function Description
JUSTIFY_DAYS(interval) adjusts interval so 30-
days interval is shown as months,return the interval types
JUSTIFY_HOURS(interval) adjusts interval so 24-
hours interval is shown as days,return the interval types
JUSTIFY_INTERVAL(interval) adjusts days using
JUSTIFY_HOURS and JUSTIFY_DAYS,with additional sign adjustments

FUNCTIONS - stored procedures allowing us to do task that require multiple queries


to execute a task
it allows database reuse as other applications can interact directly with
your stored procedures instead of middle-tier or duplicating compared
syntax - CREATE [OR REPLACE] FUNCTION function_name (argument)
RETURNS return_datatype AS $variable_name$
DECLARE
declaration;
[...]
BEGIN
<function body>
[......]
RETURN {variable_name |value }
END ; LANGUAGE plpgsql;

Useful built-in functions -


- COUNT - counts the occurance of an object
- MAX - identifies the max value
- MIN - identifies the min value
- AVG - calculates the average value of the the column
- SUM - calculates the overall sum
- ARRAY - puts input values,including nulls,concatenated
into an array
- NUMERIC - required to manipulate numbers in sql
- STRING - required to manipulate string

You might also like