You are on page 1of 61

Introduction of SQL

History

• The SQL programming language was first developed in the 1970s by IBM
researchers Raymond Boyce and Donald Chamberlin.
• The programming language, known then as SEQUEL.
• In 1979, a company called Relational Software, which later became Oracle,
commercially released its own version of the SQL language called Oracle V2.
Basic Concepts

• SQL stands for Structured Query Language.


• SQL is a standard language for accessing and manipulating databases.
• When a user wants to get some information from databases, the user can issue
Query.
• A query is a user-request to retrieve data or information with a certain condition.
Basic Concepts(cont.)

• SQL functions fit into three broad categories:


---- Data Manipulation Languages (DML): Which deal with data manipulation. It
includes different commands such as select, insert, update, delete, merge etc.
---- Data Definition Languages (DDL): Which deal with databases schemas and
description. It includes different commands such as create, alter, drop, truncate,
comment, rename etc.
---- Data Control Languages (DCL): Which deal with the rights and permissions of
database system. It includes commands such as grant and revoke.
Advantages of SQL

• SQL Queries can be used to retrieve large amounts of records from a database
quickly and efficiently.
• Using standard SQL it is easier to manage databases systems without having to
write substantial amount of code.
• SQL databases use long - established standards, which is being adopted by ANSI &
ISO.
Disadvantages of SQL

Although SQL has many advantages, still there are a few disadvantages.
Various Disadvantages of SQL are as follows:

• Complex Interface –
SQL has a difficult interface that makes few users uncomfortable while dealing
with the database.
• Cost –
Some versions are costly and hence, programmers cannot access it.
• Partial Control –
Due to hidden business rules, complete control is not given to the database.
What is Excel?

• Microsoft Excel is an application used to build and format spreadsheets.


• It is good for operations on flat files - summarizing, cross-validating, visualizing,
and building pivot tables.
• It is a very powerful application that has the ability to do many things such as
calculating loan, etc.
Advantages of Excel

• It's easy to browse data.


• It is easy to manually enter and edit data.
• Formulas make it a living document.
• It has a bulit-in suite of helpers for charts, comments, spellchecking etc.
• It's relatively easy to learn.
Disadvantages of Excel

• It's not very good for working with multiple datasets in combination.
• It lacks data integrity.
• It doesn't scale As the amount of data increase performance suffers.
• If you have two people editing data in Excel, you can expect three copies of the
final spreadsheet.
• It uses a bunch of filters and sorting for finding some data in a spreadsheet.
What is Database?

• Database is a collection of information organized for easy access, management


and maintenance.
• Examples
• Telephone directory
• Customer Data
• Product Inventory
• Visitor's register
• Weather records
Types of Data Models

1. Object Based logical model


• Entity relationship model (ER)

2. Record Based logical model


• Hierarchical model (ER)
• Network Data model
• Relational Data model
What is SQL?

• Programming language specifically designed for working with database to...


• Create
• Manipulate
• Share/Access
SQL Data Types
• Numeric : bit, tinyint, smallint, int, bigint, decimal, numeric, float, real
• Character/ Strings: char, varchar, text
• Date/Time : date, time, datetime, timestamp, year
SQL Constraints

Constraint Description
Not Null Ensures that a column does not have a NULL value
Default Provides a default value for a column when none is specified

Unique Ensures that all values in a column are different


Primary Identifies each row/record in a database table uniquely
Check Ensures that all values in a column satisfy certain conditions
Index Creates and retrieves data from the database very quickly
SQL Command Groups

• DDL (Data Definition Language): creation of objects

• DML (Data Manipulation Language): Manipulation of data

• DCL (Data Control Language): assignment and removal of permissions

• TCL (Transaction Control Language): saving and restoring changes to a database


DDL- Data Definition Language

Constraint Description
Create Creates objects in the database/database objects
Alter Alters the structures of the database/ database objects
Drop Deletes objects from the database
Truncate Removes all records from a table permanently
Rename Renames an object
DDL- Data Definition Language- Create Command
• Create table employee (emp_id int, emp_id first_name last_name salary
first_name varchar(20), last_name
varchar(20), salary int);
DDL- Data Definition Language- Alter Command
• Alter table employees add column emp_id first_na last_nam salary Contact
contact int(10); me e
DDL- Data Definition Language- Rename Command
• Alter table employees rename emp_id first_na last_nam salary job_code
column contact to job_code; me e
DML- Data Manipulation Language

Constraint Description
Insert Insert data in to table
Update Updates existing data within a table
Delete Delete specified/ all records from a table
DML- Data Manipulation Language- Insert command
• insert into employees(emp_id, emp_id first_name last_name salary
first_name,last_name,salary) values
(101, 'Harry','Potter',10000); 101 Harry Potter 10000
• insert into employees(emp_id,
first_name,last_name,salary) values 102 Neeta Kumari 20000
(102, 'Neeta','Kumari',20000);
DML- Data Manipulation Language- Update command

• update employees set emp_id first_name last_name salary


last_name='Prasad' where
emp_id=102; 101 Harry Potter 10000

102 Neeta Prasad 20000


DML- Data Manipulation Language- Delete command

• delete from employees where emp_id first_name last_name salary


emp_id=102;
101 Harry Potter 10000

102 Neeta Prasad 20000


SQL Operators- Filter

• WHERE clause: emp_id first_na last_na salary


me me
• used to specify a condition while fetching the data
101 Harry Potter 10000
from a single table or by joining with multiple tables.
102 Neeta Prasad 20000
• Not only used in the SELECT statement, but it is also
used in the UPDATE, DELETE statement etc.
• eg: select * from employees WHERE
emp_id=101; emp_id first_na last_na salary
me me
101 Harry Potter 10000
SQL Operators

• An Operator is a reserved word or a character used in an SQL statement's


WHERE clause to perform operations, such as comparisons and arithmetic
operations.
• Below are the list of someoperators:
- Arithmetic Operators
- Comparison Operators
- Logical Operators
SQL Arithmetic Operators

Operator Description Example


+ Addition- Add values on either side of the operator a+b

- Subtarction- Subtracts right hand operand from the left hand operand a-b

* Multiplication- Multiplies values on either side of the operator a*b

/ Divison- Divides left hand operand by right hand operand a/b

% Modulus- Divdes left hand operand by right hand operand and returns b%a
reminder.
SQL Comparison Operators
Operator Description Example
= Checks if the values of two operands are equal or not, if yes then conditions (a=b)
become true.
!= Checks if the values of two operands are equal or not, if values are not equal a!=b
then condition becomes true.
<> Checks if the values of two operands are equal or not, if values are not equal a<>b
then condition becomes true.
> Greater than a>b

< Less than a<b

>= Greater than or equal to a>=b

<= Less than or equal to a<=b


SQL Comparison Operators

Sample Queries:
SELECT * FROM employees WHERE first_name = ‘Steven’ and salary = 15000;

SELECT * FROM employees WHERE first_name = ‘Steven’ OR salary != 15000;

SELECT * FROM employees WHERE first_name = ‘Steven’ and salary > 15000;

SELECT * FROM employees WHERE first_name = ‘Steven’ and salary >=15000;

SELECT * FROM employees WHERE first_name = ‘Steven’ and salary < 15000;

SELECT * FROM employees WHERE first_name = ‘Steven’ and salary <=15000;

SELECT * FROM employees WHERE first_name = ‘Steven’ and salary <> 15000;
SQL Logical Operators
Operator Illustrative Example Result
AND (5<2) and (5>3) False

OR (5<2) or (5>3) True

NOT(!=) NOT(5<2) True

Sample Queries:
SELECT * FROM employees WHERE first_name = ‘Steven’ and salary = 15000;
SELECT * FROM employees WHERE first_name = ‘Steven’ OR salary = 15000;
SELECT * FROM employees WHERE first_name = ‘Steven’ and salary !=
15000;
SQL Special Operators
Operator Description
BETWEEN Checks an attribute value within range

LIKE Checks an attribute value matches a given string pattern

IS NULL Checks an attribute value is NULL

IN Checks an attribute value matches any value within a value list

DISTINCT Limit values to unique values


SQL Special Operators

Sample Queries:

SELECT * FROM employees WHERE salary BETWEEN 10000 and 50000;

SELECT * FROM employees WHERE first_name LIKE ‘Steven’;

SELECT * FROM employees WHERE salary IS NULL;

SELECT * FROM employees WHERE salary IN (5000,10000,20000);

SELECT DISTINCT(first_name) from employees;


SQL Operators - Aggregations
Aggregations Description
AVG() Returns the average value from specified columns

COUNT() Returns number of table rows

MAX() Returns largest value among the records

MIN() Returns smallest value among the records

SUM() Returns the sum of specified column values


SQL Operators - Aggregations

Sample Queries:

SELECT avg(salary) FROM employees;

SELECT count(salary) FROM employees;

SELECT count(*) FROM employees;

SELECT min(salary) FROM employees;

SELECT max(salary) FROM employees;

SELECT sum(salary) FROM employees;


SQL LIMIT Clause
• The LIMIT clause is used to set an upper limit on the number of tuples returned by SQL.

• It is important to note that this clause is not supported by all SQL versions.

• The LIMIT clause can also be specified using the SQL 2008 OFFSET/FETCH FIRST clauses.

• The limit/offset expressions must be a non-negative integer.

Syntax:
SELECT *
FROM table_name
LIMIT 5;
SQL LIMIT along with OFFSET
• The OFF SET value is also most often used together with the LIMIT keyword. The OFF SET value

allows us to specify which row to start from retrieving data.

• Let's suppose that we want to get a limited number of members starting from the middle of the

rows, we can use the LIMIT keyword together with the offset value to achieve that. The script

shown below gets data starting the second row and limits the results to 2.

SYNTAX

SELECT * FROM table_name LIMIT 1, 2;


SQL GROUP BY Clause
Arrange identical data into groups emp_id first_name last_name salary dept_id

eg : SELECT max(salary), dept_id


103 Harry Potter 20000 12
FROM employees
GROUP BY dept_id; 102 Edwin Thomas 15000 11

101 Steven Cohen 10000 10

100 Erik John 10000 12


SQL HAVING Clause
• Used with aggregate functions due to its emp_id first_na last_na salary dept_id
non-performancein the WHERE clause. me me
• Must follow the GROUP BY clause in a
103 Harry Potter 20000 12
query and must also precede the ORDER
BY clause if used.
102 Edwin Thomas 15000 11

eg : SELECT avg(salary), dept_id


101 Steven Cohen 10000 10
FROM employees
GROUP BY dept_id 100 Erik John 10000 12
HAVING count(dept_id)>=2;
SQL ORDER BY Clause emp_id first_nam last_name salary
e
• Used to sort output of SELECT statement.
101 Steven Cohen 10000
• Default is to sort in ASC(Ascending)
• Can sort in reverse (descending) Order
102 Edwin Thomas 15000
with “DESC” after the column name

103 Harry Potter 20000


eg : SELECT * FROM employees
ORDER BY salary DESC;
emp_id first_nam last_name salary
e
103 Harry Potter 20000

102 Edwin Thomas 15000

101 Steven Cohen 10000


SQL UNION
• Used to combine the result-set of two or more SELECT statements removing duplicates.

• Each SELECT statement within the Union must have the same number of columns.

• The selected columns must be of similar data types and must be in the same order in each

SELECT statement.

• More than two queries can be clubbed using more than one union statement.
SQL UNION
Product 2
Product 1
Category_id Product_nam Category_id Product_name
Product_name
e 1 Samsung
1 Nokia Nokia
2 LG
2 Samsung 3 HP Samsung
3 HP HP
5 Dell
6 Nikon Nikon
6 Apple
LG
10 Playstation
Dell

eg : SELECT product_name FROM product1 Apple


UNION Playstation
SELECT product_name FROM product2 ;
SQL UNION ALL
• Used to combine the results to two SELECT statements including duplicate rows.

• The same rules that apply to the UNION clause will apply to the UNION ALL operator.

• SYNTAX:
SELECT col1,col2.......FROM table1
UNION ALL
SELECT col1,col2.......... FROM table2;
SQL UNION ALL
Product 2
Product 1
Product_name
Category_id Product_nam Category_id Product_name
e Nokia
1 Samsung
1 Nokia Samsung
2 LG
2 Samsung HP
3 HP
3 HP Nikon
5 Dell
6 Nikon Samsung
6 Apple
LG
10 Playstation
HP
eg : SELECT product_name FROM product1 Dell
UNION ALL
Apple
SELECT product_name FROM product2 ;
Playstation
SQL Aliases
• SQL aliases are used to give a table, or a column in a table, a temporary name.

• Aliases are often used to make column names more readable.

• An alias only exists for the duration of that query.

• An alias is created with the AS keyword.

Alias Column Syntax


SELECT column_name AS alias_name
FROM table_name;

Alias Table Syntax


SELECT column_name(s)
FROM table_name AS alias_name;
SQL JOINS
• Combine rows/columns from two or more tables, based on
a related column between them in a database
A∩B
• INNER JOIN -Returns the rows when there is a match in both
tables. Table Table
A B

• LEFT JOIN -Returns all the rows from the left table, even if there (A ∩ B)U A
are no matches in the right table.
Table Table
A B

• RIGHT JOIN-Returns all rows from the right table, even if there (A ∩ B)U B
are no matches in the left table.
Table Table
A B
SQL JOINS
(A ∩ B) U (A-B)U(B-A)

• FULL OUTER JOIN -Returns rows when there is a match in one of


the tables.
Table Table
A B

• SELF JOIN - Used to join a table to itself as if the table were two
tables, temporarily renaming at least one table in the SQL
statement.
Table
A
(Join Itself)

• CARTESIAN JOIN(Cross Join)-Returns the Cartesian product of


the sets of records from the two or more joined tables.
Table Table
A B
SQL INNER JOIN
The INNER JOIN creates a new result table by combining column values of two
tables (table1 and table 2) based upon the join-predicate. The query compares each
row of table1 with each row of table2 to find all pairs of rows which satisfy the join-
predicate.

SYNTEX:

SELECT table1.col1, table1.col2,.......,table1.coln


FROM table1
INNER JOIN table2
ON table1.comonfield = table2.commonfield;

46
SQL INNER JOIN
emp_id first_na last_na salary dept_id dept_id dept_name manager_i location_id
me me d
103 Harry Potter 20000 12 10 IT 200 1700

102 Edwin Thomas 15000 11 11 Marketing 201 1800

101 Steven Cohen 10000 10 13 Resources 203 2400

100 Erik John 10000 12 14 Shipping 121 1500

SELECT e.emp_id, e.first_name, e.last_name, emp_id first_name last_name dept_id dept_nam


d.dept_id, d.dept_name e
FROM employees e 101 Steven Cohen 10 IT
INNER JOIN departments d
ON e.dept_id = d.dept_id 102 Edwin Thomas 11 Marketing
SQL LEFT JOIN
The LEFT JOIN returns all the values from the left table, plus matched values from
the right table or NULL in case of no matching join predicate.

SYNTEX:

SELECT table1.col1, table1.col2,.......,table1.coln


FROM table1
LEFT JOIN table2
ON table1.comonfield = table2.commonfield;
SQL LEFT JOIN
emp_id first_na last_na salary dept_id dept_id dept_name manager_i location_id
me me d
103 Harry Potter 20000 12 10 IT 200 1700

102 Edwin Thomas 15000 11 11 Marketing 201 1800

101 Steven Cohen 10000 10 13 Resources 203 2400

100 Erik John 10000 12 14 Shipping 121 1500

emp_id first_name last_name dept_id dept_nam


SELECT e.emp_id, e.first_name, e.last_name, e
d.dept_id, d.dept_name 101 Steven Cohen 10 IT
FROM employees e
LEFT OUTER JOIN departments d 102 Edwin Thomas 11 Marketing
ON e.dept_id = d.dept_id
103 Harry Potter NULL NULL

100 Erik John NULL NULL


SQL RIGHT JOIN
The RIGHT JOIN returns all the values from the right table, plus matched values from
the left table or NULL in case of no matching join predicate.

SYNTEX:

SELECT table1.col1, table1.col2,.......,table1.coln


FROM table1
RIGHT JOIN table2
ON table1.comonfield = table2.commonfield;
SQL RIGHT JOIN
emp_id first_na last_na salary dept_id dept_id dept_name manager_i location_id
me me d
103 Harry Potter 20000 12 10 IT 200 1700

102 Edwin Thomas 15000 11 11 Marketing 201 1800

101 Steven Cohen 10000 10 13 Resources 203 2400

100 Erik John 10000 12 14 Shipping 121 1500

emp_id first_name last_name dept_id dept_nam


SELECT e.emp_id, e.first_name, e.last_name, e
d.dept_id, d.dept_name 101 Steven Cohen 10 IT
FROM employees e
RIGHT JOIN departments d 102 Edwin Thomas 11 Marketing
ON e.dept_id = d.dept_id;
NULL NULL NULL 13 Resources

NULL NULL NULL 14 Shipping


SQL FULL OUTER JOIN
The FULL OUTER JOIN combines the results of both left and right outer joins. The
joined table will contain all records from both the tables and fill in NULLs for
missing matches on either side.

SYNTEX:

SELECT table1.col1, table1.col2,.......,table1.coln


FROM table1
LEFT JOIN table2
ON table1.comonfield = table2.commonfield
UNION
SELECT table1.col1, table1.col2,.......,table1.coln
FROM table1
RIGHT JOIN table2
ON table1.comonfield = table2.commonfield;
SQL FULL OUTER JOIN
emp_id first_nam last_nam salary dept_id dept_id dept_name manager_id location_id
e e
103 Harry Potter 20000 12 10 IT 200 1700

102 Edwin Thomas 15000 11 11 Marketing 201 1800


101 Steven Cohen 10000 10 13 Resources 203 2400
100 Erik John 10000 12 14 Shipping 121 1500

emp_id first_name last_name dept_id dept_nam


SELECT table1.col1, table.col2,.......,table1.coln
e
FROM table1
LEFT JOIN table2 101 Steven Cohen 10 IT
ON table1.comonfield = table2.commonfield; 102 Edwin Thomas 11 Marketing
UNION
SELECT table1.col1, table.col2,.......,table1.coln 103 Harry Potter 12 NULL
FROM table1 100 Erik John 12 NULL
RIGHT JOIN table2
NULL NULL NULL 13 Resouces
ON table1.comonfield = table2.commonfield;
NULL NULL NULL 14 Shipping
SQL SELF JOIN
emp_id Name man_id Name Manger

1 Harry 3 Harry Steven


2 Edwin 7 Edwin Cohen
3 Steven 4 Steven Erik
4 Erik 5 Erik Potter
5 Potter 6 Potter Thomas
6 Thomas Null Thomas NulL
7 Cohen 6 Cohen Thomas

8 John NULL John NULL

SELECT e.name Name,m.name


Manager
FROM emp e
INNER JOIN emp m
on e.emp_id= m.man_id;
SQL CROSS JOIN
Assume there are 4 records in table1 and table 3 records in table2

SYNTEX:
Select * From table1 CROSS JOIN table2; A 1
A 2
A 3
alpha NUM B 1
A 1 B 2

B 2 B 3
C 1
C 3
C 2
C 3
SQL- Views
• A view is a virtual table based on the result-set of an SQL statement.
• A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.
• You can add SQL functions, Where and Join statements to a view and present the
data as if the data were coming from one single table.
• Below is the syntax for creating a view:
Create View view_name as
Select column1, column2,..........
FROM table_name
Where condition;
SQL- Stored Procedures
• A stored procedure is a prepared SQL code that you can save, so the code can be reused over and
over again.
• So if you have an SQL query that you write over and over again, save it as a stored procedure, and
then just call it to execute it.
• You can also pass parameters to a stored procedure, so that the stored procedure can act based on
the parameter value(s) that is passed.

Stored Procedure Syntax


CREATE PROCEDURE procedure_name
AS
sql_statement
GO;

Execute a Stored Procedure


EXEC procedure_name;
SQL- Primary Key
• The PRIMARY KEY constraint uniquely identifies each record in a table.
• Primary keys must contain UNIQUE values, and cannot contain NULL values.
• A table can have only ONE primary key; and in the table, this primary key can consist of
single or multiple columns (fields).
SYNTAX:
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

58
SQL- UNIQUE Key
• The UNIQUE constraint ensures that all values in a column are different.
• Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a
column or set of columns.
• A PRIMARY KEY constraint automatically has a UNIQUE constraint.
SYNTAX:
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
SQL- Auto Increment
• Auto-increment allows a unique number to be generated automatically when a new record is inserted
into a table.
• MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature.
• By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.
Syntax
The following SQL statement defines the "Personid" column to be an auto-increment primary key field in
the "Persons" table:
CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid));

To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
ALTER TABLE Persons AUTO_INCREMENT=100;
THANK YOU

You might also like