0% found this document useful (0 votes)
21 views23 pages

UNIT3 Parti

SQL, or Structured Query Language, is used to retrieve and manipulate data in relational database management systems (RDMS), which store data in tables. It supports four fundamental operations: SELECT (read), INSERT (create), UPDATE (modify), and DELETE (remove), collectively known as CRUD. The document provides detailed syntax and examples for various SQL commands, including SELECT, INSERT, UPDATE, DELETE, and others, along with clauses like WHERE, GROUP BY, and aggregate functions.

Uploaded by

ashokkmahato2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views23 pages

UNIT3 Parti

SQL, or Structured Query Language, is used to retrieve and manipulate data in relational database management systems (RDMS), which store data in tables. It supports four fundamental operations: SELECT (read), INSERT (create), UPDATE (modify), and DELETE (remove), collectively known as CRUD. The document provides detailed syntax and examples for various SQL commands, including SELECT, INSERT, UPDATE, DELETE, and others, along with clauses like WHERE, GROUP BY, and aggregate functions.

Uploaded by

ashokkmahato2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

What is SQL?

SQL is a language used to retrieve and manipulate data in a RDMS.


SQL stands for Structured Query Language.
What is a Database?
A database is a place to store data.

A relational database system (RDMS) stores data in tables.

Relational Database Tables


A relational database stores data in tables. Each table has a number of rows and
columns. The table below has 4 rows and 3 columns.

Today, SQL is mostly used by programmers who use SQL inside their language to
build applications that access data in a database.
Four fundamental operations that apply to any database are:
1. Read the data -- SELECT
2. Insert new data -- INSERT
3. Update existing data -- UPDATE
4. Remove data – DELETE
Collectively these are referred to as CRUD (Create, Read, Update, Delete). The
general form for each of these 4 operations in SQL is:
The SQL SELECT general form

SELECT column-names
FROM table-name

WHERE condition
ORDER BY sort-order;

Example:
SELECT FirstName, LastName, City, Country
FROM Customer
WHERE City = 'Paris'
ORDER BY LastName;

The SQL INSERT general form


INSERT into table-name (column-names)
VALUES (column-values);

Example:
INSERT into Supplier (Name, ContactName, City, Country)
VALUES ('Oxford Trading', 'Ian Smith', 'Oxford', 'UK');

The SQL UPDATE general form


UPDATE table-name
SET column-name = column-value
WHERE condition;
Example:
UPDATE OrderItem
SET Quantity = 2
WHERE Id = 388;

The SQL DELETE general form


DELETE from table-name
WHERE condition;

Example:
DELETE from Customer
WHERE Email = '[email protected]';

SQL SELECT Statement:


 The SELECT statement is used to select data from a database.
 The data returned is stored in a result table, called the result-set.
 SELECT is the most frequently used action on a database.
Examples:
The general syntax is:
SELECT column-names
FROM table-name;

To select all columns, use *


SELECT * FROM table-name;

Problem: List all customers.


SELECT *
FROM Customer;
Problem: List the first name, last name, and city of all customers.
SELECT FirstName, LastName, City
FROM Customer;
SQL WHERE Clause:
 To limit the number of rows, use the WHERE clause.
 The WHERE clause filters for rows that meet certain criteria.
 WHERE is followed by a condition that returns either true or false.
 WHERE is used with SELECT, UPDATE, and DELETE.
The SQL WHERE syntax:
A WHERE clause with a SELECT statement:
SELECT column-names
FROM table-name
WHERE condition;

A WHERE clause with an UPDATE statement:

UPDATE table-name
SET column-name = value
WHERE condition;
A WHERE clause with a DELETE statement:
DELETE FROM table-name
WHERE condition;

SQL WHERE Clause Examples


Problem: List the customers in Sweden.
SELECT Id, FirstName, LastName, City, Country, Phone
FROM Customer
WHERE Country = 'Sweden';
Problem: Update the city to Sydney for supplier Pavlova, Ltd.
UPDATE Supplier
SET City = 'Sydney'
WHERE Name = 'Pavlova, Ltd.';
Problem: Delete all products with unit price higher than $50.

DELETE FROM Product


WHERE UnitPrice> 50;

Note: Referential Integrity may prevent this deletion.

SQL INSERT INTO Statement:


 The INSERT INTO statement is used to add new data to a database.
 The INSERT INTO statement adds a new record to a table.
 INSERT INTO can contain values for some or all of its columns.
 INSERT INTO can be combined with a SELECT to insert records.

The SQL INSERT INTO syntax:


The general syntax is:
INSERT INTO table-name (column-names)
VALUES (values);
SQL INSERT INTO Examples:
Problem: Add a record for a new customer.
INSERT INTO Customer (FirstName, LastName, City, Country, Phone)
VALUES ('Craig', 'Smith', 'New York', 'USA', 1-01-993 2800);
Problem: Add a new customer named Anita Coats to the database.
INSERT INTO Customer (FirstName, LastName)
VALUES ('Anita', 'Coats');
SQL CREATE DATABASE Statement:
The CREATE DATABASE statement is used to create a new SQL database.
Syntax:
CREATE DATABASE databasename;
Example
CREATE DATABASE test;

SQL DROP DATABASE Statement:


The DROP DATABASE statement is used to drop an existing SQL
database. Syntax
DROP DATABASE databasename;
Example
DROP DATABASE test;

SQL CREATE TABLE Statement:


The CREATE TABLE statement is used to create a new table in a
database. Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
....
);
 The column parameters specify the names of the columns of the table.
 The datatype parameter specifies the type of data the column can hold (e.g.
varchar, integer, date, etc.).
SQL CREATE TABLE Example:
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
A copy of an existing table can also be created using CREATE
TABLE. Syntax
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
Example
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;

SQL DROP TABLE Statement


The DROP TABLE statement is used to drop an existing table in a database.
Syntax
DROP TABLE table_name;
Example
DROP TABLE Persons;
SQL TRUNCATE TABLE
The TRUNCATE TABLE statement is used to delete the data inside a table, but
not the table itself.
Syntax
TRUNCATE TABLE table_name;

ALTER TABLE Statement


The ALTER TABLE statement is used to add, delete, or modify columns in an
existing table.

The ALTER TABLE statement is also used to add and drop various constraints on
an existing table.

 ALTER TABLE - ADD Column


To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype;
Example:
ALTER TABLE Customers
ADD Email varchar(255);

 ALTER TABLE - DROP COLUMN


To delete a column in a table, use the following syntax (notice that some database
systems don't allow deleting a column):

ALTER TABLE table_name


DROP COLUMN column_name;
Example
ALTER TABLE Customers DROP COLUMN Email;
 ALTER TABLE-MODIFY COLUMN
To modify a column in table, use the following syntax.

ALTER TABLE table_name MODIFY coulumn_name;

SQL ORDER BY Examples


Problem: List all suppliers in alphabetical order
SELECT CompanyName, ContactName, City,
Country FROM Supplier
ORDER BY CompanyName;
Problem: List all suppliers in reverse alphabetical order
SELECT CompanyName, ContactName, City,
Country FROM Supplier
ORDER BY CompanyName DESC;
Problem: List all customers ordered by country, then by city within each
country Ordering by one or more columns is possible.
SELECT FirstName, LastName, City,
Country FROM Customer
ORDER BY Country, City;
Problem: List all suppliers in the USA, Japan, and Germany, ordered by
city.
SELECT Id, CompanyName, City, Country
FROM Supplier
WHERE Country IN ('USA', 'Japan', 'Germany')
ORDER BY City ASC;
SQL SELECT TOP Statement:
 The SELECT TOP statement returns a specified number of records.
 SELECT TOP is useful when working with very large datasets.
 Non SQL Server databases use keywords like LIMIT and ROWNUM.

The SQL SELECT TOP syntax


The general syntax is:
SQL SERVER Syntax:
SELECT TOP number | percent column_name(s)
FROM table_name
WHERE condition;
MySQL Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Oracle Syntax:
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
Example:
Problem: List top 10 most expensive products.
SELECT TOP 10 Id, ProductName, UnitPrice, Package
FROM Product
ORDER BY UnitPrice DESC;

SQL SELECT DISTINCT Statement:


 SELECT DISTINCT returns only distinct (different) values.
 SELECT DISTINCT eliminates duplicate records from the results.
 DISTINCT can be used with aggregates: COUNT, AVG, MAX, etc.
 DISTINCT operates on a single column. DISTINCT for multiple columns is
not supported.
The SQL SELECT DISTINCT syntax
The general syntax is:
SELECT DISTINCT column-name
FROM table-name;

Can be used with COUNT and other aggregates


SELECT COUNT (DISTINCT column-name)
FROM table-name;
SQL SELECT Examples:
Problem: List all supplier countries in alphabetical order.
SELECT DISTINCT Country
FROM Supplier
ORDER BY COUNTRY;
Problem: List the number of supplier countries
SELECT COUNT (DISTINCT Country)
FROM Supplier;

AGGREGATE FUNCTIONS

SQL SELECT MIN, MAX Statement:


 SELECT MIN returns the minimum value for a column.
 SELECT MAX returns the maximum value for a column.
The SQL SELECT MIN and MAX syntax
The general MIN syntax is:
SELECT MIN(column-name)
FROM table-name;

The general MAX syntax is:


SELECT MAX(column-name)
FROM table-name;
Problem: Find the cheapest product
SELECT MIN(UnitPrice)
FROM Product;

Problem: Find the last order date in 2013.


SELECT MAX(OrderDate)
FROM [Order]
WHERE YEAR(OrderDate) = 2013;

SQL SELECT COUNT, SUM, AVG:


 SELECT COUNT returns a count of the number of data values.
 SELECT SUM returns the sum of the data values.
 SELECT AVG returns the average of the data values.

The SQL SELECT COUNT, SUM, and AVG syntax


The general COUNT syntax is:
SELECT COUNT(column-name)
FROM table-name;

The general SUM syntax is:


SELECT SUM(column-name)
FROM table-name;

The general AVG syntax is:


SELECT AVG(column-name)
FROM table-name;

SQL SELECT COUNT, SUM, and AVG Examples:


Problem: Find the number of customers.
SELECT COUNT(Id)
FROM Customer;
Problem: Compute the total amount sold in 2013
SELECT SUM(TotalAmount)
FROM [Order]
WHERE YEAR(OrderDate) = 2013;
Problem: Compute the average size of all orders
SELECT AVG(TotalAmount)
FROM [Order];

SQL WHERE AND, OR, NOT Clause:


 WHERE conditions can be combined with AND, OR, and NOT.
 A WHERE clause with AND requires that two conditions are true.
 A WHERE clause with OR requires that one of two conditions is true.
 A WHERE clause with NOT negates the specified condition.

The WHERE with AND, OR, NOT syntax


A WHERE clause with AND:
SELECT column-names
FROM table-name
WHERE condition1 AND condition2;
A WHERE clause with OR:
UPDATE table-name
SET column-name = value
WHERE condition1 OR condition2;

A WHERE clause with NOT:


DELETE FROM table-name
WHERE NOT condition;

SQL WHERE with AND, OR, and NOT Examples


Problem: Get customer named Abhimanuyadav.
SELECT Id, FirstName, LastName, City, Country
FROM Customer
WHERE FirstName = ' ram ' AND LastName = 'kumar';

Problem: List all customers from Nepal or India.


SELECT Id, FirstName, LastName, City, Country
FROM Customer
WHERE Country = 'Nepal' OR Country = 'India';
Problem: List all customers that are not from the USA.
SELECT Id, FirstName, LastName, City, Country
FROM Customer
WHERE NOT Country = 'USA';
Problem: List all orders that not between $50 and $15000.
SELECT Id, OrderDate, CustomerId, TotalAmount
FROM [Order]
WHERE NOT (TotalAmount>= 50 AND TotalAmount<= 15000)
ORDER BY TotalAmount DESC;

SQL WHERE BETWEEN Clause:


 WHERE BETWEEN returns values that fall within a given range.
 WHERE BETWEEN is a shorthand for >= AND <=.
 BETWEEN operator is inclusive: begin and end values are included.

The SQL WHERE BETWEEN syntax


The general syntax is:
SELECT column-names
FROM table-name
WHERE column-name BETWEEN value1 AND value2;
SQL WHERE BETWEEN Examples
Problem: List all products between $10 and $20.
SELECT Id, ProductName, UnitPrice
FROM Product
WHERE UnitPrice BETWEEN 10 AND
20 ORDER BY UnitPrice;
Problem: List all products not between $10 and $100 sorted by price.
SELECT Id, ProductName, UnitPrice
FROM Product
WHERE UnitPrice NOT BETWEEN 5 AND
100 ORDER BY UnitPrice;
Problem: Get the number of orders and amount sold between Jan 1, 2013 and
Jan31, 2013.
SELECT COUNT(Id), SUM(TotalAmount)
FROM [Order]
WHERE OrderDate BETWEEN '1/1/2013' AND '1/31/2013';

SQL WHERE IN Clause:


 The IN operator allows you to specify multiple values in a WHERE clause.
 The IN operator is a shorthand for multiple OR conditions.
The SQL WHERE IN syntax
The general syntax is:
SELECT column-names
FROM table-name
WHERE column-name IN (values);
SQL WHERE IN Examples
Problem: List all suppliers from the India, Pakistan, OR Japan.
SELECT Id, CompanyName, City, Country
FROM Supplier WHERE Country IN ('India', 'Pakistan',
'Japan');

Problem: List all products that are not exactly $10, $20, $40, or $50
unitprice.
SELECT Id, ProductName, UnitPrice
FROM Product
WHERE UnitPrice NOT IN (10,20,40,50);
Problem: List all customers that are from the same countries as the
suppliers.
SELECT Id, FirstName, LastName, Country
FROM Customer
WHERE Country IN (SELECT Country FROM Supplier);
SQL WHERE LIKE Statement:
The LIKE operator is used in a WHERE clause to search for a specified pattern in
a column.
There are two wildcards often used in conjunction with the LIKE operator:
 % - The percent sign represents zero, one, or multiple characters.
 _ - The underscore represents a single character.
The SQL WHERE LIKE syntax
The general syntax is:
SELECT column-names
FROM table-name
WHERE column-name LIKE value;
SQL WHERE LIKE Examples
Problem: List all products with names that start with
'Ca'.SELECT Id, ProductName, UnitPrice,
Package
FROM Product
WHERE ProductName LIKE 'Ca%';

Problem: List all products that start with 'Cha' or 'Chan' and have one
morecharacter.
SELECT Id, ProductName, UnitPrice, Package
FROM Product
WHERE ProductName LIKE 'Cha_' OR ProductName LIKE 'Chan_';

Here are some examples showing different LIKE operators with '%' and '_'
wildcards:
SQL IS NULL Clause:
What is a NULL Value?
 A field with a NULL value is a field with no value.
 If a field in a table is optional, it is possible to insert a new record or update
a record without adding a value to this field. Then, the field will be saved
with a NULL value.
Note: A NULL value is different from a zero value or a field that contains
spaces.A field with a NULL value is one that has been left blank during record
creation!

The SQL WHERE IS NULL syntax


The general syntax is:
SELECT column-names
FROM table-name
WHERE column-name IS NULL;
The general not null syntax is:
SELECT column-names
FROM table-name
WHERE column-name IS NOT NULL;
SQL WHERE IS NULL Examples
Problem: List all suppliers that have no fax number
SELECT Id, CompanyName, Phone, Fax
FROM Supplier
WHERE Fax IS NULL;
Problem: List all suppliers that do have a fax number
SELECT Id, CompanyName, Phone, Fax
FROM Supplier
WHERE Fax IS NOT NULL;

SQL GROUP BY Clause:


 The GROUP BY clause groups records into summary rows.
 GROUP BY returns one records for each group.
 GROUP BY typically also involves aggregates: COUNT, MAX, SUM,
AVG, etc.
 GROUP BY can group by one or more columns.
The SQL GROUP BY syntax
The general syntax is:
SELECT column-names
FROM table-name
WHERE condition
GROUP BY column-names;
The general syntax with ORDER BY is:
SELECT column-names
FROM table-name
WHERE condition
GROUP BY column-names
ORDER BY column-names;
SQL GROUP BY Examples
Problem: List the number of customers in each
country
SELECT COUNT(Id), Country
FROM Customer
GROUP BY Country;

Problem: List the number of customers in each country sorted high to


low
SELECT COUNT(Id), Country
FROM Customer
GROUP BY Country
ORDER BY COUNT(Id) DESC;

Problem: List the total amount ordered for each customer


SELECT SUM(O.TotalPrice), C.FirstName,
C.LastName FROM [Order] O JOIN Customer C
ON O.CustomerId = C.Id
GROUP BY C.FirstName, C.LastName
ORDER BY SUM(O.TotalPrice) DESC;

SQL HAVING Clause:


The HAVING clause was added to SQL because the WHERE keyword could not
be used with aggregate functions.
The SQL HAVING syntax
The general syntax is:
SELECT column-names
FROM table-name
WHERE condition
GROUP BY column-names
HAVING condition;
The general syntax with ORDER BY is:
SELECT column-names
FROM table-name
WHERE condition
GROUP BY column-names
HAVING condition
ORDER BY column-names;

SQL GROUP BY Examples


Problem: List the number of customers in each country. Only include countries
with more than 10 customers.
SELECT COUNT(Id), Country
FROM Customer
GROUP BY Country
HAVING COUNT(Id) > 10;

Problem: List the number of customers in each country, except the USA,
sortedhigh to low. Only include countries with 9 or more customers.
SELECT COUNT(Id), Country
FROM Customer
WHERE Country <> 'USA'
GROUP BY Country
HAVING COUNT(Id) >= 9
ORDER BY COUNT(Id) DESC;

Problem: List all customer with average orders between $1000 and $1200.
SELECT AVG(TotalAmount), FirstName, LastName
FROM [Order] O JOIN Customer C ON O.CustomerId = C.Id
GROUP BY FirstName, LastName
HAVING AVG(TotalAmount) BETWEEN 1000 AND 1200;

SQL Alias:
 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 the query.
The SQL Alias syntax
The general syntax is:
SELECT column-name AS alias-name
FROM table-name alias-name
WHERE condition;

SQL Alias Examples


Problem: List total customers in each country.
SELECT COUNT(C.Id) AS TotalCustomers, C.Country AS
Nation
FROM Customer C
GROUP BY C.Country;

Problem: Creates an alias named "CustomerName" that combine two


columns(FirstName,LastName).
SELECT CONCAT(FirstName,LastName) AS
CustomerName FROM Customer;

You might also like