SlideShare a Scribd company logo
1 of 44
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

What's hot

Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQLMahir Haque
 
New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012 New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012 Richie Rump
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETEAbrar ali
 
Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Achmad Solichin
 
Window functions with SQL Server 2016
Window functions with SQL Server 2016Window functions with SQL Server 2016
Window functions with SQL Server 2016Mark Tabladillo
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better PerformanceMySQL: Indexing for Better Performance
MySQL: Indexing for Better Performancejkeriaki
 
Explaining the explain_plan
Explaining the explain_planExplaining the explain_plan
Explaining the explain_planarief12H
 
Exploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic FunctionsExploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic FunctionsZohar Elkayam
 
SQL Assessment Command Statements
SQL Assessment Command StatementsSQL Assessment Command Statements
SQL Assessment Command StatementsShaun Wilson
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLIntroduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLMárton Kodok
 

What's hot (20)

Sql Tutorials
Sql TutorialsSql Tutorials
Sql Tutorials
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Lab1 select statement
Lab1 select statementLab1 select statement
Lab1 select statement
 
New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012 New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012
 
SQL- Introduction to PL/SQL
SQL- Introduction to  PL/SQLSQL- Introduction to  PL/SQL
SQL- Introduction to PL/SQL
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)
 
ORACLE PL SQL
ORACLE PL SQLORACLE PL SQL
ORACLE PL SQL
 
SQL Windowing
SQL WindowingSQL Windowing
SQL Windowing
 
advanced sql(database)
advanced sql(database)advanced sql(database)
advanced sql(database)
 
Window functions with SQL Server 2016
Window functions with SQL Server 2016Window functions with SQL Server 2016
Window functions with SQL Server 2016
 
Explain that explain
Explain that explainExplain that explain
Explain that explain
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better PerformanceMySQL: Indexing for Better Performance
MySQL: Indexing for Better Performance
 
Explaining the explain_plan
Explaining the explain_planExplaining the explain_plan
Explaining the explain_plan
 
Mssql to oracle
Mssql to oracleMssql to oracle
Mssql to oracle
 
Exploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic FunctionsExploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic Functions
 
SQL Assessment Command Statements
SQL Assessment Command StatementsSQL Assessment Command Statements
SQL Assessment Command Statements
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLIntroduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQL
 

Similar to Structured Query Language (SQL) - An Introduction

Structure Query Language (SQL).pptx
Structure Query Language (SQL).pptxStructure Query Language (SQL).pptx
Structure Query Language (SQL).pptxNalinaKumari2
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowPavithSingh
 
Statements,joins and operators in sql by thanveer danish melayi(1)
Statements,joins and operators in sql by thanveer danish melayi(1)Statements,joins and operators in sql by thanveer danish melayi(1)
Statements,joins and operators in sql by thanveer danish melayi(1)Muhammed Thanveer M
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsAshwin Dinoriya
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Trainingbixxman
 
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQLDATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQLDev Chauhan
 
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdfComplete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdfssuserb5bb0e
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management SystemMian Abdul Raheem
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxjainendraKUMAR55
 
dbs class 7.ppt
dbs class 7.pptdbs class 7.ppt
dbs class 7.pptMARasheed3
 

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

Structure Query Language (SQL).pptx
Structure Query Language (SQL).pptxStructure Query Language (SQL).pptx
Structure Query Language (SQL).pptx
 
Dbms
DbmsDbms
Dbms
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Statements,joins and operators in sql by thanveer danish melayi(1)
Statements,joins and operators in sql by thanveer danish melayi(1)Statements,joins and operators in sql by thanveer danish melayi(1)
Statements,joins and operators in sql by thanveer danish melayi(1)
 
Sql Document in Testing
Sql Document in TestingSql Document in Testing
Sql Document in Testing
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
DBMS.pptx
DBMS.pptxDBMS.pptx
DBMS.pptx
 
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQLDATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
 
SQL.pptx
SQL.pptxSQL.pptx
SQL.pptx
 
Sql
SqlSql
Sql
 
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdfComplete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management System
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptx
 
Oracle Sql & PLSQL Complete guide
Oracle Sql & PLSQL Complete guideOracle Sql & PLSQL Complete guide
Oracle Sql & PLSQL Complete guide
 
dbs class 7.ppt
dbs class 7.pptdbs class 7.ppt
dbs class 7.ppt
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 

Recently uploaded

JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuidePixlogix Infotech
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTopCSSGallery
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxFIDO Alliance
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
الأمن السيبراني - ما لا يسع للمستخدم جهله
الأمن السيبراني - ما لا يسع للمستخدم جهلهالأمن السيبراني - ما لا يسع للمستخدم جهله
الأمن السيبراني - ما لا يسع للمستخدم جهلهMohamed Sweelam
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceIES VE
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxMarkSteadman7
 

Recently uploaded (20)

JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
الأمن السيبراني - ما لا يسع للمستخدم جهله
الأمن السيبراني - ما لا يسع للمستخدم جهلهالأمن السيبراني - ما لا يسع للمستخدم جهله
الأمن السيبراني - ما لا يسع للمستخدم جهله
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 

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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 7
  • 8. CRUD OPERATIONS Operation SQL Command CREATE INSERT READ SELECT UPDATE UPDATE DELETE DELETE/TRUNCATE Feb, 2019 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 16
  • 17. CONSTRAINTS • PRIMARY KEY • FOREIGN KEY • UNIQUE • NOT NULL • DEFAULT • CHECK Feb, 2019 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 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 rajeevs@cdac.in 44