SQL
😮
Stack// all syntax, variable name 'as you wish' (i.e SELECT, selEct, MOviES, MOVIES, movies,
NamE, RaTing) can use anywhere
1. Open MySQL prompt
mysql -u root -p // command
Enter password: @Deepak******
........
2. To see the databases (It is necessary to add ';' at the and of all commands)
show databases;
........
3. To create new database
create database DB_name;
4. To delete database / Table
DROP DATABASE DB_name; / DROP TABLE Table_Name;
5. Select DataBase on which we will work
USE DB_name;
6. Create table in database
CREATE TABLE Movies(Name VARCHAR(100), Rating INTEGER);
7. To insert data in database
INSERT INTO Movies(Name, Rating) VALUES ("pk",8);
INSERT INTO ACTORS(FIRST_NAME, LAST_NAME, GENDER, NETWORTH) VALUES
("ANIL","KAPOOR","MALE", "140"), ("AMIR", "KHAN", "MALE", "200");
8. To see data of table
SELECT * FROM Movies;
9. To see specific column
SELECT name, rating FROM Movies;
10. To clear console (command prompt)
\! cls
11. Select specific rows
SELECT * FROM Actors WHERE Networth >= 1;
SELECT First_Name, Networth FROM Actors WHERE Networth > 140 OR Networth < 140;
SELECT * FROM Actors WHERE First_Name = "Sunny";
SQL
12. Name starting/ending/include "..." characters
SELECT * FROM Actors WHERE First_Name LIKE "AM%";
SELECT * FROM Actors WHERE First_Name LIKE "%A";
13. Arranging in asc/descending order
SELECT * FROM Actors ORDER BY Networth; // by default asc
SELECT * FROM Actors ORDER BY Networth ASC;
SELECT * FROM Actors ORDER BY Networth DESC;
14. Arranging in asc order on the basis of name
SELECT * FROM Actors WHERE First_Name LIKE "Am%" ORDER BY First_Name ASC;
SELECT * FROM Actors WHERE Gender LIKE "%M%" ORDER BY Gender, Networth ASC; //
Pehle Gender k base pe fir Networth k base pe
15. Pagination: Ek page pr limited records (Indexing of Offset starts from 0)
SELECT * FROM Actors LIMIT 3;
SELECT * FROM Actors LIMIT 2 OFFSET 1;
SELECT * FROM Actors WHERE Gender LIKE "M%" LIMIT 2;
16. Update data
UPDATE Actors SET Networth = 130 WHERE First_Name = "Sunny";
UPDATE Actors SET Networth = 130 WHERE First_Name = "Sunny" AND Last_Name =
“Devol”;
15. Delete a row
DELETE FROM Actors WHERE FIRSTNAME = "ANIL";
16. Describe Actors
DESC Actors;
17. Join Table using Foreign Key
SELECT Name, District FROM Employee_Fk JOIN Address_Fk ON Employee_Fk.Add_Id =
Address_Fk.Address_Id;
SELECT Name, Address, City, District FROM Employee_Fk JOIN Address_Fk ON
Employee_Fk.Add_Id = Address_Fk.Address_Id JOIN City_Fk ON Address_Fk.City_Id =
City_Fk.Id;
SQL
18. Left / Right outer join
L R
SELECT Name, District FROM Employee_Fk LEFT OUTER JOIN Address_Fk ON
Employee_Fk.Add_Id = Address_Fk.Address_Id;
SELECT Name, District FROM Employee_Fk RIGHT OUTER JOIN Address_Fk ON
Employee_Fk.Add_Id = Address_Fk.Address_Id;
SELECT Name, District FROM Address_Fk LEFT OUTER JOIN Employee_Fk ON
Address_Fk.Address_Id = Employee_Fk.Add_Id;
19. Length, As (Alias)
HackerRank SQL question -> Weather Observation Station 5
20. Select, Switch Case
HackerRank SQL question -> Type of Triangle
{ } => CASE, END
21. Unique (distinct)
SELECT DISTINCT State FROM State_Gb;
22. Group by (Count the repetition of states)
SELECT State, Count(*) as TotalCount FROM State_Gb GROUP BY State;
23. Aggregated (इकट्ठा) vs Non-Aggregated Query
1. Aggregated Query:
● Uses aggregate functions to summarize or compute data (like totals, averages, or
counts).
● Often includes a GROUP BY clause to group data before applying the aggregate function.
2. Non-Aggregated Query:
● Does not use aggregate functions.
● Retrieves individual rows or performs simple filtering and sorting operations.
24. Condition on rows use “Where”, Condition on group use “Having”
SELECT COUNT(*) AS Count, State FROM State_Gb GROUP BY State HAVING Count>= 2;
25. Primary key
CREATE TABLE Students ( StudentID INT NOT NULL PRIMARY KEY, Name VARCHAR(100),
Age INT );
MongoDB
- Semicolons(;) are not mandatory
- Key / Value name are case-sensitive
- All queries are case sensitive (1. All small letters, 2. deleteOne (camelCase))
1. Open MongoDB prompt (Connect at MongoDB Compass before it)
mongosh;
2. Show databases
show databases; /or/
show dbs;
3. Use database
use database_name
4. Show collections
show collections
show tables
5. Print documents of collection (// rows of table)
db.collection_name.find()
6. Create new DataBase (select if exist otherwise create)
use new_database
# If mongodb sees that there is no valid collection added in the database, and the db is empty,
it doesn’t list it.
7. Create a collection
db.createCollection(“collection_name”)
# Two documents of the same collection can possess different types of properties.
8. Add a record to collection
db.collection_name.insertOne ( { name : ”Sanket”, standard : ”12”, marks : 94, age : 17, rollno :
2312} );
9. Add multiple records
db.students.insertMany ( [
{
name:"Deepak",
uid:"21BCS9976"
},
{
name:"Kalyan",
uid:"21BCS9986"
MongoDB
}
])
(In sort)
db.students.insertMany([{name:"Deepak", uid:"21BCS9976"},{name:"Kalyan",
uid:"21BCS9986"}])
10. How to import sample db in MongoDB
Step 1: Download JSON file from any github repo, search “mongodb sample database”
Step 2: Create a new database on MongoDB Compass.
Step 3: Click on “ADD DATA” on Compass (top-left green color) and select JSON file. And
Import data.
11. How to import without MongoDB Compass
Step 1: Open your terminal / cmd
Step 2: Change the directory to where you downloaded the JSON (cd file_location)
Step 3: Run cmd “mongoimport --db db_name --collection collection_name --file data.json;”
12. Exit from mongosh
exit
Let's explore the DB we imported:
13. How to see count of documents in a collection
db.collection_name.find().count()
14. Get a certain number of documents
db.weather_data.find().limit(3)
15. Set an offset while querying a data
db.weather_data.find().limit(1).skip(2)
16. Filters the records based on the condition
db.collection_name.find ( { key1 : value1, key2 : value2 } )
db.weather_data.find ( { type : 'FM-13' } ).count()
17. Projections (select specific key-value pair. i.e, select id, name from students)
db.collection_name.find ( { filter1: value1…}, { property1: true, property2: true…} )
db.weather_data.find ( { type:'FM-13' }, { position: true, visibility: true } ) // or
db.weather_data.find ( { }, { position: true, visibility: true } ) // first argument is necessary
18. If we want to manually exclude specific properties
db.weather_data.find ( { }, { position: false, visibility: false} )
MongoDB
19. Delete a document (deleteOne, deleteMany, findOneAndDelete)
db.weather_data.deleteOne({ _id: ObjectId('5553a998e4b02cf7151190b8')})
db.weather_data.deleteOne({callLetters:'FNPG'}) // 9999-1 = 9998
db.weather_data.deleteMany({callLetters:'FNPG'}) // 9998-6 = 9992
db.weather_data.findOneAndDelete({callLetters:'FNPG'}) // same as deleteOne
20. Updation (updateOne, updateMany, ….)
db.collectionName.updateOne ( { filter1:value1}, { &operator: { key:value} } )
db.weather_data.updateOne({ _id: ObjectId('5553a998e4b02cf7151190b8')}, {$set:
{elevation:9998}})
Operators (add ‘$’ with them):
i) $set : set new value {$set: {elevation:9998}}
ii) $inc : increase value by one {$inc: {elevation:1}}
ii) $inc : decrease value by one {$inc: {elevation: -1}}
updateMany: all records which are complying to the filtration criteria will be update
21. Get distinct value of a particular key (all unique value of a key)
db.weather_data.distinct('key')
22. Operators (comparison, logical, bitwise, ….)
db.collectionName.find({property: {operator: ‘value’}}).count()
i) $ne : (not equal to) => db.weather_data.find({type: {$ne: 'FM-13'}}).count()
ii) $eq : equals
iii) $lt : less than => db.weather_data.find({"dewPoint.value":{$lt: 999}}).count()
iv) $lte : less than equal to
v) $gt : greater than
vi) $gte : greater than equal to
vii) $and : logical and
viii) $or : logical or
ix) $not : logical not
x) $nor : logical nor
xi) $in : for checking in array => db.weather_data.find({callLetters: {$in: ['3EHH', '3EIZ',
'3EJF']}}).count()
xii) $nin : not in array
db.weather_data.find({$and: [{"dewPoint.value":{$lt: 999}}, {"dewPoint.value":{$gt:
900}}]}).count()
23. Analyze queries
db.weather_data.find().explain("executionStats")
// stage: ‘COLLSCAN’ means data searched Linearly O(n)
(We can read these on google)
MongoDB
Indexing (for optimization, minimize TC)
Multiple Databases including (MongoDB, RDBMS) provide this feature.
Our data is also maintained in other data structures, and that data structure is maintained based
on which property we want indexing.
“Indexing is a mechanism using which databases prepared more data structures to store data in
a particular order based on a particular keys for faster search”
24. Get existing indexes
db.weather_data.getIndexes()
25. To delete an index
db.weather_data.dropIndex(name) // name will associated with index
26. Create index
(for integer)
db.collection_name.createIndex({property_name:1}) // 1 for ascending and -1 for descending
(for string)
db.collection_name.createIndex({property_name: “text”})
27. Optimized execution (make “elevation’ index first)
db.weather_data.find({elevation:{$lt:500}}).explain("executionStats")
……….……….……….
# Before we created our index on the elevation property we were actually reading all the docs
i.e, approx 9991 docs, to fetch all the docs with elevation less than 5000.
# But after creating the index this number will decrease drastically.
……….……….……….
28. Search for a single word (word should be of index. So, make it index first)
db.collection_name.find ( { $text : { $search : “text_name” } } )
EXAMPLE
Let, for ‘articles’ collection document is:
{ _id: 1, subject: “coffee”, author: “xyz”, views: 50 },
{ _id: 1, subject: “coffee and tea”, author: “xyz”, views: 50 }
Step 1: Make it index
db.articles.createIndex({subject: “text”})
Step 2: Search the text
db.articles.find ( { $text : { $search : “coffee” } } ) // Searched in optimized way
MongoDB
29. Sort the data
db.weather_data.find().sort ( {“dewPoint.value” : 1 }).explain(“executionStats”)