SQLW I T H
P O S T G R E S Q L
R A J E E V S R I V A S T A V A ( R A J E E V S @ C D A C . I N )
SQL
• Stands for “Structured Query Language”
• Also pronounced as “SEQUEL” (Structured English QUEry Language)
• Standard access mechanism to every RDBMS.
• Case Insensitive
• Standard Based; SQL Standards are defined by ANSI (American National
Standards Institute)
• First Standard Published in 1989; Latest is 2016
Feb, 2019 rajeevs@cdac.in 2
COMPONENTS (CATEGORIES) OF SQL
STATEMENTS
• DDL: Data Definition Language(CREATE/ALTER/DROP/TRUNCATE)
• DML: Data Manipulation Language(INSERT/UPDATE/DELETE)
• DCL: Data Control Language (GRANT/REVOKE)
• DTL: Data Transaction Language OR
TCL: Transaction Control Language (COMMIT/ROLLBACK)
• DRL: Data Retrieval Language OR
DQ: Data Query Language (SELECT)
Feb, 2019 rajeevs@cdac.in 3
CREATING A TABLE
• Data in a data base is stored in the form of tables
• The table is a collection of related data entries and it consists of
columns and rows.
SYNTEX -
– CREATE TABLE <table name> (
<col name> <data type>,
<col name> <data type>
– );
Feb, 2019 rajeevs@cdac.in 4
CONSIDERATIONS FOR CREATING
TABLE
Points to be considered before creating a table -
– What are the attributes of the tuples to be stored?
– What are the data types of the attributes? Should varchar be used instead
of char ?
– Which column(s) build the primary key?
– Which columns should be defined as unique?
– Which columns do (not) allow null values? Which columns do (not) allow
duplicates ?
– Are there default values for certain columns?
Feb, 2019 rajeevs@cdac.in 5
POSTGRESQL: DATA TYPES
• Data Type defines what kind of values can be stored in a column.
• Data Type also defines the way data will be stored in the system and the space
required in disk.
• Data Type also impacts database performance.
• Ex- Char, Varchar, Text, Integer, Numeric, Date, Time, Timestamp, Boolean,
UUID, Array JSON.
• More on PostgreSQL Datatypes :
https://www.postgresql.org/docs/11/datatype.html
Feb, 2019 rajeevs@cdac.in 6
INSERT COMMAND
• Used to insert data into a table
• Insert command always inserts values as new row
Syntax -
INSERT INTO <table name> VALUES (<val 1>, <val 2>);
• Insert data into specific columns of a table -
INSERT INTO <table name> (<col1>) VALUES (<value>);
• Define an insertion order -
INSERT INTO <table name> (<col 2>, <col 1> ) VALUES (<val 2>, <val 1>);
• Missing attribute ® NULL.
• May drop attribute names if give them in order
Feb, 2019 rajeevs@cdac.in 7
CRUD OPERATIONS
Operation SQL Command
CREATE INSERT
READ SELECT
UPDATE UPDATE
DELETE DELETE/TRUNCATE
Feb, 2019 rajeevs@cdac.in 8
SELECT COMMAND
• Used to Retrieve/Fetch information from the database.
Syntax :
SELECT <col name> FROM <table name> [WHERE <condition>];
SELECT <col1>, <col2> FROM <table name> [WHERE <condition>];
An asterisk symbol (*) Represents all columns/attributes.
Feb, 2019 rajeevs@cdac.in 9
SELECTION & PROJECTION
• SELECTION – limiting rows selection (by using WHERE clause)
– SELECT * FROM <table name> WHERE <col1> = <val1> ;
• PROJECTION – limiting columns selection (by using SELECT clause)
– SELECT <col1>, <col2> FROM <table name>;
Feb, 2019 rajeevs@cdac.in 10
ALTER TABLE
• Syntax
– To modify/change an existing column
ALTER TABLE <tablename> ALTER COLUMN <col1> <new data type>;
– To add new column
ALTER TABLE <tablename> ADD COLUMN <col> <data type>;
– To rename an existing column
ALTER TABLE <tablename> RENAME COLUMN <col> TO <new col name>;
– To drop/remove an existing column
ALTER TABLE <tablename> DROP COLUMN <col>;
Feb, 2019 rajeevs@cdac.in 11
NULL VALUE
• When you do not insert data into a column of a table for a specific row then by
default a NULL value will be inserted into that column by the database.
INSERT INTO dept (deptno, deptname) VALUES (40, ’BIOM’);
• NULL value does not occupy space in memory
• NULL value is independent of a data type
• A NULL value is not a zero (0) OR an empty string (‘ ’), rather it represents an
Unknown or Not applicable value.
Feb, 2019 rajeevs@cdac.in 12
UPDATE COMMAND
• This command inserts or modifies values in the cells in existing rows
• This command can also be used for deleting values from a cell of a table
without the need for deleting a row or a column
Syntax
• UPDATE <table name> SET <col name> = <new value> [WHERE <condition>];
Feb, 2019 rajeevs@cdac.in 13
DELETE COMMAND
• This command is used for deleting specific or all the rows from a table
Syntax
DELETE FROM <table name> [WHERE <condition>];
Feb, 2019 rajeevs@cdac.in 14
TRUNCATE COMMAND
• This command can also be used for deleting all the rows from a table
Syntax
TRUNCATE TABLE <table name>;
• Truncate command cannot be rolled back because it is a AUTO COMMIT
operation, i.e. changes committed cannot be rolled back. But DELETE is not a
AUTO COMMIT operation. Hence DELETE can be ROLLED BACK.
• Truncate is a DDL Command.
Feb, 2019 rajeevs@cdac.in 15
DROP COMMAND
• DROP command can be used for permanently deleting database objects like
table, view, function etc. from a database
Syntax
DROP TABLE <table name>;
Feb, 2019 rajeevs@cdac.in 16
CONSTRAINTS
• PRIMARY KEY
• FOREIGN KEY
• UNIQUE
• NOT NULL
• DEFAULT
• CHECK
Feb, 2019 rajeevs@cdac.in 17
RELATIONAL OPERATORS
Operator Description Example
=
Checks if the values of two operands are equal or not, if yes
then condition becomes true.
(A=A) is true
(A = B) is not true.
!=
<>
Checks if the values of two operands are equal or not, if
values are not equal then condition becomes true.
(A != B) is true.
>
Checks if the value of left operand is greater than the value
of right operand, if yes then condition becomes true.
(A > B) is not true.
<
Checks if the value of left operand is less than the value of
right operand, if yes then condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than or equal
to the value of right operand, if yes then condition
becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal to
the value of right operand, if yes then condition
becomes true.
(A <= B) is true
Feb, 2019 rajeevs@cdac.in 18
BETWEEN … AND… OPERATOR
• This operator is used as a replacement for relational (>, <) and logical
operators (AND, OR)
• The lower limit must be <= upper limit
• SELECT * FROM emp WHERE sal BETWEEN 10000 AND 20000;
Feb, 2019 rajeevs@cdac.in 19
IS NULL OPERATORS
• Used for testing for the existence of NULL values in any column
• Ex. Display the details of those employees who are not having any job
SELECT * FROM emp WHERE job IS NULL:
IS NOT NULL
SELECT * FROM emp WHERE job IS NOT NULL:
• Null value cannot be compared. Hence you cannot use relational
operators for comparing NULL value with a column
• Therefore IS NULL operator has to be used for the purpose
Feb, 2019 rajeevs@cdac.in 20
IN OPERATOR
• This operator is used to compare multiple values with a single
column
• In this operator, values supplied must be of the same type and
they should belong to only 1 column
• This operator is a replacement for multiple OR operators
– SELECT * FROM emp WHERE job IN (‘PE', ‘TO‘, ‘SE’);
Feb, 2019 rajeevs@cdac.in 21
LIKE OPERATOR - % AND _
• This operator is used for comparing characters/numbers in a
value from a specific position
• % ignores variable number of characters
• _ ignores only 1 char
• Display the details of those emps whose name is starting with ‘r’
SELECT * FROM emp WHERE ename LIKE 'r%‘;
• Display the details of those emps who have ‘h’ as second
character in their name -
SELECT * FROM emp WHERE ename LIKE ‘_h%‘;
Feb, 2019 rajeevs@cdac.in 22
DISTINCT - ELIMINATING DUPLICATES
• DISTINCT command is used to select only unique values from a column.
• i.e. only single occurrence of a value will be returned.
SELECT DISTINCT job FROM EMP;
SELECT DISTINCT loc FROM dept;
Feb, 2019 rajeevs@cdac.in 23
FUNCTIONS
• Function is a Sub Program which performs a specific task
• Every function returns only 1 value
• Functions in database can be used or defined for
– Performing calculations which are not possible/easy using
operators
– Formatting text/numbers/dates
– Type casting i.e. converting one type of data into another
– To fetch information from system schema. Eg. VERSION()
Feb, 2019 rajeevs@cdac.in 24
FUNCTION – TYPES AND USES
• Types of Functions
– System defined functions
– User defined functions
• Syntax -
SELECT <function name(args)> [FROM <table name>];
Feb, 2019 rajeevs@cdac.in 25
FUNCTIONS – SYSTEM DEFINED
• Numeric functions
• String functions
• Date and Time functions
• Type Casting funtions
• Aggregate functions
More Functions -
– https://www.postgresql.org/docs/current/functions.html
Feb, 2019 rajeevs@cdac.in 26
FEW FUNCTIONS
Aggregate Functions
• COUNT() – Gives count of occurrences; Works on All data types.
• AVG() – Average. Works only on Numeric values
• SUM() – Gives total/sum. Works only on Numeric values
• MAX() – Maximum Value. All data types
• MIN() – Minimum Value. All data types
Feb, 2019 rajeevs@cdac.in 27
REAL TIME USE OF FUNCTIONS
SELECT UPPER(dname) FROM dept;
SELECT MAX(sal) FROM emp;
SELECT SUM(sal), AVG(SAL) FROM emp;
Feb, 2019 rajeevs@cdac.in 28
JOINS
• Join is a technique of retrieving data from multiple tables
• Display the ename AND dname from emp and dept tables
SELECT ename, dname FROM emp, dept WHERE emp.deptno =
dept.deptno;
• Display the ename and dname of those emps whose sal is > 20000
SELECT ename, dname, sal FROM emp, dept WHERE emp.deptno =
dept.deptno AND sal > 20000;
Feb, 2019 rajeevs@cdac.in 29
SUBQUERIES
• It is a query within some other query
• Display the details of those employees who are getting a sal > Aditya
SELECT * FROM emp WHERE sal > (SELECT sal FROM emp WHERE
ename = ‘Aditya’;
• Display details of all employees who work in department ‘SENG’;
SELECT * FROM emp WHERE DEPTNO = (SELECT deptno FROM dept
WHERE dname = ‘SENG’);
Feb, 2019 rajeevs@cdac.in 30
MORE SUBQUERIES EXAMPLES
• Display the maximum salary from every department and also the name
of that employee who is getting the maximum Salary.
SELECT ename, sal, deptno FROM emp WHERE (deptno, sal) IN
(SELECT deptno, max(sal) FROM emp GROUP BY deptno);
Feb, 2019 rajeevs@cdac.in 31
MORE SQL CLAUSES
• ORDER BY (if used, ORDER BY must by last clause of a query, except when you
have used LIMIT Clause)
– SELECT * FROM EMP ORDER BY SAL;
– SELECT * FROM EMP ORDER BY SAL DESC;
– SELECT * FROM EMP ORDER BY SAL DESC, ENAME;
• GROUP BY
– SELECT DEPTNO, SUM(SAL) FROM EMP GROUP BY DEPTNO;
• GROUP BY….HAVING
– SELECT DEPTNO, SUM(SAL) FROM EMP GROUP BY DEPTNO HAVING SUM(SAL) <
50000;
Feb, 2019 rajeevs@cdac.in 32
LIMITING NO OF RECORDS
• LIMIT clause is used to limit number of records return in a SELECT query.
• Its not part of SQL standard, works in PostgreSQL and few other RDBMS.
• Unexceptionally, must be the last clause of a query.
SELECT * FROM emp LIMIT 2;
SELECT * FROM emp ORDER BY sal DESC LIMIT 3;
Feb, 2019 rajeevs@cdac.in 33
COPYING TABLE/DATA
• A copy of the table (with, without or selected data)can be created using
SELECT command
CREATE table dept_copy AS SELECT * FROM dept;
CREATE table emp_pe AS SELECT * FROM emp WHERE job = ‘PE’;
CREATE table emp_new AS SELECT * FROM emp WHERE 1=2
• To copy only data of a table to another table
INSERT INTO emp_seng SELECT * FROM emp WHERE deptno = (SELECT deptno
FROM dept WHERE dname = ‘SENG’);
INSERT INTO emp_seng SELECT * FROM emp WHERE deptno = 10;
Feb, 2019 rajeevs@cdac.in 34
COMMIT, SAVEPOINT & ROLLBACK
• By default autocommit parameter is ON in PostgreSQL and can be
reconfigured by PostgreSQL Administrator. A user can set autocommit
parameter to ON & OFF for herself using alter command.
• Savepoint and Rollback commands will be effective only when autocommit is
OFF;
• System (PostgreSQL Engine) autocommits all uncommitted operations before
executing any DDL command.
COMMIT;
SAVEPOINT <variable name>;
ROLLBACK [ TO <variable name>];
Feb, 2019 rajeevs@cdac.in 35
GRANT & REVOKE
• GRANT command is used to give selected/all DML and DDL command
privileges to other database user;
GRANT [PRIVILEGES] ON <tablename> TO ‘<username>‘;
GRANT [PRIVILEGES] ON <tablename> TO ‘<username>‘ WITH GRANT OPTION;
• REVOKE command is used to REVOKE command privileges given to other
database user using GRANT Command;
REVOKE [PRIVILEGES] ON <tablename> FROM ‘<username>‘;
Feb, 2019 rajeevs@cdac.in 36
ADDING A CONSTRAINT AFTER
CREATION OF A TABLE
• Any type of constraint can be added or dropped even after creation of table.
PRIMARY KEY
ALTER TABLE <tablename> ADD CONSTRAINT <constraintname> PRIMARY KEY (<column
name>);
ALTER TABLE <tablename> ADD PRIMARY KEY (<columnname>);
ALTER TABLE <tablename> DROP PRIMARY KEY;
UNIQUE
ALTER TABLE <tablename> ADD CONSTRAINT <constraintname> <UNIQUE>;
ALTER TABLE <tablename> DROP INDEX <constraintname>;
DEFAULT
ALTER TABLE <tablename> ALTER <column name> SET DEFAULT <default value>;
ALTER TABLE <tablename> ALTER <column name> DROP DEFAULT;
Feb, 2019 rajeevs@cdac.in 37
JOIN TYPES : SQL STANDARD SYNTAX
• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from
the right table
• RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records
from the left table
• FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
SELECT <column names> FROM <table name1> [LEFT |RIGHT] OUTER JOIN
<tablename2> ON <tablename1>.<column name> = <tablename2>.<column
name>;
Feb, 2019 rajeevs@cdac.in 38
INNER JOIN: EXAMPLES
SELECT empno, ename, sal, dname
FROM dept JOIN emp
ON dept.deptno = emp.deptno;
SELECT *
FROM dept JOIN emp
ON dept.deptno = emp.deptno;
Feb, 2019 rajeevs@cdac.in 39
LEFT OUTER JOIN: EXAMPLE
SELECT empno, ename, sal, dname
FROM dept LEFT OUTER JOIN emp
ON dept.deptno = emp.deptno;
SELECT *
FROM dept LEFT OUTER JOIN emp
ON dept.deptno = emp.deptno;
Feb, 2019 rajeevs@cdac.in 40
RIGHT OUTER JOIN: EXAMPLE
SELECT empno, ename, sal, dname
FROM dept RIGHT OUTER JOIN emp
ON dept.deptno = emp.deptno;
SELECT *
FROM dept RIGHT OUTER JOIN emp
ON dept.deptno = emp.deptno;
Feb, 2019 rajeevs@cdac.in 41
SET OPERATIONS: UNION, INTERSECT,
EXCEPT
• Set operations treat the tables as sets and are the usual set operators of union,
intersection, and difference
SELECT * FROM <table name 1>
UNION | INTERSECT I EXCEPT
SELECT * FROM <table name 2>;
• SET operations must fulfil following two conditions –
– Number of columns in the SELECT clause of both[all] queries must be same.
– Data type of respective columns in both[all] queries must be same or
compatible.
Feb, 2019 rajeevs@cdac.in 42
VIEWS
• Views are ‘Virtual Tables’.
• Views does not store data but fetches the data from underlying
tables[s] dynamically at runtime.
CREATE VIEW <view name> AS <Select Query> ;
• All DML operations can be performed on a view and it affects
underlying table.
Feb, 2019 rajeevs@cdac.in 43
INDEXES
• Indexes are database objects used by DBMS to retrieve the data from table in
a faster manner.
• Invisible to end user
• Speed up SELECT queries but slow down INSERTS/UPDATES/DELETES –
CREATE [UNIQUE] INDEX <index name>
ON <table name> (<column name> [, <column name2>],…..’;
• Dropping an Index
DROP INDEX <index name>;
Feb, 2019 rajeevs@cdac.in 44

More Related Content

PPTX
SQL Pass Summit Presentations from Datavail - Optimize SQL Server: Query Tuni...
ODP
Oracle SQL Advanced
ODP
SQL Tunning
PPTX
U-SQL Does SQL (SQLBits 2016)
PDF
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
PPTX
Structure query language (sql)
PPTX
Oracle basic queries
PPT
Oracle Course
SQL Pass Summit Presentations from Datavail - Optimize SQL Server: Query Tuni...
Oracle SQL Advanced
SQL Tunning
U-SQL Does SQL (SQLBits 2016)
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
Structure query language (sql)
Oracle basic queries
Oracle Course

What's hot (20)

PPT
Sql Tutorials
PDF
Oracle SQL Basics
PPTX
Introduction to SQL
PPTX
Oraclesql
PPTX
Lab1 select statement
PPTX
New T-SQL Features in SQL Server 2012
PPT
SQL- Introduction to PL/SQL
PPTX
Database COMPLETE
PPT
Les03 (Using Single Row Functions To Customize Output)
PPT
ORACLE PL SQL
PPTX
SQL Windowing
PPTX
advanced sql(database)
PDF
Window functions with SQL Server 2016
PPT
Explain that explain
PDF
MySQL: Indexing for Better Performance
PDF
Explaining the explain_plan
PDF
Mssql to oracle
PPTX
Exploring Advanced SQL Techniques Using Analytic Functions
PPTX
SQL Assessment Command Statements
PDF
Introduction to Databases - query optimizations for MySQL
Sql Tutorials
Oracle SQL Basics
Introduction to SQL
Oraclesql
Lab1 select statement
New T-SQL Features in SQL Server 2012
SQL- Introduction to PL/SQL
Database COMPLETE
Les03 (Using Single Row Functions To Customize Output)
ORACLE PL SQL
SQL Windowing
advanced sql(database)
Window functions with SQL Server 2016
Explain that explain
MySQL: Indexing for Better Performance
Explaining the explain_plan
Mssql to oracle
Exploring Advanced SQL Techniques Using Analytic Functions
SQL Assessment Command Statements
Introduction to Databases - query optimizations for MySQL
Ad

Similar to Structured Query Language (SQL) - An Introduction (20)

PPTX
Structure Query Language (SQL).pptx
PPT
INTRODUCTION TO SQL QUERIES REALTED BRIEF
PDF
PPSX
MS SQL Server
PPTX
More Complex SQL and Concurrency ControlModule 4.pptx
PDF
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
PPTX
SQL.pptx for the begineers and good know
PDF
SQL Overview
PPTX
Statements,joins and operators in sql by thanveer danish melayi(1)
DOC
Sql Document in Testing
PPTX
DDL,DML,SQL Functions and Joins
PPT
Advanced Sql Training
PPTX
DBMS.pptx
PPTX
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
PPTX
SQL.pptx
PDF
PDF
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
PPTX
Relational Database Management System
PPTX
DBMS and SQL(structured query language) .pptx
PPT
Oracle Sql & PLSQL Complete guide
Structure Query Language (SQL).pptx
INTRODUCTION TO SQL QUERIES REALTED BRIEF
MS SQL Server
More Complex SQL and Concurrency ControlModule 4.pptx
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
SQL.pptx for the begineers and good know
SQL Overview
Statements,joins and operators in sql by thanveer danish melayi(1)
Sql Document in Testing
DDL,DML,SQL Functions and Joins
Advanced Sql Training
DBMS.pptx
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
SQL.pptx
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Relational Database Management System
DBMS and SQL(structured query language) .pptx
Oracle Sql & PLSQL Complete guide
Ad

Recently uploaded (20)

PPTX
GROUP4NURSINGINFORMATICSREPORT-2 PRESENTATION
PDF
CloudStack 4.21: First Look Webinar slides
PDF
Credit Without Borders: AI and Financial Inclusion in Bangladesh
PDF
Enhancing plagiarism detection using data pre-processing and machine learning...
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
Consumable AI The What, Why & How for Small Teams.pdf
PPTX
The various Industrial Revolutions .pptx
PDF
Flame analysis and combustion estimation using large language and vision assi...
PPTX
TEXTILE technology diploma scope and career opportunities
PPT
Geologic Time for studying geology for geologist
DOCX
Basics of Cloud Computing - Cloud Ecosystem
PPTX
Build Your First AI Agent with UiPath.pptx
PPT
Module 1.ppt Iot fundamentals and Architecture
PPTX
Custom Battery Pack Design Considerations for Performance and Safety
PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PPT
What is a Computer? Input Devices /output devices
PDF
Statistics on Ai - sourced from AIPRM.pdf
PPTX
Configure Apache Mutual Authentication
GROUP4NURSINGINFORMATICSREPORT-2 PRESENTATION
CloudStack 4.21: First Look Webinar slides
Credit Without Borders: AI and Financial Inclusion in Bangladesh
Enhancing plagiarism detection using data pre-processing and machine learning...
Getting started with AI Agents and Multi-Agent Systems
Consumable AI The What, Why & How for Small Teams.pdf
The various Industrial Revolutions .pptx
Flame analysis and combustion estimation using large language and vision assi...
TEXTILE technology diploma scope and career opportunities
Geologic Time for studying geology for geologist
Basics of Cloud Computing - Cloud Ecosystem
Build Your First AI Agent with UiPath.pptx
Module 1.ppt Iot fundamentals and Architecture
Custom Battery Pack Design Considerations for Performance and Safety
Final SEM Unit 1 for mit wpu at pune .pptx
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
What is a Computer? Input Devices /output devices
Statistics on Ai - sourced from AIPRM.pdf
Configure Apache Mutual Authentication

Structured Query Language (SQL) - An Introduction

  • 1. SQLW I T H P O S T G R E S Q L R A J E E V S R I V A S T A V A ( R A J E E V S @ C D A C . I N )
  • 2. SQL • Stands for “Structured Query Language” • Also pronounced as “SEQUEL” (Structured English QUEry Language) • Standard access mechanism to every RDBMS. • Case Insensitive • Standard Based; SQL Standards are defined by ANSI (American National Standards Institute) • First Standard Published in 1989; Latest is 2016 Feb, 2019 [email protected] 2
  • 3. COMPONENTS (CATEGORIES) OF SQL STATEMENTS • DDL: Data Definition Language(CREATE/ALTER/DROP/TRUNCATE) • DML: Data Manipulation Language(INSERT/UPDATE/DELETE) • DCL: Data Control Language (GRANT/REVOKE) • DTL: Data Transaction Language OR TCL: Transaction Control Language (COMMIT/ROLLBACK) • DRL: Data Retrieval Language OR DQ: Data Query Language (SELECT) Feb, 2019 [email protected] 3
  • 4. CREATING A TABLE • Data in a data base is stored in the form of tables • The table is a collection of related data entries and it consists of columns and rows. SYNTEX - – CREATE TABLE <table name> ( <col name> <data type>, <col name> <data type> – ); Feb, 2019 [email protected] 4
  • 5. CONSIDERATIONS FOR CREATING TABLE Points to be considered before creating a table - – What are the attributes of the tuples to be stored? – What are the data types of the attributes? Should varchar be used instead of char ? – Which column(s) build the primary key? – Which columns should be defined as unique? – Which columns do (not) allow null values? Which columns do (not) allow duplicates ? – Are there default values for certain columns? Feb, 2019 [email protected] 5
  • 6. POSTGRESQL: DATA TYPES • Data Type defines what kind of values can be stored in a column. • Data Type also defines the way data will be stored in the system and the space required in disk. • Data Type also impacts database performance. • Ex- Char, Varchar, Text, Integer, Numeric, Date, Time, Timestamp, Boolean, UUID, Array JSON. • More on PostgreSQL Datatypes : https://www.postgresql.org/docs/11/datatype.html Feb, 2019 [email protected] 6
  • 7. INSERT COMMAND • Used to insert data into a table • Insert command always inserts values as new row Syntax - INSERT INTO <table name> VALUES (<val 1>, <val 2>); • Insert data into specific columns of a table - INSERT INTO <table name> (<col1>) VALUES (<value>); • Define an insertion order - INSERT INTO <table name> (<col 2>, <col 1> ) VALUES (<val 2>, <val 1>); • Missing attribute ® NULL. • May drop attribute names if give them in order Feb, 2019 [email protected] 7
  • 8. CRUD OPERATIONS Operation SQL Command CREATE INSERT READ SELECT UPDATE UPDATE DELETE DELETE/TRUNCATE Feb, 2019 [email protected] 8
  • 9. SELECT COMMAND • Used to Retrieve/Fetch information from the database. Syntax : SELECT <col name> FROM <table name> [WHERE <condition>]; SELECT <col1>, <col2> FROM <table name> [WHERE <condition>]; An asterisk symbol (*) Represents all columns/attributes. Feb, 2019 [email protected] 9
  • 10. SELECTION & PROJECTION • SELECTION – limiting rows selection (by using WHERE clause) – SELECT * FROM <table name> WHERE <col1> = <val1> ; • PROJECTION – limiting columns selection (by using SELECT clause) – SELECT <col1>, <col2> FROM <table name>; Feb, 2019 [email protected] 10
  • 11. ALTER TABLE • Syntax – To modify/change an existing column ALTER TABLE <tablename> ALTER COLUMN <col1> <new data type>; – To add new column ALTER TABLE <tablename> ADD COLUMN <col> <data type>; – To rename an existing column ALTER TABLE <tablename> RENAME COLUMN <col> TO <new col name>; – To drop/remove an existing column ALTER TABLE <tablename> DROP COLUMN <col>; Feb, 2019 [email protected] 11
  • 12. NULL VALUE • When you do not insert data into a column of a table for a specific row then by default a NULL value will be inserted into that column by the database. INSERT INTO dept (deptno, deptname) VALUES (40, ’BIOM’); • NULL value does not occupy space in memory • NULL value is independent of a data type • A NULL value is not a zero (0) OR an empty string (‘ ’), rather it represents an Unknown or Not applicable value. Feb, 2019 [email protected] 12
  • 13. UPDATE COMMAND • This command inserts or modifies values in the cells in existing rows • This command can also be used for deleting values from a cell of a table without the need for deleting a row or a column Syntax • UPDATE <table name> SET <col name> = <new value> [WHERE <condition>]; Feb, 2019 [email protected] 13
  • 14. DELETE COMMAND • This command is used for deleting specific or all the rows from a table Syntax DELETE FROM <table name> [WHERE <condition>]; Feb, 2019 [email protected] 14
  • 15. TRUNCATE COMMAND • This command can also be used for deleting all the rows from a table Syntax TRUNCATE TABLE <table name>; • Truncate command cannot be rolled back because it is a AUTO COMMIT operation, i.e. changes committed cannot be rolled back. But DELETE is not a AUTO COMMIT operation. Hence DELETE can be ROLLED BACK. • Truncate is a DDL Command. Feb, 2019 [email protected] 15
  • 16. DROP COMMAND • DROP command can be used for permanently deleting database objects like table, view, function etc. from a database Syntax DROP TABLE <table name>; Feb, 2019 [email protected] 16
  • 17. CONSTRAINTS • PRIMARY KEY • FOREIGN KEY • UNIQUE • NOT NULL • DEFAULT • CHECK Feb, 2019 [email protected] 17
  • 18. RELATIONAL OPERATORS Operator Description Example = Checks if the values of two operands are equal or not, if yes then condition becomes true. (A=A) is true (A = B) is not true. != <> Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true Feb, 2019 [email protected] 18
  • 19. BETWEEN … AND… OPERATOR • This operator is used as a replacement for relational (>, <) and logical operators (AND, OR) • The lower limit must be <= upper limit • SELECT * FROM emp WHERE sal BETWEEN 10000 AND 20000; Feb, 2019 [email protected] 19
  • 20. IS NULL OPERATORS • Used for testing for the existence of NULL values in any column • Ex. Display the details of those employees who are not having any job SELECT * FROM emp WHERE job IS NULL: IS NOT NULL SELECT * FROM emp WHERE job IS NOT NULL: • Null value cannot be compared. Hence you cannot use relational operators for comparing NULL value with a column • Therefore IS NULL operator has to be used for the purpose Feb, 2019 [email protected] 20
  • 21. IN OPERATOR • This operator is used to compare multiple values with a single column • In this operator, values supplied must be of the same type and they should belong to only 1 column • This operator is a replacement for multiple OR operators – SELECT * FROM emp WHERE job IN (‘PE', ‘TO‘, ‘SE’); Feb, 2019 [email protected] 21
  • 22. LIKE OPERATOR - % AND _ • This operator is used for comparing characters/numbers in a value from a specific position • % ignores variable number of characters • _ ignores only 1 char • Display the details of those emps whose name is starting with ‘r’ SELECT * FROM emp WHERE ename LIKE 'r%‘; • Display the details of those emps who have ‘h’ as second character in their name - SELECT * FROM emp WHERE ename LIKE ‘_h%‘; Feb, 2019 [email protected] 22
  • 23. DISTINCT - ELIMINATING DUPLICATES • DISTINCT command is used to select only unique values from a column. • i.e. only single occurrence of a value will be returned. SELECT DISTINCT job FROM EMP; SELECT DISTINCT loc FROM dept; Feb, 2019 [email protected] 23
  • 24. FUNCTIONS • Function is a Sub Program which performs a specific task • Every function returns only 1 value • Functions in database can be used or defined for – Performing calculations which are not possible/easy using operators – Formatting text/numbers/dates – Type casting i.e. converting one type of data into another – To fetch information from system schema. Eg. VERSION() Feb, 2019 [email protected] 24
  • 25. FUNCTION – TYPES AND USES • Types of Functions – System defined functions – User defined functions • Syntax - SELECT <function name(args)> [FROM <table name>]; Feb, 2019 [email protected] 25
  • 26. FUNCTIONS – SYSTEM DEFINED • Numeric functions • String functions • Date and Time functions • Type Casting funtions • Aggregate functions More Functions - – https://www.postgresql.org/docs/current/functions.html Feb, 2019 [email protected] 26
  • 27. FEW FUNCTIONS Aggregate Functions • COUNT() – Gives count of occurrences; Works on All data types. • AVG() – Average. Works only on Numeric values • SUM() – Gives total/sum. Works only on Numeric values • MAX() – Maximum Value. All data types • MIN() – Minimum Value. All data types Feb, 2019 [email protected] 27
  • 28. REAL TIME USE OF FUNCTIONS SELECT UPPER(dname) FROM dept; SELECT MAX(sal) FROM emp; SELECT SUM(sal), AVG(SAL) FROM emp; Feb, 2019 [email protected] 28
  • 29. JOINS • Join is a technique of retrieving data from multiple tables • Display the ename AND dname from emp and dept tables SELECT ename, dname FROM emp, dept WHERE emp.deptno = dept.deptno; • Display the ename and dname of those emps whose sal is > 20000 SELECT ename, dname, sal FROM emp, dept WHERE emp.deptno = dept.deptno AND sal > 20000; Feb, 2019 [email protected] 29
  • 30. SUBQUERIES • It is a query within some other query • Display the details of those employees who are getting a sal > Aditya SELECT * FROM emp WHERE sal > (SELECT sal FROM emp WHERE ename = ‘Aditya’; • Display details of all employees who work in department ‘SENG’; SELECT * FROM emp WHERE DEPTNO = (SELECT deptno FROM dept WHERE dname = ‘SENG’); Feb, 2019 [email protected] 30
  • 31. MORE SUBQUERIES EXAMPLES • Display the maximum salary from every department and also the name of that employee who is getting the maximum Salary. SELECT ename, sal, deptno FROM emp WHERE (deptno, sal) IN (SELECT deptno, max(sal) FROM emp GROUP BY deptno); Feb, 2019 [email protected] 31
  • 32. MORE SQL CLAUSES • ORDER BY (if used, ORDER BY must by last clause of a query, except when you have used LIMIT Clause) – SELECT * FROM EMP ORDER BY SAL; – SELECT * FROM EMP ORDER BY SAL DESC; – SELECT * FROM EMP ORDER BY SAL DESC, ENAME; • GROUP BY – SELECT DEPTNO, SUM(SAL) FROM EMP GROUP BY DEPTNO; • GROUP BY….HAVING – SELECT DEPTNO, SUM(SAL) FROM EMP GROUP BY DEPTNO HAVING SUM(SAL) < 50000; Feb, 2019 [email protected] 32
  • 33. LIMITING NO OF RECORDS • LIMIT clause is used to limit number of records return in a SELECT query. • Its not part of SQL standard, works in PostgreSQL and few other RDBMS. • Unexceptionally, must be the last clause of a query. SELECT * FROM emp LIMIT 2; SELECT * FROM emp ORDER BY sal DESC LIMIT 3; Feb, 2019 [email protected] 33
  • 34. COPYING TABLE/DATA • A copy of the table (with, without or selected data)can be created using SELECT command CREATE table dept_copy AS SELECT * FROM dept; CREATE table emp_pe AS SELECT * FROM emp WHERE job = ‘PE’; CREATE table emp_new AS SELECT * FROM emp WHERE 1=2 • To copy only data of a table to another table INSERT INTO emp_seng SELECT * FROM emp WHERE deptno = (SELECT deptno FROM dept WHERE dname = ‘SENG’); INSERT INTO emp_seng SELECT * FROM emp WHERE deptno = 10; Feb, 2019 [email protected] 34
  • 35. COMMIT, SAVEPOINT & ROLLBACK • By default autocommit parameter is ON in PostgreSQL and can be reconfigured by PostgreSQL Administrator. A user can set autocommit parameter to ON & OFF for herself using alter command. • Savepoint and Rollback commands will be effective only when autocommit is OFF; • System (PostgreSQL Engine) autocommits all uncommitted operations before executing any DDL command. COMMIT; SAVEPOINT <variable name>; ROLLBACK [ TO <variable name>]; Feb, 2019 [email protected] 35
  • 36. GRANT & REVOKE • GRANT command is used to give selected/all DML and DDL command privileges to other database user; GRANT [PRIVILEGES] ON <tablename> TO ‘<username>‘; GRANT [PRIVILEGES] ON <tablename> TO ‘<username>‘ WITH GRANT OPTION; • REVOKE command is used to REVOKE command privileges given to other database user using GRANT Command; REVOKE [PRIVILEGES] ON <tablename> FROM ‘<username>‘; Feb, 2019 [email protected] 36
  • 37. ADDING A CONSTRAINT AFTER CREATION OF A TABLE • Any type of constraint can be added or dropped even after creation of table. PRIMARY KEY ALTER TABLE <tablename> ADD CONSTRAINT <constraintname> PRIMARY KEY (<column name>); ALTER TABLE <tablename> ADD PRIMARY KEY (<columnname>); ALTER TABLE <tablename> DROP PRIMARY KEY; UNIQUE ALTER TABLE <tablename> ADD CONSTRAINT <constraintname> <UNIQUE>; ALTER TABLE <tablename> DROP INDEX <constraintname>; DEFAULT ALTER TABLE <tablename> ALTER <column name> SET DEFAULT <default value>; ALTER TABLE <tablename> ALTER <column name> DROP DEFAULT; Feb, 2019 [email protected] 37
  • 38. JOIN TYPES : SQL STANDARD SYNTAX • (INNER) JOIN: Returns records that have matching values in both tables • LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table • RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table • FULL (OUTER) JOIN: Return all records when there is a match in either left or right table SELECT <column names> FROM <table name1> [LEFT |RIGHT] OUTER JOIN <tablename2> ON <tablename1>.<column name> = <tablename2>.<column name>; Feb, 2019 [email protected] 38
  • 39. INNER JOIN: EXAMPLES SELECT empno, ename, sal, dname FROM dept JOIN emp ON dept.deptno = emp.deptno; SELECT * FROM dept JOIN emp ON dept.deptno = emp.deptno; Feb, 2019 [email protected] 39
  • 40. LEFT OUTER JOIN: EXAMPLE SELECT empno, ename, sal, dname FROM dept LEFT OUTER JOIN emp ON dept.deptno = emp.deptno; SELECT * FROM dept LEFT OUTER JOIN emp ON dept.deptno = emp.deptno; Feb, 2019 [email protected] 40
  • 41. RIGHT OUTER JOIN: EXAMPLE SELECT empno, ename, sal, dname FROM dept RIGHT OUTER JOIN emp ON dept.deptno = emp.deptno; SELECT * FROM dept RIGHT OUTER JOIN emp ON dept.deptno = emp.deptno; Feb, 2019 [email protected] 41
  • 42. SET OPERATIONS: UNION, INTERSECT, EXCEPT • Set operations treat the tables as sets and are the usual set operators of union, intersection, and difference SELECT * FROM <table name 1> UNION | INTERSECT I EXCEPT SELECT * FROM <table name 2>; • SET operations must fulfil following two conditions – – Number of columns in the SELECT clause of both[all] queries must be same. – Data type of respective columns in both[all] queries must be same or compatible. Feb, 2019 [email protected] 42
  • 43. VIEWS • Views are ‘Virtual Tables’. • Views does not store data but fetches the data from underlying tables[s] dynamically at runtime. CREATE VIEW <view name> AS <Select Query> ; • All DML operations can be performed on a view and it affects underlying table. Feb, 2019 [email protected] 43
  • 44. INDEXES • Indexes are database objects used by DBMS to retrieve the data from table in a faster manner. • Invisible to end user • Speed up SELECT queries but slow down INSERTS/UPDATES/DELETES – CREATE [UNIQUE] INDEX <index name> ON <table name> (<column name> [, <column name2>],…..’; • Dropping an Index DROP INDEX <index name>; Feb, 2019 [email protected] 44