SQL It Vedant
SQL It Vedant
select(10+10) as addition;
select(20-10) as sub;
select length('INDIA') as Total_char;
select repeat('psg',2);
select upper('india');
select lower('INDIA');
Select curdate();
select day(curdate());
select month(curdate());
select year(curdate());
select now();
select length(name) as total_char from employees;
select concat('India',' ','is',' ','in',' ','Asia')as Facts;
select * from employees;
select name, desig , concat(name,' ',desig) from employees;
update employees set desig='peon' where name ='Neel';
select*from employees;
use bank_db;
select name,dept, concat(name,' ',dept) as name_dept from employees;
select reverse('Abhinav');
ASCII value, or American Standard Code for Information Interchange value, is a numeric code
that represents a character in a computer: - Syntax- select ascii(‘0’);
Group by clause is a part of select expression that grp records into summary rows and
returns one record for each grp syntax- select dept, avg(salary) as AVG_SAL from
employees group by dept;
Select distincy city from employees; This syntax will retur us the unique values without any
repetative data.
select count(distinct dept) as total_dept from employees; This will return me the total no. of
dept present in the table.
Select avg(age) from emply;- this will give me the avg age
Select dept, sum(salary) as total_salary from emply group by dept- This will give me total
s;ary for each dept
Select count(emp_id),dept from emplyy group by dept, order by count(empy_id);-- This will
arrange the empy-id and aarnage it with arder.
VARCHAR stores variable-length charact er strings, while CHAR stores fixed-length character strings.
VARCHAR is more space-efficient for variable-length data.
Nchar- in case we need to add special character we use this >>storage as char
Date/time- represemt date and time including s.formats and times zones
Boolean- either T or F indicating binary choices- logic test of if as excel
INSERT- addin new rows to tables,populating the database with fresh data
UPDATE- Modify exsisiting data with rows,making changes and updates
DELETE- Removing unwanted data or outdated rows from tables, maintain data intergrity
ALTER-
- **Operators**
- **Arithmetic Operators**: +, -, *, /, %
- A database is a collection of related data organized for efficient retrieval, while a table is a
collection of rows and columns that stores data in a structured format within a database
Some Differences Between VARCHAR and TEXT or char The VAR in VARCHAR means that you
can set the max size to anything between 1 and 65,535. TEXT fields have a fixed max size of
65,535 characters
03-01-2025
IN Operator
Matches any value in a specified list.
Syntax: value IN (value1, value2, ...)
Example:
SELECT * FROM customers WHERE state IN ('CA', 'NY', 'TX');
What is NULL value in SQL-
A value that is currently unknown , value maybe determined in future, old value is deleted
without a replacement
The CASE statement in SQL is used to perform conditional logic within queries.
It allows you to execute different actions based on different conditions.
CASE statement evaluates conditions in order and returns the result of the first true
condition. NULL values can be handled explicitly using IS NULL condition within CASE.
08-01-2025
WHERE column_name = NULL does not return any rows because NULL is
not equal to any value, including itself.
Types of joins
Joins are used to retrieve data from two or more table based on related columns. This is essential in
relational databases, where data is sorted across multiple tables to reduce redundancy and improve
organization.what
Inner join there a prerequisite that there should be a common data set(rows) b/w both the
table—it returns the matching rows from both the table
Left-Join
Right Join
Self-join- . It is used when you need to compare rows within the same table or extract
hierarchical relationships.
Full outer join- full outer join combines the result of both L AND R joins includes all the rows
from both the table,with nulls where there is no matches.
DDL.DML,DQL
--In SQL, commands are categorized into different groups based on their purpose.
Here’s an explanation of DDL, DML, and DQL:--L
DDL commands are used to define and manage database schema (structures). These commands deal
with creating, modifying, and deleting database objects like tables, indexes, and views.
TRUNCATE: Removes all records from a table but retains its structure.
Example:
sql
CopyEdit
-- Create a table
Name VARCHAR(50),
Department VARCHAR(50)
);
Example:
sql
CopyEdit
-- Insert a record
-- Update a record
UPDATE Employees
WHERE EmployeeID = 1;
-- Delete a record
WHERE EmployeeID = 1;
DQL commands are used to query data from the database. The primary command in this category is
SELECT.
Example:
sql
CopyEdit
FROM Employees
Summary Table:
>> Show patient_id, diagnosis from admissions. Find patients admitted multiple times for the same
diagnosis.
>> Show patient_id, first_name, last_name from patients whose does not have any records
in the admissions table. (Their patient_id does not exist in any admissions.patient_id
rows.)
Yaha pr doo table tha in ^-- in such case we use simple sub-query
Like-- select p.patient_id,p.first_name,p.last_name
from
patients p
where
p.patient_id not in
(select a.patient_id from admissions a)
>>Display a single row with max_visits, min_visits, average_visits where the maximum,
minimum and average number of admissions per day is calculated. Average is rounded to 2
decimal places.
>> select
max(number_of_visits) as max_visits,
min(number_of_visits) as min_visits,
round(avg(number_of_visits),2) as average_visits
from (
select admission_date, count(*) as number_of_visits
from admissions
group by admission_date)
yaha we used sub-query and baad mai within () wale query phle execute hogi uske baad
matchin results jayege 1st query main
For example, if they weight 100 to 109 they are placed in the 100 weight group, 110-119 =
110 weight group, etc.
>>Each admission costs $50 for patients without insurance, and $10 for patients with
insurance. All patients with an even patient_id have insurance.
Give each patient a 'Yes' if they have insurance, and a 'No' if they don't have insurance.
Add up the admission_total cost for each has_insurance group.
Solution-
No 127800
Yes 25110
SELECT
CASE WHEN patient_id % 2 = 0 Then
'Yes'
ELSE
'No'
END as has_insurance,
SUM(CASE WHEN patient_id % 2 = 0 Then
10
ELSE
50
END) as cost_after_insurance
FROM admissions
GROUP BY has_insurance;
💡 Medium Level:
1️⃣ Write a query to find the second highest salary in an employee table.
2️⃣ Fetch all employees whose names contain the letter “a” exactly twice.
3️⃣ How do you retrieve only duplicate records from a table?
4️⃣ Write a query to calculate the running total of sales by date.
5️⃣ Find employees who earn more than the average salary in their department.
6️⃣ Write a query to find the most frequently occurring value in a column.
7️⃣ Fetch records where the date is within the last 7 days from today.
8️⃣ Write a query to count how many employees share the same salary.
9️⃣ How do you fetch the top 3 records for each group in a table?
🔟 Retrieve products that were never sold (hint: use LEFT JOIN).
💡 Challenging Level:
1️⃣ Retrieve customers who made their first purchase in the last 6 months.
2️⃣ How do you pivot a table to convert rows into columns?
3️⃣ Write a query to calculate the percentage change in sales month-over-month.
4️⃣ Find the median salary of employees in a table.
5️⃣ Fetch all users who logged in consecutively for 3 days or more.
6️⃣ Write a query to delete duplicate rows while keeping one occurrence.
7️⃣ Create a query to calculate the ratio of sales between two categories.
8️⃣ How would you implement a recursive query to generate a hierarchical structure?
9️⃣ Write a query to find gaps in sequential numbering within a table.
🔟 Split a comma-separated string into individual rows using SQL.
💡 Advanced Problem-Solving:
1️⃣ Rank products by sales in descending order for each region.
2️⃣ Fetch all employees whose salaries fall within the top 10% of their department.
3️⃣ Identify orders placed during business hours (e.g., 9 AM to 6 PM).
4️⃣ Write a query to get the count of users active on both weekdays and weekends.
5️⃣ Retrieve customers who made purchases across at least three different categories.
HAVING Clause
>>he GROUP BY clause is used to arrange identical data into groups with the help of aggregate
functions. It's typically used with aggregate functions like COUNT, SUM, AVG, MAX, MIN, etc., to
perform operations on each group of rows
. Types of Joins in SQL
Joins are used to combine rows from two or more tables based on a related column.
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
CROSS JOIN- CARTESIAN PRODUCT
SELF JOIN
What are triggers in sql
Triggers are sql code that are automatically executed in response to certain
Events on a table these are used to maintain data integrity.
Example- whenever new customer join in welcome email is to be spend