Chapter 1 SQL

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 45

Module-4

SQL: Advanced Queries:


More complex SQL retrieval queries
• The SQL SELECT Statement retrieves data from a database.

SELECT Statement in SQL

The SELECT statement in SQL is used to fetch or retrieve data from a


database.

It allows users to access the data and retrieve specific data based on
specific conditions.

The SELECT clause is the first clause and is one of the last clauses of
the select statement that the database server evaluates.
The syntax for the SELECT statement is:

Syntax SELECT column1,column2…. FROM table_name ;

SELECT Statement Example: INSERT INTO Customer (CustomerID, CustomerName,


CREATE TABLE Customer( LastName, Country, Age, Phone)
CustomerID INT PRIMARY KEY, VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),
CustomerName VARCHAR(50),
(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),
LastName VARCHAR(50),
Country VARCHAR(50), (3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),
Age int, (4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),
Phone int (5, 'Nishant. Salchichas S.A.', 'Jain',
);
'Spain','22','xxxxxxxxxx');
Output:
Retrieve Data using SELECT Query
• In this example, we will fetch CustomerName, LastName from the table
Customer:
SELECT CustomerName, LastName FROM Customer;

Output:
Fetch All Table using SELECT Statement

SELECT * FROM Customer;

Output:
SELECT Statement with WHERE Clause

• Suppose we want to see table values with specific conditions then


WHERE Clause is used with select statement.
SELECT CustomerName FROM Customer where Age = '21';

Output:
SQL SELECT Statement with GROUP BY Clause

SELECT COUNT (item), Customer_id FROM Orders GROUP BY order_id;

Output:
SELECT Statement with HAVING Clause
Query:

SELECT Department, sum(Salary) as Salary


FROM employee
GROUP BY department
HAVING SUM(Salary) >= 50000;

Output:
SELECT Statement with ORDER BY clause in SQL

SELECT * FROM Customer ORDER BY Age DESC;


SQL SELECT TOP Clause
• The SELECT TOP clause in SQL only returns the specified number of rows
from the table. It is valuable on enormous tables with a large number of records.
Returning countless records can affect execution.
• Note: Not all database systems support the SELECT TOP clause.
Syntax:

SELECT column1, column2, … TOP count


FROM table_name
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]];

Here,

• column1, column2 = names of columns

• count = number of records to be fetched


SQL SELECT TOP Clause Example

Query:

SELECT CustomerName, Age TOP 4* FROM Customer ORDER BY Salary DESC;


Output:
SQL SELECT TOP Clause with WHERE Clause Example

SELECT TOP 2* FROM Employee WHERE Salary>2000 ORDER BY Salary;

?
Select the first 3 records of the Customers table:
LIMIT SELECT * FROM Customers
LIMIT 3;

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedados y Constitución 2222
helados

3 Antonio Moreno Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden


snabbköp
Result:

CustomerID CustomerNa ContactNam Address City PostalCode Country


me e
1 Alfreds Maria Obere Str. 57 Berlin 12209 Germany
Futterkiste Anders
2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico
Emparedados Constitución
y helados 2222
3 Antonio Antonio Mataderos México D.F. 05023 Mexico
Moreno Moreno 2312
Taquería
FETCH FIRST:
Select the first 3 records of the Customers table:

SELECT * FROM Customers


FETCH FIRST 3 ROWS ONLY;

CustomerID CustomerNa ContactNam Address City PostalCode Country


me e
1 Alfreds Maria Obere Str. 57 Berlin 12209 Germany
Futterkiste Anders
2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico
Emparedados Constitución
y helados 2222
3 Antonio Antonio Mataderos México D.F. 05023 Mexico
Moreno Moreno 2312
Taquería
Important Points with SQL SELECT Statement

• It is used to access records from one or more database tables and views.
• The SELECT statement retrieves selected data based on specified conditions.
• The result of a SELECT statement is stored in a result set or result table.
• The SELECT statement can be used to access specific columns or all columns from a
table.
• It can be combined with clauses like WHERE, GROUP BY, HAVING, and ORDER BY
for more refined data retrieval.
• The SELECT statement is versatile and allows users to fetch data based on various
criteria efficiently.
SQL Views

• Views in SQL are a kind of virtual table. A view also has rows and columns like
tables, but a view doesn’t store data on the disk like a table. View defines a customized
query that retrieves data from one or more tables, and represents the data as if it was
coming from a single source.

• We can create a view by selecting fields from one or more tables present in the
database. A View can either have all the rows of a table or specific rows based on
certain conditions.
 Create StudentDetails table:

CREATE TABLE StudentDetails ( S_ID INT PRIMARY


KEY, NAME VARCHAR(255), ADDRESS
VARCHAR(255) );

INSERT INTO StudentDetails (S_ID, NAME, ADDRESS) VALUES


(1, 'Harsh', 'Kolkata'), (2, 'Ashish', 'Durgapur'), (3, 'Pratik', 'Delhi'),
(4, 'Dhanraj', 'Bihar'), (5, 'Ram', 'Rajasthan');
Create StudentMarks table :

CREATE TABLE StudentMarks ( ID INT PRIMARY KEY, NAME


VARCHAR(255), Marks INT, Age INT );

INSERT INTO StudentMarks (ID, NAME, Marks, Age) VALUES


(1, 'Harsh', 90, 19), (2, 'Suresh', 50, 20), (3, 'Pratik', 80, 19), (4,
'Dhanraj', 95, 21), (5, 'Ram', 85, 18);
CREATE VIEWS in SQL
• We can create a view using CREATE VIEW statement. A View can be created
from a single table or multiple tables.
• Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
Parameters:

• view_name: Name for the View


• table_name: Name of the table
• condition: Condition to select rows
Example 1: Creating View from a single table
StudentDetails:

CREATE VIEW DetailsView AS


SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5

StudentMarks:
SELECT * FROM DetailsView;

In this example, we will create a View named DetailsView from the table
StudentDetails.

OUTPUT:
Example 2: Create View From Table
In this example, we will create a view named StudentNames from the table
StudentDetails.
Output:
CREATE VIEW StudentNames AS
SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;

SELECT * FROM StudentNames;


Example 3: Creating View from multiple tables

• In this example we will create a View named MarksView from two tables
StudentDetails and StudentMarks. To create a View from multiple tables we
can simply include multiple tables in the SELECT statement.

CREATE VIEW MarksView AS


SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
SELECT * FROM MarksView;

Output:
UPDATE VIEW in SQL
• If you want to update the existing data within the view, use the UPDATE
statement.

UPDATE view_name
Syntax: SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

Note: Not all views can be updated using the UPDATE statement.

If you want to update the view definition without affecting the data, use
the CREATE OR REPLACE VIEW statement.
CREATE OR REPLACE VIEW view_name AS
Syntax: SELECT column1, column2, ...
FROM table_name
WHERE condition;
Rules to Update Views in SQL:
Certain conditions need to be satisfied to update a view. If any of these conditions are not met, the
view can not be updated.
1.The SELECT statement which is used to create the view should not include GROUP BY clause or
ORDER BY clause.
2.The SELECT statement should not have the DISTINCT keyword.
3.The View should have all NOT NULL values.
4.The view should not be created using nested queries or complex queries.
5.The view should be created from a single table. If the view is created using multiple tables then
we will not be allowed to update the view.
Example 1: Update View to Add or Replace a View Field

• We can use the CREATE OR REPLACE VIEW statement to add or


replace fields from a view.
• If we want to update the view MarksView and add the field AGE to this
View from StudentMarks Table, we can do this by:
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS,
StudentMarks.MARKS, StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
If we fetch all the data from MarksView now as:

SELECT * FROM MarksView;

Output:
Example 2: Update View to Insert a row in a view

INSERT INTO DetailsView(NAME, ADDRESS)


VALUES("Suresh","Gurgaon");

If we fetch all the data from DetailsView now as,

SELECT * FROM DetailsView;

Output:
DELETE VIEWS in SQL

• SQL allows us to delete an existing View. We can delete or drop View


using the DROP statement.

Syntax: DROP VIEW view_name;

Example: DROP VIEW MarksView; we are deleting the View MarksView.


Example 3: Deleting a row from a View
DELETE FROM DetailsView
WHERE NAME="Suresh";

If we fetch all the data from DetailsView now as,

SELECT * FROM DetailsView;


Specifying constraints as assertions and
action triggers

You might also like