0% found this document useful (0 votes)
19 views14 pages

SQL It Vedant

The document provides a comprehensive overview of SQL commands and concepts, including data manipulation, querying, and database structure. It covers various SQL operations such as creating tables, inserting data, updating records, and using different types of joins. Additionally, it explains data types, constraints, and advanced querying techniques, along with practical examples and challenges for SQL proficiency.
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)
19 views14 pages

SQL It Vedant

The document provides a comprehensive overview of SQL commands and concepts, including data manipulation, querying, and database structure. It covers various SQL operations such as creating tables, inserting data, updating records, and using different types of joins. Additionally, it explains data types, constraints, and advanced querying techniques, along with practical examples and challenges for SQL proficiency.
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/ 14

Confusion-

 When we want to add new col in table


 Alter table employees add doj date;
 When we want to add new value in recently added col
 Update employees set doj='2024-12-01' where name = 'Abhi';
 Select Name , sum(salary) as Total_Sal from employees group by Name;
 select name,dept, concat(name,' ',dept) as name_dept from employees;- This is used for to
concat two different string in same table
 create table t2- To create table
creat table employee (id int not null, department varchar(50), age int);
 insert into t2 values (1,'FSD',20);- to add values
 INSERT INTO table_name (column1, column2, ..., columnN)
 VALUES (value1, value2, ..., valueN);

25th DEC 2024

 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');

26th dec 2024

 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.

 Sql is relational database structured databases. Backbone of data management enabling


efficient storange and manipulation(blending of data) of information. Fosterimg data
integrity and concictency
 Data re by default arramged in ascending order
 Navigating the structured databases-schema>>tables>>col>row attributes of data are like
name we assign them to identify them- primary key is unique//Foreign key – difference
 Schema- bluwprint of a databse, definig tabeles, col, relationship b/w them
 F.key is know as Referential integrity—( establishes a relationship with the primary key of
another table.
  Purpose: It is used to maintain referential integrity by ensuring that the value in the
foreign key matches an existing value in the referenced primary key.)
 P.KEY- IT UNIquly indentifies the records
 Working with tables and rows-
 Create table>>add rows>>modify rows>.delete rows
DATATYPES
 Int-whole numbers we don’t give bytes
 Float- decimals
 Alpha numeric(complex no.)50j
 Strings(char,varchar,nchar.)—Varchar/char we need to give bytes, in””—char(it stores the
bytes that might cause storage issue) and varchar (it passes on the remaining bytes to
others)difference- storange issue/ issue of omptimization/

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

QUERYING DATA WITH SQL

 Select- retrieve data from table based on criteria


 FROM- Specify the table from which data is to be extracted
 Where- Filter data on condituion to narrow down result
 Order By- default is asc so no need to write in command, sorting retrived data acc to
specific col or criteria.

MANIPULATING DATA WITH SQL

 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**: +, -, *, /, %

- **Comparison Operators**: =, <>, >, <, >=, <=

- **Logical Operators**: AND, OR, NOT

**What is the difference between a database and a table?**

- 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

3rd Jan 2025

 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

 5. Adding or Removing Indexes



 To add or remove indexes on columns for faster data retrieval:

 - **Adding an index**:
 ```sql
 CREATE INDEX index_name
 ON table_name (column_name)
 - **Purpose**: Dropping a table in SQL means permanently
removing the table and all its data from the database. This
operation is irreversible and should be done with caution.
 INSERT DATA USING A SELECT STATEMENT-
#insert into student (name,dob,email,mob_no)
select name,dob,email.mob_no from join_2024 where
name=’Abhinav’;
 Auto increment is used with Primary key and pk is used to ensure
there is data integrity
 Constraint in sql are like rules in data bases to prevent
chaos and maintain an order
 Foreign key- referential integrity how to create PK and Fk
 What is index in sql??

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.

 HOW TO NETWORK- HOW To start- where to start.


 What is Intersect in SQL-??

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

If want one table all data ex- order.*


 Cross Joins we don’t define on condition

 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

 Full joins or union


 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

1. DDL (Data Definition Language):

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.

Common DDL Commands (TADrC)


 CREATE: Creates a new database object (e.g., table, view).

 ALTER: Modifies an existing database object.

 DROP: Deletes a database object.

 TRUNCATE: Removes all records from a table but retains its structure.

Example:

sql

CopyEdit

-- Create a table

CREATE TABLE Employees (

EmployeeID INT PRIMARY KEY,

Name VARCHAR(50),

Department VARCHAR(50)

);

-- Alter the table to add a column

ALTER TABLE Employees ADD Salary DECIMAL(10, 2);

-- Drop the table

DROP TABLE Employees;

2. DML (Data Manipulation Language):


DML commands are used to manipulate the data within tables. These commands handle inserting,
updating, deleting, and retrieving data.

Common DML Commands:

 INSERT: Adds new records to a table.

 UPDATE: Modifies existing records.

 DELETE: Removes records from a table.

Example:

sql

CopyEdit

-- Insert a record

INSERT INTO Employees (EmployeeID, Name, Department, Salary)

VALUES (1, 'Alice', 'HR', 50000);

-- Update a record

UPDATE Employees

SET Salary = 55000

WHERE EmployeeID = 1;

-- Delete a record

DELETE FROM Employees

WHERE EmployeeID = 1;

3. DQL (Data Query Language):

DQL commands are used to query data from the database. The primary command in this category is
SELECT.

Common DQL Commands:

 SELECT: Retrieves data from the database.

Example:

sql

CopyEdit

-- Select all columns from the Employees table

SELECT * FROM Employees;


-- Select specific columns

SELECT Name, Salary

FROM Employees

WHERE Department = 'HR';

Summary Table:

Category Purpose Common Commands

DDL Define or modify database schema CREATE, ALTER, DROP, TRUNCATE

DML Manipulate data in tables INSERT, UPDATE, DELETE

DQL Query data from the database SELECT

TO FIND THE UNMATCHED OR UNOREDED RECORDS IN 2 TABLE ILL USE THE


NOT IN FUNCTION FOR EX- this will give me unordered pizza

- Interview question- in not null que must where there is no manager


- Logic test..||
- Communication
-

>> Show patient_id, diagnosis from admissions. Find patients admitted multiple times for the same
diagnosis.

Elaborate- same table se syntax-**select patient_id,diagnosis from admissions group by patient_id,


diagnosis having count(*)>1;**

 Remove NULL values from query.


For this we use **where col_name is NOT NULL**
 Want to include 2 where clause in one syntax—

In 2nd where caluse see how we use odd term

>> 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

>>Show all of the patients grouped into weight groups.


Show the total amount of patients in each weight group.
Order the list by the weight group decending.

For example, if they weight 100 to 109 they are placed in the 100 weight group, 110-119 =
110 weight group, etc.

select count(*) as patients_in_group,


(weight/10)*10 as weight_group
from patients
group by weight_group
order by weight_group desc

>>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.

 what is order of execution in sql


>>In SQL, the order of execution (also known as the logical processing order) is different
from thway a query is written. Understanding this order is crucial for SQL optimization and
interview success.
SELECT DISTINCT department, AVG(salary) AS avg_salary
FROM employees
WHERE salary > 50000
GROUP BY department
HAVING AVG(salary) > 60000
ORDER BY avg_salary DESC
LIMIT 5;
 Diff b/w where and having-
both used to filter records in SQL, but they are used in different contexts.
WHERE Clause
 Purpose: Used to filter records before any groupings are made.
 Usage: Applicable to individual rows in the table.
 Application: Can be used with SELECT, UPDATE, DELETE, etc

HAVING Clause

 Purpose: Used to filter records after groupings are made.


 Usage: Applicable to groups of rows created by the GROUP BY clause.
 Application: Typically used with aggregate functions like COUNT, SUM, AVG, etc.

 What is the use of group by?

>>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

You might also like