0% found this document useful (0 votes)
8 views15 pages

Update Unix Commands

Uploaded by

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

Update Unix Commands

Uploaded by

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

Sr

UNIX Commands
no
How to hide empty lines in a file?
1
>>>> grep -v ^$ India
How to display the empty lines
2
grep -n ^$ India
How to replace blank values
3
sed ‘s/^$/No Blanks/g’ India
How to delete empty lines in a file? (-I Specifies the "in-place" editing mode)
4
>>>> sed -i /^$/d India
How to print the hidden files?
5
>>>> ls -la
How to find the largest size file. (-maxdepth 1 limits the search to a maximum depth of 1 levels)
6
>>>> find . -maxdepth 1 -type f -exec ls -lh {} \; | sort -k5rh
How to display the files in a directory, size less than 4 MB?
7
>>>> find . -type f -size -4M -exec ls -lh {} \; | sort -k5rh
How do you delete the files older than 10 days?
8
>>> find . -type f -mtime +10 -exec rm {} +
How to display directory which contain given word?
10
>>> find . -type d -name Raj | grep -v "/\."
Want to find out file which is greater than 100MB and not accessed in last one year and want to delete that file
11
>>>> Find . -type f -size +100m -atime +365 -exec rm {} +
How to transfer files from one application Server to another server?
12
>>> scp -p mdv_Distrib.dat aosbl@esxha553 : /path to destination
How to run a process in background and what is it’s advantage?
13 >>> ./1_test.sh & (It allows you to run other commands and perform tasks without waiting for the background
process to complete)
How to check background running process.
14
Jobs
How do you find the number of occurrences of the word in the file?
15
>>> grep -c 'corona' India
How do you find the line numbers for the matching pattern?
16
>>> grep -n covid India.txt
Write a command to print the lines that ends with the word "specific_word"?
17
>>>> grep "doctor$" India
Write a command to print the lines matching with exact word?
18
>>> grep Teacher India
Match all words starting with “Particular String”.
19
>>>> grep ^Mama India
Match all pattern which starts with J and doesn’t follow by u?
20
>>>> grep -P 'J(?!u)' csv
To show below and above 10 lines of the matching pattern? (A= After error & B= Before error)
21
>>> grep -A10 -B10 Error India.txt
To show above 9 lines of the matching pattern? (this use to search error pattern, B= Before error)
22
>>> grep -B9 error csv.txt
How to zip and unzip the files?
23 >>> zip Backup aaa.txt xyz.txt (We can apply this on both file & directory to compress the multiple files)
unzip Backup.zip
How to display files names which contain given word / How to check Raj word is present in how many files.
24
>>> grep -l RAJ *
How to search for multiple matching string in the file?
26
>>> egrep “Teacher|Doctor|Clerk” India
To delete the file which is having permission 664?
27
>>>> find . -type f -perm 664 -delete
How to change the permission of any file?
28
>>>> Chmod 644 India
What is the default permission newly created file and directory?
29
>>>> File 644 & Directory 755
Create a 0 byte file with 477 permission?
30
>>> touch csv | chmod 477 csv
If file content is space separated, then how to show only last field of the file?
31
>>>> awk '{ print $NF }' abc
Print all input lines from filename that have more than 4 fields.
32
>>> awk 'NF > 4' abc
Print the total number of lines in the filename to the screen.
34 >>> i) awk '{print NR, $0}' India
ii) cat -n India
Replace 4th occurrence of any pattern with given new pattern?
35
>>> sed '4s/Mumbai/Bombay/' India
How to replace the word from the 04th to 07th line only. (Raj should be there in 4th to 7th word then this will replace )
36
>>> sed '4,7 s/Raj/Rajuu/g' India
How to replace all the occurrences of any word with given word in file
37
>>>> sed 's/Bambai/Mumbai/g' abc
How to print from 03rd to 10th line?
38
>>>> sed -n '3,10p' India
Write a command to print the lines that do not contain the word "Mangesh"
39
>>>> grep -v Mangesh India
What is the difference between ‘comm’ and ‘diff’ commands?
40 i) The comm command compares two files byte by byte. This will show uniq content & common attributes.
ii) The diff command compares two files line by line. This will show different attributes.
How to open the file from 6th line?
41
>>> tail -n +6 India
How to search any ERROR string in VI editor and navigate it? (upward & downward)
i) Open the file in the VI editor
ii) Press the / key to enter search mode in VI.
42
iii) Type the string you want to search for, in this case, "ERROR." And hit enter
iv) To see the next occurrence of the search string, press “n”
v) To navigate to the previous occurrence of the search string, press “N”
How to monitor continue updating logs
43
>>>> tail -f /var/log/syslog
How to copy and delete any line in VI?
44 >>>> yy to copy & dd to delete the line
p to paste the line & ddp to cut patste the line
How to go into Insert mode from Command mode?
45
>>>> By press the " i " button
How to save the changes and exit from VI?
46
>>>> :wq
How to go to 56th line in VI?
47
>>>> Type " 56G "
How you will find %memory & %CPU utilization?
48
>>>> TOP command (q to exit)
How to replace all occurrences of some specific character?
49
>>>>> sed 's/oldText/newText/g' csv
How to append a file to current file using VI editor?
50
>>>>> :r csv
What is the UNIX command to list files/folders in alphabetical order and sorted with modified time?
51
>>>> ls -lt
What ‘more’ command does?
52 >>>> It displays screenful of text in a file not the whole data in file (It will show one screen containt as per your
screen size )
How to display 57th line of the file?
53 i) cat -n India | head -57 >>>>> This will show first 57 lines.
ii) sed -n '57p' India >>>>> This will show only 57th line. head -57 India | tail -n1
What is the command to find maximum memory taking process on the server?
54
>>>> top -o %MEM
What is the command to find the currently running process in Unix Server? (ps = process statuss)
55
>>>> ps -ef
What is the command to find remaining disk space in the UNIX server?
>>>> df -h
56 Filesystem Size Used Avail Use% Mounted on
/dev/sda1 20G 10G 10G 50% /
/dev/sdb1 50G 25G 25G 50% /home
What is the UNIX command to confirm a remote host is alive or not?
57
>>>> ping SERVER NAME (ping es233ahr)
What is the method to see command line history?
58
>>> history
What is the command to find if the system is 32 bit or 64 bit?
59 >>>> uname -m
(x86_64 : Indicates a 64-bit system.)
What is the purpose of the “echo” command?
60 >>> Echo is a command that outputs the strings that are passed to it as a argument.
used to display text/messages on terminal
Write a command to erase all files in the current directory including all its subdirectories.
61 >>>> i) rm-r
ii) rm -rf
Which command is used for remote login?
62
>>>> ssh username@Ipaddress (ssh [email protected])
Which command determines the IP address and domain name?
63
>>>> nslookup google.com (also we can see DNS information by dig command)
How to check the IpAddress
64 >>>> ifconfig
ip addr
What is the importance of $#
65
>>> " $# " represents the number of arguments passed to a shell script or a function.
How to check first 4 lines in top command >>>
66
>>>> top -n4
Name the command that is used to take the backup?
67
>>> tar cvf Backup.tar (used for archiving and creating backups of files and directories)
How to see most repeated word in a file/ How to check a count of repeated word.
68
>>>> sort India | uniq -c
How to see only duplicate lines (with count of duplicates)
69
>>>> sort India | uniq -cd
How Remove duplicate lines from a file
70
>>>> sort India | uniq (This will show uniq values)
How to see only unique values
71 >>>> sort India | uniq -u (This will exclude the the word which is repeated. Eg. Javed is repeated 2 times then it will
exclude Javed word from file)
Find duplicate files in linux
72
>>>> fdupes -r .
How to check server restart date and time
73 >>>> i) who -b
ii) last -x reboot
How to check from when the server is up and running
>>>>> uptime -p
How to check last shutdown time of server.
75
>>>> last -x shutdown
How to cancel the shutdown
76
>>>> shutdown -c
How to restart the server
77 >>>> i) shutdown -r
ii) reboot
To check the operating system details
78
uname

To check server name


79
uname -n
To check server name
80
hostname
How to check ipaddress of linux system
81
hostname -I
How change from normal user to root user
82
su – root
How to give root power to current user
83
sudo -s
How to fetch 1st & 4th Column
84
awk ‘{print $1,$4}’ India
How to separate the space by comma
85
Awk -F “,” ‘{print $1,$2}’ India
How to print the lines that contain manager
86
awk ‘/Manager/{print}’ India
How to fetch 1st & 10th line with awk command
87
awk ‘NR ==1 || NR==10’ India
How to fetch 57th line with awk command
88 awk ‘NR ==57’ India
sed -n ‘57p’ India
How to fetch 1st line from file
89
head -n1 India

How to delete a header from a file.


90
sed -i '1d' India
How to delete all data except first line
91
sed -i ‘2,$d’ India
How to check failed login attempts
92 lastb | less
How to check if process/application is running or not
93 ps -ef
How to stop/terminate the running process.
94 ps -ef
kill -9 PID
Delete all the files that are modified more than 40 days.
95 find . -type f -mtime +40 -exec rm {} \;
Delete all directories along with files modified more than 40 days.
96 find . -type d -mtime +40 -exec rm -r {} \;
Command to delete a header from a file.
97 sed -i '1d' India
Command to list all the files which are more than 50MB.
98 find . -type f -size +50M
Command to list all the zombie process. ( List of all processes (ps aux) and then pipes the output to grep, which filters the
99 lines containing 'Z', indicating zombie processes.)
ps aux | grep 'Z'
Command to print 20th line without awk & sed
100 head -n20 India | tail -n1
How to see files which are modified 6 months before.
101 find . -type f -mtime +180
How to get the last field of a file.
102 awk '{print $NF}' filename
I have executed a script and left the desk. When cameback how will i check the running process.
103 ps aux | grep abc.log
top

104 Which ITIL tool you are using (Information Technology Infrastructure Library.)
Control-M

105 What is ITRS (IT Real-time Solutions)


Geneos alert notifications are generated by ITRS.

What is ITSM (Information Technology Service Management)


106 ITSM involves various processes such as incident management, problem management, change management,
configuration management.
Service Now, BMC Remedy

107 What is AIX (Advanced Interactive eXecutive)


AIX is a UNIX-based operating system
How to search a file on the server
108 find . -name India
To see 1st line in a file
109 head -n1 India

110 To delete all data except 1st line


sed -i '2,$d' India (It deletes lines from the second line. 2,$ define line 2 to the end of the file)
What is Dev environment
111 Where application development tasks such as designing, debugging are takes place. It is used to find & fix the error.

What is Test environment


112 Where testing teams analyse the quality of application where programmers identify & fix the bugs.
What is Production environment
113 Where the software made available for use for the users. It is a stage where the application has been publically
release.
What are the types of servers
Web Servers: These servers handle HTTP requests from clients (web browsers) and deliver web content. eg.
Apache, Nginx.

Application Servers: They are responsible for running and managing applications and their functionalities. It is
uesed to communication between applications and databases. eg. Tomcat, NodeJS, JBoss, and IBM WebSphere.
114
Database Servers: These servers manage databases and provide database services. eg. MySQL (An open-source
RDBMS widely used for web applications), PostgreSQL (Another open-source RDBMS & suitable for enterprise-level
applications).

What is nano editor


115 It is used by beginners or those who might not be familiar with more complex terminal-based editors like Vi.

What is yum command


116 yum is a command-line package management utility. It's used to install, update, remove, and manage software
packages on these systems.
What is Incident.
117 An incident reported to an organization's support team, which contains information such as the nature and severity
of the issue, the affected system or service.
What is Change request.
118 A formal proposal for an additon or alteration to any component or any aspect of IT services.
What is Problem tickets.
Incidents with similar patterns occur repeatedly
We need to Implement permanent fixes to address the root cause of the problem. And this might involve software
119
updates, configuration changes, or other corrective actions. Additionally, we can provide temporary workarounds
to minimize the impact of the problem.

What is load balancer.


It equally distributes incoming network traffic (requests) among multiple servers, prevents any single server from
being overwhelmed and improving overall responsiveness. It routes the traffic away from failed or unhealthy
120
servers to healthy servers, ensuring that services remain available even if some servers fail.

What is WebSphere
121 WebSphere is a application server. It provides a platform for deploying and managing enterprise applications,
supporting various programming languages

122 What is Apache HTTP Server (Apache):


Its an open-source web server used for hosting websites.

123 What is JBoss


JBoss refers to a family of open-source application server products developed by Red Hat
What is Redhat
124 RHEL serve as an operating system for servers. It Provides a stable and secure platform for running a wide range of
applications.
What is VM
125 VM is a software-based replica of a physical computer which allows multiple OS to run on a single physical machine
known as the host.
KIBANA
Kibana is used to monitoring various metrics and logs, setting up alerts based on predefined conditions, and
126 visualizing the health and performance of systems. It helps to identify patterns, troubleshoot issues, and monitor
system health.

Which ETL tool you are using (ETL - Extract, Transform, Load)
127 Informatica facilitates the ETL process by extracting data from multiple sources, & transform it according to
business rules and requirements, and load it into target systems, such as data warehouses, databases.
AUTOSYS
Autosys is a job scheduling and automation tool which is used to manage and schedule complex workflows
128 including batch processes, scripts.
Eg. Control-M
Weekend support
129 If the alerts get triggered then we support on call to take care of it

Weekend Activity
On weekend we do activities like server restart and application restart & memory management task. If there is any
changes we take all details from L3 team like scripts and server name and time of the activity and team name and
130 we prepare a runbook and we share it with L1 team
We have a CAB call on which mgmt decide the task for weekend activity. there are fix weekends where we do server
restart or if any changes is there then we raise RFC (Request For Change) for the same.

Middleware
131 Middleware allows applications to communicate with each other, even if they are running on different platforms or
written in different programming languages.

Zabbix tool (Network Monitoring tool)


Zabbix monitors the status and performance of servers & applications in real-time such as CPU usage, memory
132 utilization, disk space, network activity. Users can set up threshold-based triggers to receive alerts when threshold
is crossed.
Notifications can be delivered through emails, teams, also in incident management systems.
Eg. Dynatrace, Splunk

Splunk (Network Monitoring tool)


133 Splunk continuously collect data from various sources, including servers, applications, databases.
Data sources may include performance metrics (CPU usage, memory usage, disk space, network latency), log files,
event logs, and more. Users can set up threshold-based triggers to receive alerts when threshold is crossed.
Eg. Dynatrace, Splunk
How do you send a web service request from Linux?
134 curl <URL> >>>> is a powerful command-line tool for making HTTP requests
wget <URL> >>>> is a command-line tool for downloading files from the web

135 How do you check how much memory and CPU your Java process is consuming?
ps -ef | grep 'java'

How do you start and stop Tomcat in Linux?

136 cd /home/jk/tomcat/bin
If you do not have permissions to run script, then set permission with below command
chmod +x start.sh
./start.sh --> to start the server
./stop.sh --> to stop the server

137 How to find all the files that contain IP address.


grep -r '\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}' /path/to/search

138 In a filesystem fetch top 10 largest files in the current directory (under a specific folder)
ls -lS | head -n 10

139 To find the top 10 largest files in a given filesystem


find /mnt/c -type f -exec du -h {} + | sort -rh | head -n 10
To see top 10 large size file in unix
140 find . -type f -exec du -h {} + | sort -rh | head -n 10
How to sum total size of a files in a directory. (It will show the total disk usage)
141 du -c /path/to/directory/* | grep 'total$'
How to remove blank spaces & replaces it with a single space (The syntax \{2,\} specifies that you are looking for two or
more occurrences)
sed 's/ \{2,\}/ /g' India

142
For deleting 3rd column in a file
cat India | cut -d ' ' --complement -f3

143

How to remove special characters from file in unix. (@#$%^&*)


sed -i 's/[^[:alnum:]]//g' India

144

145 How to remove duplicate lines from the file.


sort India | uniq
Print all fruits and their respective count in entire file. (Apple Orange, Apple Guava) 2 Apples will be the result.
sed 's/ /\n/g' Fruits | sort | uniq -c |sort -rk1

146

147 Find last 10 transactions in a growing file.


tail -f India

148 Find latest 10 files in the directory where a script creates 10 files every millisecond.
ls -lrt | tail -n10
Print last word in each line. (Apple Orange, Apple Guava) Orange & Guava will be the result.
awk '{print $NF}' India

149

How to replace apple with Seb without other associated words getting replaced. (Apple Orange, Apple Guava) Apples will
be the replced.
sed -i 's/\bApple\b/Seb/gI' India

150

File is taking a lot of time today we need to kill the processes using it.
Fuser India
150 kill -9 PID
How to find .log files that are 1GB in size and not accessed in last 30 days and I want to delete it.
151 find /path/to/search -type f -name "*.log" -size +1G -atime +30 -exec rm {} \;
How to find heap memory usages in Linux -->>> Heap memory is used for dynamic memory allocation at runtime. To find
heap memory usage in we can use top & ps aux command
top
152 ps aux | grep <process_name>
To print the string which occurs more than 2 times in line 6

sed -n '6p' your_file.txt | tr -s ' ' '\n' | sort | uniq -c | awk '$1 > 2 {print $2}'
(sed -n '6p' your_file.txt: This extracts the content of line 6 from your file. tr -s ' ' '\n': This replaces spaces with newline
characters, effectively splitting the line into individual words. awk '$1 > 2 {print $2}': This prints the words that occur more
153 than 2 times.)
If I want to search for a string in all the files and if string found all those files should be moved to a directory

find . -type f -exec grep -q "Goa" {} \; -print | xargs mv -t test


(-exec grep -q "Goa" {} \;: Executes grep to search for the string "Goa" in each file. The -q option makes grep quiet, -print:
Prints the path of files that match the search criteria. xargs mv -t test: Takes the list of matching file paths from the previous
154 step and moves them to the "test" directory).
How to sum total size of a files in a directory.

du -sh /home/coderpad/test
du: Stands for disk usage.
-s: Summarize the total size.
155 -h: Human-readable format
How to see .txt files in directory
156 find /path/to/your/directory -type f -name "*.txt"
What is inode

Inode is index node, it served as uniq identifier used to store metadata about a file or directory. (metadata includes
information such as the file's permissions, owner, group, size, timestamps)

How to give access to single user of a file

setfacl -m u:John:rwx /home/coderpad/India


(This command used to modify the Access Control List (ACL) for a file or directory to grant read, write, and execute
157 permissions to a user named "John.")
setfacl: Command to set file access control lists.
-m: Modify the ACL of the specified file or directory.
u:John:rwx: Grants read (r), write (w), and execute (x) permissions to the user "John."
From a file call abc.txt , different exceptions , how to find only fetch all the different exception logs
158 grep "Exception" abc.txt | sort | uniq
What is the difference between NF and $NF

Andhra Pradesh Arunachal Pradesh


awk '{print NF}' f1
NF will print the total number of fields (Answer is 4 ).

Andhra Pradesh Arunachal Pradesh


awk '{print $NF}' f1
159 Ans : Pradesh
Print Second column and Last column in each line

awk '{ print $2, $NF }' your_file.txt


$2: Represents the value of the second column (field) in each line.
160 $NF: Represents the value of the last column (field) in each line.
Unix commands on search, vi editor search

There are various commands and techniques for searching the text (grep, find, sed, awk)
161 grep "pattern" India
find /path/ -name " India "
sed -n '/pattern/p' India
awk '/pattern/' India
What is use of shred command

162 To permanently delete a file which is unable to recover.


shred -u India
shred --remove India

163 What is nohup


nohup is a command to run a process in the background even when a user logs off from the system.
What is daemon
164 Daemon is a background job or process responsible for a certain task.
Eg. Httpd, sshd
commonly used network commands

ping: This is used for checking network connectivity.


165 hostname: This gives the IP address and domain name
nslookup: This performs a DNS query
traceroute: This is used to see number of hops and response time required to reach the host.
netstat: This provides information about system and ports, routing tables, interface statistics, etc.
What is the difference between ps -ef and ps -aux

166 ps -ef command displays a snapshot of the currently running processes in a full listing format
ps -aux command also displays information about currently running processes but with slightly different options
and formatting.

167 Delete the files older than 30 days


find /path/ -type f -mtime +30 -exec rm {}\;

168 Delete all the .xlsx files older than 30 days


find /path/ -type f -name “*.xlsx” -mtime +30 -exec rm{}\;

169 How to print the files accessed within an hour.


find /path/ -type f -amin -60

170 How to find files which are modified before 6 month


find /path/ -type f -mtime +180
Search OMC in Amdocs directory and its subdirectories. If any files are found with this string, moved to the /Broadband
171 directory.
find /Amdocs -type f -exec grep -q 'OMC' {} \; -exec mv {} /Broadband/ \;
There is a file which is having comma separator , please replace all commas with space
172 sed 's/,/ /g' your_file.txt

Show all lines except the lines which starts with # in the file
173 cat India | grep -v ^#
grep -v ^# India

174

How to remove files older than 7 days by creating a cronjob to run every night.
0 2 * * * find /var/log/India -type f -mtime +7 -exec rm -rf {} \;

175

How to view the users login & logout details ?

last user aosbl


176

How can we give a normal user all the root level privileges

#Add the User to the sudo Group


aosbl -aG sudo aosbl

#Edit the sudoers file in vi editor


visudo
177

How to check if the package is installed

#It is used to list all packages installed on a Red Hat-based system (such as CentOS, Fedora, or RHEL).
178
rpm -qa
# This will help you find packages that contain "bind" in their names.
rpm -qa | grep bind
179 How to check system load without top command.
uptime

180 How to check the open files by specified user


lsof -u aosbl

181 How to schedule a server reboot in 15 minutes.


shutdown -r +15

182 How to reboot the server right now.


shutdown -r now
How will you schedule a server reboot at 11 PM
183 shutdown -r 23:00

How to prevent users from deleting other users files in a directory.

#When the sticky bit is set on a directory, only the owner of the file/directory, or the root user can delete or
rename.
184

Sending alert email when disk space is full

#!/bin/bash

# Threshold for disk space usage (in percentage)


DISK_THRESHOLD=90

# Get disk space usage


disk_usage=$(df -h --output=pcent / | tail -n 1 | sed 's/[^0-9]//g')
185
# Check disk space
if [ $disk_usage -ge $DISK_THRESHOLD ]; then
echo "Disk space is running low: $disk_usage% used" | mail -s "Disk space alert" [email protected]
fi

df -h --output=pcent /: This command displays disk usage information for the root filesystem (/)
only outputs the percentage used (--output=pcent).
tail -n 1: This command retrieves only the last line of the output
sed 's/[^0-9]//g': This removes any non-numeric characters from the output, leaving only the numeric percentage value.
How to redirect an error of a command into a file.

186

187 Which command to use to get info about ports


netstat -l
How to check open port on linux
netstat putan | grep 22 (In below SS it is showing LISTEN means its open)
188

If you want to transfer the 10GB file remotely. What would be the first thing you will do.
Will to tar & then will do gzin to compress the file. Then we can transfer that file.

189

190 What are the examples of linux distribution


Redhat, CentOS, Ubuntu, Fedora, SUSE, Debian
How to check the status of previously executed command.
$? (0 means successful, other numbers means unsuccessful)
191

What is Swap memory.


192 Swap memory is a reserved space on a computer's hard disk uses as virtual memory. When the RAM is fully utilized, the
operating system moves inactive data from RAM to the swap space.
How to read only 26th to 30th lines.
head -30 India | tail -5

193

If you have .txt , .log , .xml files how will you see only .txt files.
194
ls -lrt *.txt

195 Create 100 files with naming file1, file2, file3… file100.
touch file{1..100)
How to display all the files that starts with c

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210
Sr. SQL Command
No
Query is long running, what steps u will take?
Check if Index is dropped
Check any database parameter is modified
check any scheduled job running at same time
1 Check if user count are increase suddenly to access the database.
Check Resource lockage, if we have received huge data load from upstream
Check session to find which query is taking long time by V$Session & V$SQL

There are two tables EMPLOYEES(Employee_Id,Full_Name), address of employees say ADDRESS(Employee_Id, Location,
State, Country).
What is the query to find count of Employees country wise

2 SELECT Country, Count(*) AS EmpCount


FROM Employees Emp JOIN Address Add
ON Emp.Employee_Id = Add.Employee_Id
GROUP BY Country;

Some records in EMPLOYEES table are deleted,so needed to find count of employees deleted country wise.
SELECT Country, Count(*) AS DeletedEmpCount
FROM Address
3
WHERE Employee_id NOT IN (Select Employee_id FROM Employees)
GROUP BY Country;

What is use of stored procedure


4 This reduces network traffic and enhances performance as the database engine doesn't need to recompile the
query each time it's executed.
What is DBMS (Database Management System).
5 DBMS allows users to create, manage, manipulate and interact with data in databases.
components and functions are DML & DDL & DCL
What is RDBMS (Relational Database Management System)
RDBMS organizes data into tables with rows and columns. It execute data integrity by constraints like unique keys,
6 foreign keys, and rules that maintain data accuracy and consistency & preventing duplicate records.

What is Data
7 Data is raw information that can be collected, stored, and processed. It becomes valuable when it's organized &
structured.
What is Database
8 Database is an organized collection of structured data stored in a computer system. It's designed to efficiently
manage, store, retrieve, and manipulate data.
What is Data Warehouse
9 Data Warehouse is a centralized repository where organizations store large volumes of data collected from various
sources within their operations.
CREATE MATERIALIZED VIEW mv_Employees
AS
10 SELECT Employee_id, Employee_Name, Salary, Hire_Date
FROM Employees;

We need to refresh once we updated anything. (Materialized view store the result of query as a physical table)
11 REFRESH MATERIALIZED VIEW mv_Employees;
Print employee name and his manager name from a table. (This query uses a self-join on the EmployeeTable)
SELECT Emp. Employee_name AS EmpName, Mgr.Employee_name AS Manager
12 FROM Employees Emp JOIN Employees Mgr
ON Emp.Manager_id = Mgr.Employee_id;

How to take avg salary for each employees

SELECT First_Name, Department, Salary, AVG(Salary)


13
OVER () AS average_salary
FROM employees;
How to see 3rd transaction for each user
SELECT *
FROM (SELECT user_id, spend, transaction_date,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY transaction_date) AS transaction_rank
14 FROM transactions) ranked_transactions
WHERE transaction_rank = 3
AND user_id = 'desired_user_id';

How to see 1st line in SQL


SELECT *
FROM (SELECT *
15 FROM Employees
Order By Sr.No ASC)
WHERE ROWNUM = 1;

How to see last line in SQL.


SELECT *
FROM (SELECT *
16 FROM Employees
ORDER BY Sr.No DESC)
WHERE ROWNUM = 1;

How to see 1st & 10th line in SQL


SELECT *
FROM ( SELECT Employee_id, First_Name, ROWNUM AS rnum
17 FROM Employees
WHERE ROWNUM <= 10)
WHERE rnum >= 1;

Change the user's password


18 ALTER USER username
IDENTIFIED BY 'new_password';
Deletion of Duplicate rows using row number() and without using row number()?

With CTE AS
(Select Employee_id, Full_Name, Email,
19 ROW_NUMBER() Over (PARTITION BY Email ORDER BY Employee_id) AS RowNum
From Employees)

Delete From CTE


Where RowNum > 1;
Maximum average of student Marks

Select Roll_Number,
20 (Subject1+Subject2+Subject3)/3 AS Average
From Student_Marks
Order By Average Desc
LIMIT 1 ;
Find employees who are getting more salary than their managers.

SELECT Emp.Full_Name
21
FROM Employees Emp JOIN Employees Mgr
ON Emp .Manager_Id = Mgr.Employee_Id
Where Emp.Salary > Mgr.Salary;
How to print odd rows
Select *
22 From Employees
Where MOD(ROWNUM, 2) = 1;

How to print Even rows

23 Select *
From Employees
Where MOD(ROWNUM, 2) = 0;

24
How to get unique top 10 salaries using single line query

SELECT DISTINCT salary


25 FROM Employees
WHERE salary IS NOT NULL
ORDER BY salary DESC
HAVING COUNT(DISTINCT salary) <= 10;
What is query optimization, how to get query optimized
Query optimization is a critical aspect of database tuning, especially in systems dealing with large amounts of data
26 and complex queries.

I have Emp table and Dept table. Need to see Emp_id and count of department Id

Select Emp.Employee_id, Count(Department_id) As DepartmentCount


27
From Employees Emp JOIN Department Dept
ON Emp.Employee_id = Dept.Employee_id
Group By Emp.Employee_id ;
Need to see 5th highest salary from large dataset (Common Table Expressions. It allows you to define a temporary result
set)

28

What is Cursor
Cursors are typically used in scenarios where you need to perform row-level operations, especially when dealing
29 with stored procedures, triggers. Types of cursors are Implicit Cursor & Explicit Cursor

Stored Procedure
A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again. So if
30 you have an SQL query that you write over and over again, save it as a stored procedure, and then just call it to
execute it
Trigger
Trigger is a database object that is associated with a table and automatically executes a set of SQL statements when
31 a specific event occurs on that table. Triggers are used to enforce business rules, maintain data integrity, types of
triggers are DML triggers, DDL triggers, Logon triggers.
Deletion of Duplicate rows

WITH CTE AS
(SELECT *,
ROW_NUMBER() OVER (PARTITION BY Emp_id, Emp_Name ORDER BY Emp_id) AS rnum
FROM Employees)

DELETE FROM CTE


32
WHERE rnum > 1;

-------------------------------------------------------------------------------------
DELETE FROM Employees
WHERE Emp_id NOT IN
(SELECT MIN(Emp_id)
FROM Employees
GROUP BY Emp_id, Emp_Name);
Display the duplicate records.

SELECT Emp_Name, Address, Salary, Department_id, Count(*)


33
FROM Employees
GROUP BY Emp_Name, Address, Salary, Department_id
HAVING COUNT(*) > 1;
34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

You might also like