Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

SQL (4)

SQL is a structured query language used to manage and manipulate data in relational databases. It consists of various commands categorized into DDL, DML, DCL, TCL, and DQL, along with data types, constraints, and aggregate functions. The document also provides examples of SQL queries for data retrieval and manipulation.

Uploaded by

shubham26may2000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

SQL (4)

SQL is a structured query language used to manage and manipulate data in relational databases. It consists of various commands categorized into DDL, DML, DCL, TCL, and DQL, along with data types, constraints, and aggregate functions. The document also provides examples of SQL queries for data retrieval and manipulation.

Uploaded by

shubham26may2000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

SQL

Structured Query Language

SQL is a query language to query the data from Relational


database systems like MySQL, MS SQL Server etc..

SQL Commands :
There are 5 SQL commands -
1.​Data definition language (DDL) : Used to define structure of
the table.
DDL : CREATE , ALTER , DROP , TRUNCATE ,RENAME etc.

2.​Data manipulation language (DML) : Used to make changes in


the data present in the table.
DML : INSERT, UPDATE , DELETE

3.​Data control language (DCL) : Used to control the access to


the data.
DCL : GRANT , REVOKE

4.​Transaction control language (TCL) : Used to manage the


transactions on databases.
TCL : COMMIT , ROLLBACK ,SAVEPOINT

5.​Data Query Language (DQL) : used to query the data from the
database.
DQL : SELECT
SQL Data types :

A data type in SQL defines what kind of data a column, variable can
hold

Numeric:
Numeric data types are used to store numbers.

●​ INT: Integer from -2,147,483,648 to 2,147,483,647.


●​ DECIMAL(p, s) & NUMERIC(p, s): Fixed precision and scale
numbers (up to 38 digits).
●​ MONEY: Monetary values from -922,337,203,685,477.5808 to
922,337,203,685,477.5807.

Date and Time:


Date and time data types are used to store dates and times.
●​ DATE Only dates (e.g., "2025-01-15").
●​ TIME Only time (e.g., "14:30:00").
●​ DATETIME Both date and time together. (E.g - 2025-01-15
14:30:00 )

Character and String:


Character and string data types are used to store text. Examples of
●​ CHAR(x)
●​ VARCHAR(x) Variable-length text (e.g., names, email).

Binary:
Binary data types are used to store binary data, such as images
and files.
●​ BINARY Fixed-length binary data
●​ VARBINARY Variable-length binary data for files, images, etc.
SQL Constraints :
SQL Constraints are rules or conditions that you apply to columns
in a table to ensure the data's integrity, accuracy, and reliability.

Let say we have an employee table and a project table

●​ NOT NULL
Ensures that a column cannot have empty values.
EmployeeName , Email

●​ UNIQUE
Ensures all values in a column are different.
Email , ProjectName

●​ PRIMARY KEY
A combination of NOT NULL and UNIQUE. It identifies each
record in a table uniquely.
EmployeeID , ProjectID
●​ FOREIGN KEY
A column that links to the Primary Key of another table. This
ensures referential integrity.

●​ EmployeeID in the Projects table references EmployeeID


in the Employees table.
●​ Ensures that every EmployeeID in Projects must exist in
Employees.

●​ CHECK
Ensures values in a column meet a specific condition.

If we want any Salary shouldn’t be less than 3000 then we will


apply check constraint in Salary column
CHECK (Salary >= 3000)

●​ DEFAULT
Assigns a default value to a column if no value is provided
during insertion.

DEFAULT Automatically fills the Country field with 'USA' if no


value is provided during data insertion.
CREATE and INSERT VALUES in Table :

Let’s see what we can do with our tables :

WHERE clause : The WHERE clause allows the user to filter the
data from the table. The WHERE clause allows the user to extract
only those records that satisfy a specified condition

Lets i want to see the details of customer with Customer_ID C2

Operators in where clause


= Equal
> Greater than
< Less than
>= Greater than equal
<= Less than equal
< > Not equal (also written as !=)
BETWEEN Between a range
LIKE Search for pattern
IN Specify multiple possible values for a column

ORDER BY :
Order by is used to print the values from the table in
order(ascending or descending)

Order By in Descending order


SELECT first_name, last_name,email FROM customer ORDER BY
first_name DESC;
Order By in Ascending order
SELECT first_name, last_name,email FROM customer ORDER BY
first_name ASC;

SQL Aggregate functions :

MAX , MIN , SUM, AVG , COUNT

LIKE function - Used with WHERE to get specific pattern in a


column
Used with two wildcards 1st is % and 2nd is _

For getting the values which starts with a

Select product_name from Products​


Where product_name like ‘a% ’

For getting the values which ends with a


Select product_name from Products​
Where product_name like ‘%a’

For getting the values which contains ah

Select product_name from Products​


Where product_name like ‘%ah%’

For getting the values which starts with a and ends with h

Select product_name from Products​


Where product_name like ‘a%h’

For getting the values which starts with a and at least are 5
character sin length

Select product_name from Products​


Where product_name like ‘a______%’

(6 underscores are used)


use Practice

select * from dbo.mock_sales_data

Q1. Calculate the product wise quantity of products sold

select Product , sum(Quantity_Sold) Qty_sold


from dbo.mock_sales_data
group by Product

Q2.Calculate the product wise quantity of products sold for


November 2022

select Product , sum(Quantity_Sold) Qty_sold


from dbo.mock_sales_data
where month(Date) ='11' and year(Date) = '2022'
group by Product

-- Calculate the top selling product (quantity wise) in 2021-june


select TOP 1 product , Sum(Quantity_Sold) Qty_sold
from dbo.mock_sales_data
where month(Date) ='06' and year(Date) = '2021'
group by Product
order by Qty_sold

Q3. Calculate the top selling product quantity wise in year 2021
month wise

Year | month | product | Total Quantity Sold


​ ​ ​ ​ ​

WITH RANK_TABLE AS (​ ​ ​
SELECT
Year(Date) AS Year,
Month(Date) AS Month,
Product,
SUM(Quantity_Sold) AS TotalQuantitySold,
RANK() OVER (PARTITION BY Month(Date) ORDER BY
SUM(Quantity_Sold) DESC) AS Rank
FROM
dbo.mock_sales_data
WHERE
Year(Date) = 2021
GROUP BY
Year(Date), Month(Date), Product
)
SELECT
Year,
Month,
Product,
TotalQuantitySold
FROM RANK_TABLE
where Rank = 1

Q4. give the product , month and year in which product was sold
higest, qtysold ,total price

WITH grouped_data AS (
SELECT
YEAR(Date) AS yr,
MONTH(Date) AS mon,
Product,
SUM(Quantity_Sold) AS qty_sold,
SUM(Unit_Price) AS unit_price_sum
FROM
dbo.mock_sales_data
GROUP BY
YEAR(Date), MONTH(Date), Product
),
final_table AS (
SELECT
*,
RANK() OVER (PARTITION BY Product ORDER BY
unit_price_sum DESC) AS rankedrow
FROM
grouped_data
)
SELECT Product,yr,mon,qty_sold,unit_price_sum
FROM final_table
where rankedrow = 1

Q5. Give the list of the topsales man with total quantity sold
year-monthly wise

WITH grouped_sales as (
select year(Date)yr,Month(Date)mon ,Salesperson sp
,SUM(Quantity_Sold) qty_sold
from dbo.mock_sales_data
group by year(Date),Month(Date),Salesperson
),

pertition as(
select yr,mon,sp,qty_sold, Rank()over(partition by yr, mon order by
qty_sold desc)rnkcol
from grouped_sales )

select yr,mon,sp,qty_sold from pertition


where rnkcol = 1

Q6. to get the top salesman yearwise

WITH grouped_sales as (
select year(Date)yr ,Salesperson sp ,SUM(Quantity_Sold) qty_sold
from dbo.mock_sales_data
group by year(Date),Salesperson
),

pertition as(
select yr,sp,qty_sold, Rank()over(partition by yr order by qty_sold
desc)rnkcol
from grouped_sales )

select yr,sp,qty_sold from pertition


where rnkcol = 1

You might also like