SlideShare a Scribd company logo
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
Ad

Recommended

SQL Pass Summit Presentations from Datavail - Optimize SQL Server: Query Tuni...
SQL Pass Summit Presentations from Datavail - Optimize SQL Server: Query Tuni...
Datavail
 
Oracle SQL Advanced
Oracle SQL Advanced
Dhananjay Goel
 
SQL Tunning
SQL Tunning
Dhananjay Goel
 
U-SQL Does SQL (SQLBits 2016)
U-SQL Does SQL (SQLBits 2016)
Michael Rys
 
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
Edgar Alejandro Villegas
 
Structure query language (sql)
Structure query language (sql)
Nalina Kumari
 
Oracle basic queries
Oracle basic queries
PRAKHAR JHA
 
Oracle Course
Oracle Course
rspaike
 
Sql Tutorials
Sql Tutorials
Priyabrat Kar
 
Oracle SQL Basics
Oracle SQL Basics
Dhananjay Goel
 
Introduction to SQL
Introduction to SQL
Mahir Haque
 
Oraclesql
Oraclesql
Priya Goyal
 
Lab1 select statement
Lab1 select statement
Balqees Al.Mubarak
 
New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012
Richie Rump
 
SQL- Introduction to PL/SQL
SQL- Introduction to PL/SQL
Vibrant Technologies & Computers
 
Database COMPLETE
Database COMPLETE
Abrar ali
 
Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)
Achmad Solichin
 
ORACLE PL SQL
ORACLE PL SQL
Srinath Maharana
 
SQL Windowing
SQL Windowing
Sandun Perera
 
advanced sql(database)
advanced sql(database)
welcometofacebook
 
Window functions with SQL Server 2016
Window functions with SQL Server 2016
Mark Tabladillo
 
Explain that explain
Explain that explain
Fabrizio Parrella
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better Performance
jkeriaki
 
Explaining the explain_plan
Explaining the explain_plan
arief12H
 
Mssql to oracle
Mssql to oracle
Chien Chung Shen
 
Exploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic Functions
Zohar Elkayam
 
SQL Assessment Command Statements
SQL Assessment Command Statements
Shaun Wilson
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQL
Márton Kodok
 
Structure Query Language (SQL).pptx
Structure Query Language (SQL).pptx
NalinaKumari2
 
INTRODUCTION TO SQL QUERIES REALTED BRIEF
INTRODUCTION TO SQL QUERIES REALTED BRIEF
VADAPALLYPRAVEENKUMA1
 

More Related Content

What's hot (20)

Sql Tutorials
Sql Tutorials
Priyabrat Kar
 
Oracle SQL Basics
Oracle SQL Basics
Dhananjay Goel
 
Introduction to SQL
Introduction to SQL
Mahir Haque
 
Oraclesql
Oraclesql
Priya Goyal
 
Lab1 select statement
Lab1 select statement
Balqees Al.Mubarak
 
New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012
Richie Rump
 
SQL- Introduction to PL/SQL
SQL- Introduction to PL/SQL
Vibrant Technologies & Computers
 
Database COMPLETE
Database COMPLETE
Abrar ali
 
Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)
Achmad Solichin
 
ORACLE PL SQL
ORACLE PL SQL
Srinath Maharana
 
SQL Windowing
SQL Windowing
Sandun Perera
 
advanced sql(database)
advanced sql(database)
welcometofacebook
 
Window functions with SQL Server 2016
Window functions with SQL Server 2016
Mark Tabladillo
 
Explain that explain
Explain that explain
Fabrizio Parrella
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better Performance
jkeriaki
 
Explaining the explain_plan
Explaining the explain_plan
arief12H
 
Mssql to oracle
Mssql to oracle
Chien Chung Shen
 
Exploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic Functions
Zohar Elkayam
 
SQL Assessment Command Statements
SQL Assessment Command Statements
Shaun Wilson
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQL
Márton Kodok
 
Introduction to SQL
Introduction to SQL
Mahir Haque
 
New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012
Richie Rump
 
Database COMPLETE
Database COMPLETE
Abrar ali
 
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 2016
Mark Tabladillo
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better Performance
jkeriaki
 
Explaining the explain_plan
Explaining the explain_plan
arief12H
 
Exploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic Functions
Zohar Elkayam
 
SQL Assessment Command Statements
SQL Assessment Command Statements
Shaun Wilson
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQL
Márton Kodok
 

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

Structure Query Language (SQL).pptx
Structure Query Language (SQL).pptx
NalinaKumari2
 
INTRODUCTION TO SQL QUERIES REALTED BRIEF
INTRODUCTION TO SQL QUERIES REALTED BRIEF
VADAPALLYPRAVEENKUMA1
 
Dbms
Dbms
Sachin Yadav
 
MS SQL Server
MS SQL Server
Md. Mahedee Hasan
 
More Complex SQL and Concurrency ControlModule 4.pptx
More Complex SQL and Concurrency ControlModule 4.pptx
bgscseise
 
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
PreetiKushwah6
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
PavithSingh
 
SQL Overview
SQL Overview
Stewart Rogers
 
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
 
Sql Document in Testing
Sql Document in Testing
Saurabh Bhardwaj
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
Ashwin Dinoriya
 
Advanced Sql Training
Advanced Sql Training
bixxman
 
DBMS.pptx
DBMS.pptx
Geetha Kannan
 
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
Dev Chauhan
 
SQL.pptx
SQL.pptx
AmitDas125851
 
Sql
Sql
Diana Diana
 
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
ssuserb5bb0e
 
Relational Database Management System
Relational Database Management System
Mian Abdul Raheem
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptx
jainendraKUMAR55
 
Oracle Sql & PLSQL Complete guide
Oracle Sql & PLSQL Complete guide
Raviteja Chowdary Adusumalli
 
Structure Query Language (SQL).pptx
Structure Query Language (SQL).pptx
NalinaKumari2
 
INTRODUCTION TO SQL QUERIES REALTED BRIEF
INTRODUCTION TO SQL QUERIES REALTED BRIEF
VADAPALLYPRAVEENKUMA1
 
More Complex SQL and Concurrency ControlModule 4.pptx
More Complex SQL and Concurrency ControlModule 4.pptx
bgscseise
 
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
PreetiKushwah6
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
PavithSingh
 
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 Joins
Ashwin Dinoriya
 
Advanced Sql Training
Advanced Sql Training
bixxman
 
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
Dev Chauhan
 
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
ssuserb5bb0e
 
Relational Database Management System
Relational Database Management System
Mian Abdul Raheem
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptx
jainendraKUMAR55
 
Ad

Recently uploaded (20)

Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
SAP Modernization Strategies for a Successful S/4HANA Journey.pdf
SAP Modernization Strategies for a Successful S/4HANA Journey.pdf
Precisely
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
June Patch Tuesday
June Patch Tuesday
Ivanti
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
SAP Modernization Strategies for a Successful S/4HANA Journey.pdf
SAP Modernization Strategies for a Successful S/4HANA Journey.pdf
Precisely
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
June Patch Tuesday
June Patch Tuesday
Ivanti
 
Ad

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