Sql queries interview questions

  • 10,479 views
Uploaded on

 

More in: Education , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
10,479
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
549
Comments
0
Likes
4

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. SQL Queries Interview Questions - Oracle Part 1As a database developer, writing SQL queries, PLSQL code is part of daily life. Having a goodknowledge on SQL is really important. Here i am posting some practical exampleson SQL queries.To solve these interview questions on SQL queries you have to create the products, sales tables in youroracle database. The "Create Table", "Insert" statements are provided below.CREATE TABLE PRODUCTS( PRODUCT_ID INTEGER, PRODUCT_NAME VARCHAR2(30));CREATE TABLE SALES( SALE_ID INTEGER, PRODUCT_ID INTEGER, YEAR INTEGER, Quantity INTEGER, PRICE INTEGER);
  • 2. INSERT INTO PRODUCTS VALUES ( 100, Nokia);INSERT INTO PRODUCTS VALUES ( 200, IPhone);INSERT INTO PRODUCTS VALUES ( 300, Samsung);INSERT INTO PRODUCTS VALUES ( 400, LG);INSERT INTO SALES VALUES ( 1, 100, 2010, 25, 5000);INSERT INTO SALES VALUES ( 2, 100, 2011, 16, 5000);INSERT INTO SALES VALUES ( 3, 100, 2012, 8, 5000);INSERT INTO SALES VALUES ( 4, 200, 2010, 10, 9000);INSERT INTO SALES VALUES ( 5, 200, 2011, 15, 9000);INSERT INTO SALES VALUES ( 6, 200, 2012, 20, 9000);INSERT INTO SALES VALUES ( 7, 300, 2010, 20, 7000);INSERT INTO SALES VALUES ( 8, 300, 2011, 18, 7000);INSERT INTO SALES VALUES ( 9, 300, 2012, 20, 7000);COMMIT;
  • 3. The products table contains the below data.SELECT * FROM PRODUCTS;PRODUCT_ID PRODUCT_NAME-----------------------100 Nokia200 IPhone300 SamsungThe sales table contains the following data.SELECT * FROM SALES;SALE_ID PRODUCT_ID YEAR QUANTITY PRICE--------------------------------------1 100 2010 25 50002 100 2011 16 50003 100 2012 8 5000
  • 4. 4 200 2010 10 90005 200 2011 15 90006 200 2012 20 90007 300 2010 20 70008 300 2011 18 70009 300 2012 20 7000Here Quantity is the number of products sold in each year. Price is the sale price of each product.I hope you have created the tables in your oracle database. Now try to solve the belowSQL queries.1. Write a SQL query to find the products which have continuous increase in sales every year?Solution:Here “Iphone” is the only product whose sales are increasing every year.STEP1: First we will get the previous year sales for each product. The SQL query to do this isSELECT P.PRODUCT_NAME, S.YEAR, S.QUANTITY, LEAD(S.QUANTITY,1,0) OVER ( PARTITION BY P.PRODUCT_ID
  • 5. ORDER BY S.YEAR DESC ) QUAN_PREV_YEARFROM PRODUCTS P, SALES SWHERE P.PRODUCT_ID = S.PRODUCT_ID;PRODUCT_NAME YEAR QUANTITY QUAN_PREV_YEAR-----------------------------------------Nokia 2012 8 16Nokia 2011 16 25Nokia 2010 25 0IPhone 2012 20 15IPhone 2011 15 10IPhone 2010 10 0Samsung 2012 20 18
  • 6. Samsung 2011 18 20Samsung 2010 20 0Here the lead analytic function will get the quantity of a product in its previous year.STEP2: We will find the difference between the quantities of a product with its previous year’s quantity.If this difference is greater than or equal to zero for all the rows, then the product is a constantlyincreasing in sales. The final query to get the required result isSELECT PRODUCT_NAMEFROM(SELECT P.PRODUCT_NAME, S.QUANTITY - LEAD(S.QUANTITY,1,0) OVER ( PARTITION BY P.PRODUCT_ID ORDER BY S.YEAR DESC ) QUAN_DIFFFROM PRODUCTS P, SALES SWHERE P.PRODUCT_ID = S.PRODUCT_ID
  • 7. )AGROUP BY PRODUCT_NAMEHAVING MIN(QUAN_DIFF) >= 0;PRODUCT_NAME------------IPhone2. Write a SQL query to find the products which does not have sales at all?Solution:“LG” is the only product which does not have sales at all. This can be achieved in three ways.Method1: Using left outer join.SELECT P.PRODUCT_NAMEFROM PRODUCTS P LEFT OUTER JOIN SALES SON (P.PRODUCT_ID = S.PRODUCT_ID);
  • 8. WHERE S.QUANTITY IS NULLPRODUCT_NAME------------LGMethod2: Using the NOT IN operator.SELECT P.PRODUCT_NAMEFROM PRODUCTS PWHERE P.PRODUCT_ID NOT IN (SELECT DISTINCT PRODUCT_ID FROM SALES);PRODUCT_NAME------------LGMethod3: Using the NOT EXISTS operator.SELECT P.PRODUCT_NAME
  • 9. FROM PRODUCTS PWHERE NOT EXISTS (SELECT 1 FROM SALES S WHERE S.PRODUCT_ID = P.PRODUCT_ID);PRODUCT_NAME------------LG3. Write a SQL query to find the products whose sales decreased in 2012 compared to 2011?Solution:Here Nokia is the only product whose sales decreased in year 2012 when compared withthe sales inthe year 2011. The SQL query to get the required output isSELECT P.PRODUCT_NAMEFROM PRODUCTS P, SALES S_2012, SALES S_2011WHERE P.PRODUCT_ID = S_2012.PRODUCT_IDAND S_2012.YEAR = 2012
  • 10. AND S_2011.YEAR = 2011AND S_2012.PRODUCT_ID = S_2011.PRODUCT_IDAND S_2012.QUANTITY < S_2011.QUANTITY;PRODUCT_NAME------------Nokia4. Write a query to select the top product sold in each year?Solution:Nokia is the top product sold in the year 2010. Similarly, Samsung in 2011 and IPhone, Samsung in2012. The query for this isSELECT PRODUCT_NAME, YEARFROM(SELECT P.PRODUCT_NAME, S.YEAR,
  • 11. RANK() OVER ( PARTITION BY S.YEAR ORDER BY S.QUANTITY DESC ) RNKFROM PRODUCTS P, SALES SWHERE P.PRODUCT_ID = S.PRODUCT_ID)AWHERE RNK = 1;PRODUCT_NAME YEAR--------------------Nokia 2010Samsung 2011IPhone 2012Samsung 2012
  • 12. 5. Write a query to find the total sales of each product.?Solution:This is a simple query. You just need to group by the data on PRODUCT_NAME and then find the sumof sales.SELECT P.PRODUCT_NAME, NVL( SUM( S.QUANTITY*S.PRICE ), 0) TOTAL_SALESFROM PRODUCTS P LEFT OUTER JOIN SALES SON (P.PRODUCT_ID = S.PRODUCT_ID)GROUP BY P.PRODUCT_NAME;PRODUCT_NAME TOTAL_SALES---------------------------LG 0IPhone 405000Samsung 406000
  • 13. Nokia 245000SQL Queries Interview Questions - Oracle Part 2This is continuation to my previous post, SQL Queries Interview Questions - Oracle Part 1, Where ihave used PRODUCTS and SALES tables as an example. Here also i am using the same tables. So,just take a look at the tables by going through that link and it will be easy for you to understandthe questions mentioned here.Solve the below examples by writing SQL queries.1. Write a query to find the products whose quantity sold in a year should be greater than the averagequantity sold across all the years?Solution:This can be solved with the help of correlated query. The SQL query for this isSELECT P.PRODUCT_NAME, S.YEAR, S.QUANTITYFROM PRODUCTS P, SALES SWHERE P.PRODUCT_ID = S.PRODUCT_IDAND S.QUANTITY > (SELECT AVG(QUANTITY) FROM SALES S1 WHERE S1.PRODUCT_ID = S.PRODUCT_ID
  • 14. );PRODUCT_NAME YEAR QUANTITY--------------------------Nokia 2010 25IPhone 2012 20Samsung 2012 20Samsung 2010 202. Write a query to compare the products sales of "IPhone" and "Samsung" in each year? The outputshould look like asYEAR IPHONE_QUANT SAM_QUANT IPHONE_PRICE SAM_PRICE---------------------------------------------------2010 10 20 9000 70002011 15 18 9000 70002012 20 20 9000 7000Solution:By using self-join SQL query we can get the required result. The required SQL query is
  • 15. SELECT S_I.YEAR, S_I.QUANTITY IPHONE_QUANT, S_S.QUANTITY SAM_QUANT, S_I.PRICE IPHONE_PRICE, S_S.PRICE SAM_PRICEFROM PRODUCTS P_I, SALES S_I, PRODUCTS P_S, SALES S_SWHERE P_I.PRODUCT_ID = S_I.PRODUCT_IDAND P_S.PRODUCT_ID = S_S.PRODUCT_IDAND P_I.PRODUCT_NAME = IPhoneAND P_S.PRODUCT_NAME = SamsungAND S_I.YEAR = S_S.YEAR3. Write a query to find the ratios of the sales of a product?Solution:
  • 16. The ratio of a product is calculated as the total sales price in a particular year divide by the totalsales price across all years. Oracle provides RATIO_TO_REPORT analytical function for finding theratios. The SQL query isSELECT P.PRODUCT_NAME, S.YEAR, RATIO_TO_REPORT(S.QUANTITY*S.PRICE) OVER(PARTITION BY P.PRODUCT_NAME ) SALES_RATIOFROM PRODUCTS P, SALES SWHERE (P.PRODUCT_ID = S.PRODUCT_ID);PRODUCT_NAME YEAR RATIO-----------------------------IPhone 2011 0.333333333IPhone 2012 0.444444444IPhone 2010 0.222222222Nokia 2012 0.163265306
  • 17. Nokia 2011 0.326530612Nokia 2010 0.510204082Samsung 2010 0.344827586Samsung 2012 0.344827586Samsung 2011 0.3103448284. In the SALES table quantity of each product is stored in rows for every year. Now write a query totranspose the quantity for each product and display it in columns? The output should look like asPRODUCT_NAME QUAN_2010 QUAN_2011 QUAN_2012------------------------------------------IPhone 10 15 20Samsung 20 18 20Nokia 25 16 8Solution:Oracle 11g provides a pivot function to transpose the row data into column data. The SQL query for thisisSELECT * FROM(SELECT P.PRODUCT_NAME,
  • 18. S.QUANTITY, S.YEARFROM PRODUCTS P, SALES SWHERE (P.PRODUCT_ID = S.PRODUCT_ID))APIVOT ( MAX(QUANTITY) AS QUAN FOR (YEAR) IN (2010,2011,2012));If you are not running oracle 11g database, then use the below query for transposing the row data intocolumn data.SELECT P.PRODUCT_NAME, MAX(DECODE(S.YEAR,2010, S.QUANTITY)) QUAN_2010, MAX(DECODE(S.YEAR,2011, S.QUANTITY)) QUAN_2011, MAX(DECODE(S.YEAR,2012, S.QUANTITY)) QUAN_2012FROM PRODUCTS P, SALES SWHERE (P.PRODUCT_ID = S.PRODUCT_ID)GROUP BY P.PRODUCT_NAME;
  • 19. 5. Write a query to find the number of products sold in each year?Solution:To get this result we have to group by on year and the find the count. The SQL query for this question isSELECT YEAR, COUNT(1) NUM_PRODUCTSFROM SALESGROUP BY YEAR;YEAR NUM_PRODUCTS------------------2010 32011 32012 3SQL Queries Interview Questions - Oracle Part 3Here I am providing Oracle SQL Query Interview Questions. If you find any bugs in the queries, Pleasedo comment. So, that i will rectify them.1. Write a query to generate sequence numbers from 1 to the specified number N?Solution:
  • 20. SELECT LEVEL FROM DUAL CONNECT BY LEVEL<=&N;2. Write a query to display only friday dates from Jan, 2000 to till now?Solution:SELECT C_DATE, TO_CHAR(C_DATE,DY)FROM( SELECT TO_DATE(01-JAN-2000,DD-MON-YYYY)+LEVEL-1 C_DATE FROM DUAL CONNECT BY LEVEL <= (SYSDATE - TO_DATE(01-JAN-2000,DD-MON-YYYY)+1))WHERE TO_CHAR(C_DATE,DY) = FRI;3. Write a query to duplicate each row based on the value in the repeat column? The input table datalooks like as belowProducts, Repeat----------------
  • 21. A, 3B, 5C, 2Now in the output data, the product A should be repeated 3 times, B should be repeated 5 times and Cshould be repeated 2 times. The output will look like as belowProducts, Repeat----------------A, 3A, 3A, 3B, 5B, 5B, 5B, 5B, 5C, 2C, 2
  • 22. Solution:SELECT PRODUCTS, REPEATFROM T, ( SELECT LEVEL L FROM DUAL CONNECT BY LEVEL <= (SELECT MAX(REPEAT) FROM T) )AWHERE T.REPEAT >= A.LORDER BY T.PRODUCTS;4. Write a query to display each letter of the word "SMILE" in a separate row?SMILESolution:
  • 23. SELECT SUBSTR(SMILE,LEVEL,1) AFROM DUALCONNECT BY LEVEL <=LENGTH(SMILE);5. Convert the string "SMILE" to Ascii values? The output should look like as 83,77,73,76,69. Where 83is the ascii value of S and so on.The ASCII function will give ascii value for only one character. If you pass a string to the ascii function, itwill give the ascii value of first letter in the string. Here i am providing two solutions to get the asciivalues of string.Solution1:SELECT SUBSTR(DUMP(SMILE),15)FROM DUAL;Solution2:SELECT WM_CONCAT(A)FROM(SELECT ASCII(SUBSTR(SMILE,LEVEL,1)) AFROM DUALCONNECT BY LEVEL <=LENGTH(SMILE));
  • 24. SQL Queries Interview Questions - Oracle Part 41. Consider the following friends table as the sourceName, Friend_Name-----------------sam, ramsam, vamsivamsi, ramvamsi, jhonram, vijayram, anandHere ram and vamsi are friends of sam; ram and jhon are friends of vamsi and so on. Now write aquery to find friends of friends of sam. For sam; ram,jhon,vijay and anand are friends of friends. Theoutput should look asName, Friend_of_Firend----------------------sam, ramsam, jhonsam, vijaysam, anand
  • 25. Solution:SELECT f1.name, f2.friend_name as friend_of_friendFROM friends f1, friends f2WHERE f1.name = samAND f1.friend_name = f2.name;2. This is an extension to the problem 1. In the output, you can see ram is displayed as friends offriends. This is because, ram is mutual friend of sam and vamsi. Now extend the above query toexclude mutual friends. The outuput should look asName, Friend_of_Friend----------------------sam, jhonsam, vijaysam, anandSolution:SELECT f1.name, f2.friend_name as friend_of_friend
  • 26. FROM friends f1, friends f2WHERE f1.name = samAND f1.friend_name = f2.nameAND NOT EXISTS (SELECT 1 FROM friends f3 WHERE f3.name = f1.name AND f3.friend_name = f2.friend_name);3. Write a query to get the top 5 products based on the quantity sold without using the row_numberanalytical function? The source data looks asProducts, quantity_sold, year-----------------------------A, 200, 2009B, 155, 2009C, 455, 2009D, 620, 2009E, 135, 2009F, 390, 2009
  • 27. G, 999, 2010H, 810, 2010I, 910, 2010J, 109, 2010L, 260, 2010M, 580, 2010Solution:SELECT products, quantity_sold, yearFROM( SELECT products, quantity_sold, year, rownum r from t
  • 28. ORDER BY quantity_sold DESC)AWHERE r <= 5;4. This is an extension to the problem 3. Write a query to produce the same output using row_numberanalytical function?Solution:SELECT products, quantity_sold, yearFROM( SELECT products, quantity_sold, year, row_number() OVER( ORDER BY quantity_sold DESC) r from t)A
  • 29. WHERE r <= 5;5. This is an extension to the problem 3. write a query to get the top 5 products in eachyear based onthe quantity sold?Solution:SELECT products, quantity_sold, yearFROM( SELECT products, quantity_sold, year, row_number() OVER( PARTITION BY year ORDER BY quantity_sold DESC) r from t)AWHERE r <= 5;
  • 30. SQL Query Interview Questions - Part 5Write SQL queries for the below interview questions:1. Load the below products table into the target table.CREATE TABLE PRODUCTS( PRODUCT_ID INTEGER, PRODUCT_NAME VARCHAR2(30));INSERT INTO PRODUCTS VALUES ( 100, Nokia);INSERT INTO PRODUCTS VALUES ( 200, IPhone);INSERT INTO PRODUCTS VALUES ( 300, Samsung);INSERT INTO PRODUCTS VALUES ( 400, LG);INSERT INTO PRODUCTS VALUES ( 500, BlackBerry);INSERT INTO PRODUCTS VALUES ( 600, Motorola);COMMIT;
  • 31. SELECT * FROM PRODUCTS;PRODUCT_ID PRODUCT_NAME-----------------------100 Nokia200 IPhone300 Samsung400 LG500 BlackBerry600 MotorolaThe requirements for loading the target table are:• Select only 2 products randomly.• Do not select the products which are already loaded in the target table with in the last 30 days.• Target table should always contain the products loaded in 30 days. It shouldnot contain the products which are loaded prior to 30 days.Solution:First we will create a target table. The target table will have an additional column INSERT_DATE toknow when a product is loaded into the target table. The targettable structure isCREATE TABLE TGT_PRODUCTS
  • 32. ( PRODUCT_ID INTEGER, PRODUCT_NAME VARCHAR2(30), INSERT_DATE DATE);The next step is to pick 5 products randomly and then load into target table. While selecting checkwhether the products are there in theINSERT INTO TGT_PRODUCTSSELECT PRODUCT_ID, PRODUCT_NAME, SYSDATE INSERT_DATEFROM(SELECT PRODUCT_ID, PRODUCT_NAMEFROM PRODUCTS SWHERE NOT EXISTS (
  • 33. SELECT 1 FROM TGT_PRODUCTS T WHERE T.PRODUCT_ID = S.PRODUCT_ID )ORDER BY DBMS_RANDOM.VALUE --Random number generator in oracle.)AWHERE ROWNUM <= 2;The last step is to delete the products from the table which are loaded 30 days back.DELETE FROM TGT_PRODUCTSWHERE INSERT_DATE < SYSDATE - 30;2. Load the below CONTENTS table into the target table.CREATE TABLE CONTENTS( CONTENT_ID INTEGER, CONTENT_TYPE VARCHAR2(30));
  • 34. INSERT INTO CONTENTS VALUES (1,MOVIE);INSERT INTO CONTENTS VALUES (2,MOVIE);INSERT INTO CONTENTS VALUES (3,AUDIO);INSERT INTO CONTENTS VALUES (4,AUDIO);INSERT INTO CONTENTS VALUES (5,MAGAZINE);INSERT INTO CONTENTS VALUES (6,MAGAZINE);COMMIT;SELECT * FROM CONTENTS;CONTENT_ID CONTENT_TYPE-----------------------1 MOVIE2 MOVIE3 AUDIO
  • 35. 4 AUDIO5 MAGAZINE6 MAGAZINEThe requirements to load the target table are:• Load only one content type at a time into the target table.• The target table should always contain only one contain type.• The loading of content types should follow round-robin style. First MOVIE, second AUDIO, Third MAGAZINE and again fourth Movie.Solution:First we will create a lookup table where we mention the priorities for the content types. Thelookup table “Create Statement” and data is shown below.CREATE TABLE CONTENTS_LKP( CONTENT_TYPE VARCHAR2(30), PRIORITY INTEGER, LOAD_FLAG INTEGER);INSERT INTO CONTENTS_LKP VALUES(MOVIE,1,1);
  • 36. INSERT INTO CONTENTS_LKP VALUES(AUDIO,2,0);INSERT INTO CONTENTS_LKP VALUES(MAGAZINE,3,0);COMMIT;SELECT * FROM CONTENTS_LKP;CONTENT_TYPE PRIORITY LOAD_FLAG---------------------------------MOVIE 1 1AUDIO 2 0MAGAZINE 3 0Here if LOAD_FLAG is 1, then it indicates which content type needs to be loaded into the target table.Only one content type will have LOAD_FLAG as 1. The other content types will have LOAD_FLAG as0. The target table structure is same as the source tablestructure.The second step is to truncate the target table before loading the dataTRUNCATE TABLE TGT_CONTENTS;The third step is to choose the appropriate content type from the lookup table to load the source datainto the target table.INSERT INTO TGT_CONTENTS
  • 37. SELECT CONTENT_ID, CONTENT_TYPEFROM CONTENTSWHERE CONTENT_TYPE = (SELECT CONTENT_TYPE FROM CONTENTS_LKP WHERELOAD_FLAG=1);The last step is to update the LOAD_FLAG of the Lookup table.UPDATE CONTENTS_LKPSET LOAD_FLAG = 0WHERE LOAD_FLAG = 1;UPDATE CONTENTS_LKPSET LOAD_FLAG = 1WHERE PRIORITY = (SELECT DECODE( PRIORITY,(SELECT MAX(PRIORITY) FROM CONTENTS_LKP) ,1 , PRIORITY+1)FROM CONTENTS_LKPWHERE CONTENT_TYPE = (SELECT DISTINCT CONTENT_TYPE FROM TGT_CONTENTS));
  • 38. Grep Command in Unix and Linux ExamplesGrep is the frequently used command in Unix (or Linux). Most of us use grep just for finding the wordsin a file. The power of grep comes with using its options and regularexpressions. You can analyze largesets of log files with the help of grep command.Grep stands for Global search for Regular Expressions and Print.The basic syntax of grep command isgrep [options] pattern [list of files]Let see some practical examples on grep command.1. Running the last executed grep commandThis saves a lot of time if you are executing the same command again and again.!grepThis displays the last executed grep command and also prints the result set of the command on theterminal.2. Search for a string in a fileThis is the basic usage of grep command. It searches for the given string in the specified file.grep "Error" logfile.txtThis searches for the string "Error" in the log file and prints all the lines that has the word "Error".3. Searching for a string in multiple files.grep "string" file1 file2grep "string" file_patternThis is also the basic usage of the grep command. You can manually specify the list of files you want tosearch or you can specify a file pattern (use regular expressions) tosearch for.4. Case insensitive search
  • 39. The -i option enables to search for a string case insensitively in the give file. It matches the words like"UNIX", "Unix", "unix".grep -i "UNix" file.txt5. Specifying the search string as a regular expression pattern.grep "^[0-9].*" file.txtThis will search for the lines which starts with a number. Regular expressions is huge topic and I am notcovering it here. This example is just for providing the usage of regularexpressions.6. Checking for the whole words in a file.By default, grep matches the given string/pattern even if it found as a substring in a file. The -w optionto grep makes it match only the whole words.grep -w "world" file.txt7. Displaying the lines before the match.Some times, if you are searching for an error in a log file; it is always good to know the lines around theerror lines to know the cause of the error.grep -B 2 "Error" file.txtThis will prints the matched lines along with the two lines before the matched lines.8. Displaying the lines after the match.grep -A 3 "Error" file.txtThis will display the matched lines along with the three lines after the matched lines.9. Displaying the lines around the matchgrep -C 5 "Error" file.txtThis will display the matched lines and also five lines before and after the matched lines.10. Searching for a sting in all files recursively
  • 40. You can search for a string in all the files under the current directory and sub-directories with the help -roption.grep -r "string" *11. Inverting the pattern matchYou can display the lines that are not matched with the specified search sting patternusing the -v option.grep -v "string" file.txt12. Displaying the non-empty linesYou can remove the blank lines using the grep command.grep -v "^$" file.txt13. Displaying the count of number of matches.We can find the number of lines that matches the given string/patterngrep -c "sting" file.txt14. Display the file names that matches the pattern.We can just display the files that contains the given string/pattern.grep -l "string" file.txt15. Display the file names that do not contain the pattern.We can display the files which do not contain the matched string/pattern.grep -l "string" file.txt16. Displaying only the matched pattern.
  • 41. By default, grep displays the entire line which has the matched string. We can make the grep to displayonly the matched string by using the -o option.grep -o "string" file.txt17. Displaying the line numbers.We can make the grep command to display the position of the line which contains the matched string ina file using the -n optiongrep -n "string" file.txt18. Displaying the position of the matched string in the lineThe -b option allows the grep command to display the character position of the matched string in a file.grep -o -b "string" file.txt19. Matching the lines that start with a stringThe ^ regular expression pattern specifies the start of a line. This can be used in grep to match the lineswhich start with the given string or pattern.grep "^start" file.txt20. Matching the lines that end with a stringThe $ regular expression pattern specifies the end of a line. This can be used in grep to match the lineswhich end with the given string or pattern.grep "end$" file.txtBasic Unix and Linux Commands With ExamplesLearning unix operating system is very easy. It is just that you need to understand the unix serverconcepts and familiar with the unix commands. Here I am providing some important unixcommands which will be used in daily work.
  • 42. Unix Commands With Examples:1. Listing filesThe first thing after logging into the unix system, everyone does is listing the files in a directory. The lscommand is used to list the files in a directory.>lsadd.shlogfile.txtprime.plIf you simply execute ls on the command prompt, then it will display the files and directories in thecurrent directory.>ls /usr/local/binYou can pass a directory as an argument to ls command. In this case, the ls command prints all the filesand directories in the specific directory you have passed.2. Displaying the contents of a file.The next thing is to display the contents of a file. The cat command is used to display thecontents in afile.>cat file.txtThis is a sample unix fileLearning about unix server is awesome
  • 43. 3. Displaying first few lines from a file.The head command can be used to print the specified number of lines from the starting of a file. Thebelow head command displays the first five lines of file.>head -5 logfile.dat4. Displaying last few lines from a file.The tail command can be used to print the specified number of lines from the ending of a file. Thebelow tail command displays the last three lines of file.>tail -3 logfile.dat5. Changing the directoriesThe cd command can be used to change from one directory to another directory. You need to specifythe target directory where you want to go.>cd /var/tmpAfter typing this cd command you will be in /var/tmp directory.6. Creating a file.The touch command simply creates an empty file. The below touch command creates a new file in thecurrent directory.touch new_file.txt7. copying the contents of one file into another.The cp command is used to copy the content of source file into the target file. If the target file alreadyhave data, then it will be overwritten.>cp source_file target_file
  • 44. 8. Creating a directory.Directories are a way of organizing your files. The mkdir command is used to create the specifieddirectory.>mkdir backupThis will create the backup directory in the current directory.9. Renaming and moving the files.The mv command is used to rename the files and it also used for moving the files from one directoryinto another directory.Renaming the file.>mv file.txt new_file.txtMoving the file to another directory.>mv new_file.txt tmp/10. Finding the number of lines in a fileThe wc command can be used to find the number of line, words and characters in a file.>wc logfile.txt
  • 45. 21 26 198 logfile.txtTo know about the unix command, it is always good to see the man pages. To see the man pagessimply pass the command as an argument to the man.man lsSQL Queries Interview Questions - Oracle Analytical Functions Part 1Analytic functions compute aggregate values based on a group of rows. They differ from aggregatefunctions in that they return multiple rows for each group. Most of the SQL developers wont useanalytical functions because of its cryptic syntax or uncertainty about its logic of operation. Analyticalfunctions saves lot of time in writing queries and gives better performance when compared to nativeSQL.Before starting with the interview questions, we will see the difference between the aggregate functionsand analytic functions with an example. I have used SALES TABLEas an example to solvethe interview questions. Please create the below sales table in your oracle database.CREATE TABLE SALES( SALE_ID INTEGER, PRODUCT_ID INTEGER, YEAR INTEGER, Quantity INTEGER, PRICE INTEGER);
  • 46. INSERT INTO SALES VALUES ( 1, 100, 2008, 10, 5000);INSERT INTO SALES VALUES ( 2, 100, 2009, 12, 5000);INSERT INTO SALES VALUES ( 3, 100, 2010, 25, 5000);INSERT INTO SALES VALUES ( 4, 100, 2011, 16, 5000);INSERT INTO SALES VALUES ( 5, 100, 2012, 8, 5000);INSERT INTO SALES VALUES ( 6, 200, 2010, 10, 9000);INSERT INTO SALES VALUES ( 7, 200, 2011, 15, 9000);INSERT INTO SALES VALUES ( 8, 200, 2012, 20, 9000);INSERT INTO SALES VALUES ( 9, 200, 2008, 13, 9000);INSERT INTO SALES VALUES ( 10,200, 2009, 14, 9000);INSERT INTO SALES VALUES ( 11, 300, 2010, 20, 7000);INSERT INTO SALES VALUES ( 12, 300, 2011, 18, 7000);INSERT INTO SALES VALUES ( 13, 300, 2012, 20, 7000);
  • 47. INSERT INTO SALES VALUES ( 14, 300, 2008, 17, 7000);INSERT INTO SALES VALUES ( 15, 300, 2009, 19, 7000);COMMIT;SELECT * FROM SALES;SALE_ID PRODUCT_ID YEAR QUANTITY PRICE--------------------------------------1 100 2008 10 50002 100 2009 12 50003 100 2010 25 50004 100 2011 16 50005 100 2012 8 50006 200 2010 10 90007 200 2011 15 90008 200 2012 20 9000
  • 48. 9 200 2008 13 900010 200 2009 14 900011 300 2010 20 700012 300 2011 18 700013 300 2012 20 700014 300 2008 17 700015 300 2009 19 7000Difference Between Aggregate and Analytic Functions:Q. Write a query to find the number of products sold in each year?The SQL query Using Aggregate functions isSELECT Year, COUNT(1) CNTFROM SALESGROUP BY YEAR;
  • 49. YEAR CNT---------2009 32010 32011 32008 32012 3The SQL query Using Aanalytic functions isSELECT SALE_ID, PRODUCT_ID, Year, QUANTITY, PRICE, COUNT(1) OVER (PARTITION BY YEAR) CNTFROM SALES;
  • 50. SALE_ID PRODUCT_ID YEAR QUANTITY PRICE CNT------------------------------------------9 200 2008 13 9000 31 100 2008 10 5000 314 300 2008 17 7000 315 300 2009 19 7000 32 100 2009 12 5000 310 200 2009 14 9000 311 300 2010 20 7000 36 200 2010 10 9000 33 100 2010 25 5000 312 300 2011 18 7000 34 100 2011 16 5000 37 200 2011 15 9000 313 300 2012 20 7000 35 100 2012 8 5000 3
  • 51. 8 200 2012 20 9000 3From the ouputs, you can observe that the aggregate functions return only one row per group whereasanalytic functions keeps all the rows in the gorup. Using the aggregate functions, the select clausecontains only the columns specified in group by clause and aggregate functions whereas in analyticfunctions you can specify all the columns in thetable.The PARTITION BY clause is similar to GROUP By clause, it specifies the window of rows that theanalytic funciton should operate on.I hope you got some basic idea about aggregate and analytic functions. Now lets start with solvingthe Interview Questions on Oracle Analytic Functions.1. Write a SQL query using the analytic function to find the total sales(QUANTITY) of each product?Solution:SUM analytic function can be used to find the total sales. The SQL query isSELECT PRODUCT_ID, QUANTITY, SUM(QUANTITY) OVER( PARTITION BY PRODUCT_ID ) TOT_SALESFROM SALES;PRODUCT_ID QUANTITY TOT_SALES-----------------------------100 12 71
  • 52. 100 10 71100 25 71100 16 71100 8 71200 15 72200 10 72200 20 72200 14 72200 13 72300 20 94300 18 94300 17 94300 20 94300 19 942. Write a SQL query to find the cumulative sum of sales(QUANTITY) of each product? Here first sortthe QUANTITY in ascendaing order for each product and then accumulate the QUANTITY.Cumulative sum of QUANTITY for a product = QUANTITY of current row + sum of QUANTITIES allprevious rows in that product.
  • 53. Solution:We have to use the option "ROWS UNBOUNDED PRECEDING" in the SUM analytic function to get thecumulative sum. The SQL query to get the ouput isSELECT PRODUCT_ID, QUANTITY, SUM(QUANTITY) OVER( PARTITION BY PRODUCT_ID ORDER BY QUANTITY ASC ROWS UNBOUNDED PRECEDING) CUM_SALESFROM SALES;PRODUCT_ID QUANTITY CUM_SALES-----------------------------100 8 8100 10 18100 12 30100 16 46100 25 71
  • 54. 200 10 10200 13 23200 14 37200 15 52200 20 72300 17 17300 18 35300 19 54300 20 74300 20 94The ORDER BY clause is used to sort the data. Here the ROWS UNBOUNDED PRECEDING optionspecifies that the SUM analytic function should operate on the current row and the pervious rowsprocessed.3. Write a SQL query to find the sum of sales of current row and previous 2 rows in a product group?Sort the data on sales and then find the sum.Solution:The sql query for the required ouput isSELECT PRODUCT_ID,
  • 55. QUANTITY, SUM(QUANTITY) OVER( PARTITION BY PRODUCT_ID ORDER BY QUANTITY DESC ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) CALC_SALESFROM SALES;PRODUCT_ID QUANTITY CALC_SALES------------------------------100 25 25100 16 41100 12 53100 10 38100 8 30200 20 20
  • 56. 200 15 35200 14 49200 13 42200 10 37300 20 20300 20 40300 19 59300 18 57300 17 54The ROWS BETWEEN clause specifies the range of rows to consider for calculating the SUM.4. Write a SQL query to find the Median of sales of a product?Solution:The SQL query for calculating the median isSELECT PRODUCT_ID, QUANTITY, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY QUANTITY ASC) OVER (PARTITION BY PRODUCT_ID) MEDIAN
  • 57. FROM SALES;PRODUCT_ID QUANTITY MEDIAN--------------------------100 8 12100 10 12100 12 12100 16 12100 25 12200 10 14200 13 14200 14 14200 15 14200 20 14300 17 19300 18 19
  • 58. 300 19 19300 20 19300 20 195. Write a SQL query to find the minimum sales of a product without using the group by clause.Solution:The SQL query isSELECT PRODUCT_ID, YEAR, QUANTITYFROM(SELECT PRODUCT_ID, YEAR, QUANTITY, ROW_NUMBER() OVER(PARTITION BY PRODUCT_ID ORDER BY QUANTITY ASC) MIN_SALE_RANKFROM SALES
  • 59. ) WHERE MIN_SALE_RANK = 1;PRODUCT_ID YEAR QUANTITY------------------------100 2012 8200 2010 10300 2008 17SQL Interview Questions and Answers1. What is Normalization?Normalization is the process of organizing the columns, tables of a database to minimize theredundancy of data. Normalization involves in dividing large tables into smaller tables and definingrelationships between them. Normalization is used in OLTP systems.2. What are different types of Normalization Levels or Normalization Forms?The different types of Normalization Forms are:• First Normal Form: Duplicate columns from the same table needs to be eliminated. We have to create separate tables for each group of related data and identify each row with a unique column or set of columns (Primary Key)• Second Normal Form: First it should meet the requirement of first normal form. Removes the subsets of data that apply to multiple rows of a table and place them in separate tables. Relationships must be created between the new tables and their predecessors through the use of foreign keys.• Third Normal Form: First it should meet the requirements of second normal form. Remove columns that are not depending upon the primary key.
  • 60. • Fourth Normal Form: There should not be any multi-valued dependencies.Most databases will be in Third Normal Form3. What is De-normalization?De-normalization is the process of optimizing the read performance of a database by adding redundantdata or by grouping data. De-normalization is used in OLAP systems.4. What is a Transaction?A transaction is a logical unit of work performed against a database in which all steps must beperformed or none.5. What are ACID properties?A database transaction must be Atomic, Consistent, Isolation and Durability.• Atomic: Transactions must be atomic. Transactions must fail or succeed as a single unit.• Consistent: The database must always be in consistent state. There should not be any partial transactions• Isolation: The changes made by a user should be visible only to that user until the transaction is committed.• Durability: Once a transaction is committed, it should be permanent and cannot be undone.6. Explain different storage models of OLAP?• MOLAP: The data is stored in multi-dimensional cube. The storage is not in the relational database, but in proprietary formats.• ROLAP: ROLAP relies on manipulating the data stored in the RDBMS for slicing and dicing functionality.• HOLAP: HOLAP combines the advantages of both MOLAP and ROLAP. For summary type information, HOLAP leverages on cube technology for faster performance. For detail information, HOLAP can drill through the cube.7. Explain one-to-one relationship with an example?One to one relationship is a simple reference between two tables. Consider Customer and Addresstables as an example. A customer can have only one address and an address references only onecustomer.
  • 61. 8. Explain one-to-many relationship with an example?One-to-many relationships can be implemented by splitting the data into two tables with a primary keyand foreign key relationship. Here the row in one table is referenced by one or more rows in the othertable. An example is the Employees and Departments table, where the row in the Departments table isreferenced by one or more rows in the Employees table.9. Explain many-to-many relationship with an example?Many-to-Many relationship is created between two tables by creating a junction table with the key fromboth the tables forming the composite primary key of the junction table.An example is Students, Subjects and Stud_Sub_junc tables. A student can opt for one or moresubjects in a year. Similarly a subject can be opted by one or more students. So a junction table iscreated to implement the many-to-many relationship.10. Write down the general syntax of a select statement?The basic syntax of a select statement isSELECT Columns | *FROM Table_Name[WHERE Search_Condition][GROUP BY Group_By_Expression][HAVING Search_Condition][ORDER BY Order_By_Expression [ASC|DESC]]String aggregating Analytic Functions in Oracle DatabaseThe string aggregate functions concatenate multiple rows into a single row. Consider theproducts table as an example.Table Name: ProductsYear product
  • 62. -------------2010 A2010 B2010 C2010 D2011 X2011 Y2011 ZHere, in the output we will concatenate the products in each year by a comma separator. The desiredoutput is:year product_list------------------2010 A,B,C,D2011 X,Y,ZLISTAGG analytic function in 11gR2:The LISTAGG function can be used to aggregate the strings. You can pass the explicit delimiter to theLISTAGG function.SELECT year,
  • 63. LISTAGG(product, ,) WITHIN GROUP (ORDER BY product) AS product_listFROM productsGROUP BY year;WM_CONCAT function:You cannot pass an explicit delimiter to the WM_CONCAT function. It uses comma as the stringseparator.SELECT year, wm_concat(product) AS product_listFROM productsGROUP BY year;Pivot and Unpivot Operators in Oracle Database 11gPivot:The pviot operator converts row data to column data and also can do aggregates whileconverting. Tosee how pivot operator works, consider the following "sales" table as anyexampleTable Name: Salescustomer_id product price--------------------------------------1 A 101 B 20
  • 64. 2 A 302 B 402 C 503 A 603 B 703 C 80The rows of the "sales" table needs to be converted into columns as shown belowTable Name: sales_revcutomer_id a_product b_product c_product-----------------------------------------1 10 202 30 40 503 60 70 80The query for converting the rows to columns isSELECT *FROM (SELECT customer_id,product,price from sales)pivot ( sum(price) as total_price for (product) IN ( A as a, B as b, C as c) )
  • 65. Pivot can be used to generate the data in xml format. The query for generating the data into xml fomatis shown below.SELECT *FROM (SELECT customer_id,product,price from sales)pivot XML ( sum(price) as total_price for (product) IN ( SELECT distinct product from sales) )If you are not using oracle 11g database, then you can implement the unpivot feature asconverting rowsto columnsUnpivot:Unpivot operator converts the columns into rows.Table Name: sales_revcutomer_id a_product b_product c_product-----------------------------------------1 10 202 30 40 503 60 70 80Table Name: salescustomer_id product price---------------------------1 A 10
  • 66. 1 B 202 A 302 B 402 C 503 A 603 B 703 C 80The query to convert rows into columns isSELECT *FROM sales_revUNPIVOT [EXCLUDE NULLs | INCLUDE NULLs] (price FOR product IN (a_product AS A, b_productAS B, c_product_c AS C));Points to note about the query• The columns price and product in the unpivot clause are required and these names need not to be present in the table.• The unpivoted columns must be specified in the IN clause• By default the query excludes null values.Min and Max values of contiguous rows - Oracle SQL QueryQ) How to find the Minimum and maximum values of continuous sequence numbers in a group of rows.I know the problem is not clear without giving an example. Let say I have the Employees table with thebelow data.
  • 67. Table Name: EmployeesDept_Id Emp_Seq---------------10 110 210 310 510 610 810 910 1120 120 2I want to find the minimum and maximum values of continuous Emp_Seq numbers. The output shouldlook as.Dept_Id Min_Seq Max_Seq-----------------------
  • 68. 10 1 310 5 610 8 910 11 1120 1 2Write an SQL query in oracle to find the minimum and maximum values of continuous Emp_Seq ineach department?STEP1: First we will generate unique sequence numbers in each department using the Row_Numberanalytic function in the Oracle. The SQL query is.SELECT Dept_Id, Emp_Seq, ROW_NUMBER() OVER (PARTITION BY Dept_Id ORDER BY Emp_Seq) rnFROM employees;Dept_Id Emp_Seq rn--------------------10 1 110 2 2
  • 69. 10 3 310 5 410 6 510 8 610 9 710 11 820 1 120 2 2STEP2: Subtract the value of rn from emp_seq to identify the continuous sequences as a group. TheSQL query isSELECT Dept_Id, Emp_Seq, Emp_Seq-ROW_NUMBER() OVER (PARTITION BY Dept_Id ORDER BY Emp_Seq) Dept_SplitFROM employees;Dept_Id Emp_Seq Dept_Split---------------------------
  • 70. 10 1 010 2 010 3 010 5 110 6 110 8 210 9 210 11 320 1 020 2 0STEP3: The combination of the Dept_Id and Dept_Split fields will become the group for continuousrows. Now use group by on these fields and find the min and max values. The final SQL query isSELECT Dept_Id, MIN(Emp_Seq) Min_Seq, MAX(Emp_Seq) Max_SeqFROM(
  • 71. SELECT Dept_Id, Emp_Seq, Emp_Seq-ROW_NUMBER() OVER (PARTITION BY Dept_Id ORDER BY Emp_Seq) Dept_SplitFROM employees;)AGroup BY Dept_Id, Dept_SplitRewrite Sql Query | Sql Performance TuningTuning an SQL query for performance is a big topic. Here I will just cover how to re-write a query andthereby improve the performance. Rewriting an SQL query is one of the ways you can improveperformance. You can rewrite a query in many different ways.To explain this, i have used the sales and products table.SALES(SALE_ID, YEAR, PRODUCT_ID, PRICE);PRODUCTS(PRODUCT_ID, PRODUCT_NAME);Follow the below steps in re writing a query for optimization.1. Avoid Redundant LogicI have seen people writing redundant sub-queries and worrying about their query performance. As anexample, find the total sales in each year and also the sales of product with id 10 in each year.SELECT T.YEAR, T.TOT_SAL, P.PROD_10_SAL(
  • 72. SELECT YEAR, SUM(PRICE) TOT_SAL FROM SALES GROUP BY YEAR)TLEFT OUTER JOIN( SELECT YEAR, SUM(PRICE) PROD_10_SAL FROM SALES WHERE PRODUCT_ID = 10)PON (T.YEAR = P.YEAR);Most SQL developers write the above Sql query without even thinking that it can be solved in a singlequery. The above query is rewritten asSELECT YEAR, SUM(CASE WHEN PRODUCT_ID = 10
  • 73. THEN PRICE ELSE NULL END ) PROD_10_SAL, SUM(SALES) TOT_SALFROM SALESGROUP BY YEAR;Now you can see the difference, just by reading the sales table one time we will able to solvethe problem.First take a look at of your query, identify the redundant logic and then tune it.2. LEFT OUTER JOIN, NOT EXISTS, NOT INSome times you can rewrite a LEFT OUTER JOIN by using NOT EXISTS or NOT IN and vice versa. Asan example, I want to find the products which do not sold in the year 2011.SELECT P.PRODUCT_ID, P.PRODUCT_NAMEFROM PRODUCTS P LEFT OUTER JOIN SALES SON (P.PRODUCT_ID = S.PRODUCT_ID)
  • 74. WHERE S.SALE_ID IS NULL;The same query can be rewritten using NOT EXISTS and NOT IN asSELECT P.PRODUCT_ID, P.PRODUCT_NAMEFROM PRODUCTS PWHERE NOT EXISTS ( SELECT 1 FROM SALES S WHERE S.PRODUCT_ID = P.PRODUCT_ID);SELECT P.PRODUCT_ID, P.PRODUCT_NAMEFROM PRODUCTS PWHERE PRODUCT_ID NOT IN
  • 75. ( SELECT PRODUCT_ID FROM SALES );Analyze the performance of these three queries and use the appropriate one.Note: Be careful while using the NOT IN. If the sub query returns at lease row with NULL data, then themain query wont return a row at all.3. INNER JOIN, EXISTS, INAs similar to LEFT OUTER JOIN, the INNER JOINS can also be implemented with the EXISTS orIN operators. As an example, we will find the sales of products whose product id’s exists in theproducts table.SELECT S.PRODUCT_ID, SUM(PRICE)FROM SALES S JOIN PRODUCTS PON (S.PRODUCT_ID = P.PRODUCT_ID)GROUP BY S.PRODUCT_ID;
  • 76. As we are not selecting any columns from the products table, we can rewrite the same query with thehelp of EXISTS or IN operator.SELECT S.PRODUCT_ID, SUM(PRICE)FROM SALES SWHERE EXISTS ( SELECT 1 FROM PRODUCTS P WHERE P.PRODUCT_ID = S.PRODUCT_ID);GROUP BY S.PRODUCT_ID;SELECT S.PRODUCT_ID, SUM(PRICE)FROM SALES SWHERE PRODUCT_ID IN
  • 77. ( SELECT PRODUCT_ID FROM PRODUCTS P );GROUP BY S.PRODUCT_ID;4. INNER JOIN, CORRELATED QUERYWe will see a simple join between the SALES and PRODUCTS table.SELECT S.SALE_ID, S.PRODUCT_ID, P.PRODUCT_NAMEFROM SALES S JOIN PRODUCTS PON (S.PRODUCT_ID = P.PRODUCT_ID)The above query can be rewritten with correlated query asSELECT S.SALE_ID,
  • 78. S.PRODUCT_ID, (SELECT PRODUCT_NAME FROM PRODUCTS P WHERE P.PRODUCT_ID = S.PRODUCT_ID)FROM SALES SAnalyze these two queries with the explain plan and check which one gives better performance.5. Using With Clause or Temporary Tables.Try to avoid writing complex Sql queries. Split the queries and store the data in temporary tables or usethe Oracle With Clause for temporary storage. This will improve the performance. You can also use thetemporary tables or with clause when you want to reuse the same query more than once. This savesthe time and increases the performance.Tips for increasing the query performance:• Create the required indexes. In the mean time avoid creating too many indexes on a table.• Rewrite the Sql query.• Use the explain plan, auto trace to know about the query execution.• Generate statistics on tables.• Specify the oracle Hints in the query.• Ask the DBA to watch the query and gather stats like CPU usage, number of row read etc.Top Unix Interview Questions - Part 11. How to display the 10th line of a file?head -10 filename | tail -12. How to remove the header from a file?sed -i 1 d filename3. How to remove the footer from a file?sed -i $ d filename
  • 79. 4. Write a command to find the length of a line in a file?The below command can be used to get a line from a file.sed –n <n> p filenameWe will see how to find the length of 10th line in a filesed -n 10 p filename|wc -c5. How to get the nth word of a line in Unix?cut –f<n> -d 6. How to reverse a string in unix?echo "java" | rev7. How to get the last word from a line in Unix file?echo "unix is good" | rev | cut -f1 -d | rev8. How to replace the n-th line in a file with a new line in Unix?sed -i 10 d filename # d stands for deletesed -i 10 i new inserted line filename # i stands for insert9. How to check if the last command was successful in Unix?echo $?10. Write command to list all the links from a directory?ls -lrt | grep "^l"11. How will you find which operating system your system is running on in UNIX?uname -a12. Create a read-only file in your home directory?touch file; chmod 400 file13. How do you see command line history in UNIX?The history command can be used to get the list of commands that we are executed.14. How to display the first 20 lines of a file?By default, the head command displays the first 10 lines from a file. If we change the option of head,then we can display as many lines as we want.head -20 filenameAn alternative solution is using the sed commandsed 21,$ d filenameThe d option here deletes the lines from 21 to the end of the file15. Write a command to print the last line of a file?
  • 80. The tail command can be used to display the last lines from a file.tail -1 filenameAlternative solutions are:sed -n $ p filenameawk END{print $0} filenameTop Unix Interview Questions - Part 21. How do you rename the files in a directory with _new as suffix?ls -lrt|grep ^-| awk {print "mv "$9" "$9".new"} | sh2. Write a command to convert a string from lower case to upper case?echo "apple" | tr [a-z] [A-Z]3. Write a command to convert a string to Initcap.echo apple | awk {print toupper(substr($1,1,1)) tolower(substr($1,2))}4. Write a command to redirect the output of date command to multiple files?The tee command writes the output to multiple files and also displays the output on the terminal.date | tee -a file1 file2 file35. How do you list the hidden files in current directory?ls -a | grep ^.6. List out some of the Hot Keys available in bash shell?• Ctrl+l - Clears the Screen.• Ctrl+r - Does a search in previously given commands in shell.• Ctrl+u - Clears the typing before the hotkey.• Ctrl+a - Places cursor at the beginning of the command at shell.• Ctrl+e - Places cursor at the end of the command at shell.• Ctrl+d - Kills the shell.• Ctrl+z - Places the currently running process into background.7. How do you make an existing file empty?cat /dev/null > filename8. How do you remove the first number on 10th line in file?sed 10 s/[0-9][0-9]*// < filename9. What is the difference between join -v and join -a?join -v : outputs only matched lines between two files.join -a : In addition to the matched lines, this will output unmatched lines also.
  • 81. 10. How do you display from the 5th character to the end of the line from a file?cut -c 5- filenameTop Unix Interview Questions - Part 31. Display all the files in current directory sorted by size?ls -l | grep ^- | awk {print $5,$9} |sort -n|awk {print $2}2. Write a command to search for the file map in the current directory?find -name map -type f3. How to display the first 10 characters from each line of a file?cut -c -10 filename4. Write a command to remove the first number on all lines that start with "@"?sed ,^@, s/[0-9][0-9]*// < filename5. How to print the file names in a directory that has the word "term"?grep -l term *The -l option make the grep command to print only the filename without printing the content of the file.As soon as the grep command finds the pattern in a file, it prints the pattern and stops searching otherlines in the file.6. How to run awk command specified in a file?awk -f filename7. How do you display the calendar for the month march in the year 1985?The cal command can be used to display the current month calendar. You can pass the month and yearas arguments to display the required year, month combination calendar.cal 03 1985This will display the calendar for the March month and year 1985.8. Write a command to find the total number of lines in a file?wc -l filenameOther ways to pring the total number of lines areawk BEGIN {sum=0} {sum=sum+1} END {print sum} filenameawk END{print NR} filename9. How to duplicate empty lines in a file?sed /^$/ p < filename10. Explain iostat, vmstat and netstat?• Iostat: reports on terminal, disk and tape I/O activity.• Vmstat: reports on virtual memory statistics for processes, disk, tape and CPU activity.• Netstat: reports on the contents of network data structures.Top Unix Interview Questions - Part 4cat file1 file2 file3 > file
  • 82. 2. How to display the fields in a text file in reverse order?awk BEGIN {ORS=""} { for(i=NF;i>0;i--) print $i," "; print "n"} filename3. Write a command to find the sum of bytes (size of file) of all files in a directory.ls -l | grep ^-| awk BEGIN {sum=0} {sum = sum + $5} END {print sum}4. Write a command to print the lines which end with the word "end"?grep end$ filenameThe $ symbol specifies the grep command to search for the pattern at the end of the line.5. Write a command to select only those lines containing "july" as a whole word?grep -w july filenameThe -w option makes the grep command to search for exact whole words. If the specified pattern isfound in a string, then it is not considered as a whole word. For example: In the string "mikejulymak",the pattern "july" is found. However "july" is not a whole word in that string.6. How to remove the first 10 lines from a file?sed 1,10 d < filename7. Write a command to duplicate each line in a file?sed p < filename8. How to extract the username from who am i comamnd?who am i | cut -f1 -d 9. Write a command to list the files in /usr directory that start with ch and then display the number oflines in each file?wc -l /usr/ch*Another way isfind /usr -name ch* -type f -exec wc -l {} ;10. How to remove blank lines in a file ?grep -v ‘^$’ filename > new_filenameTop Unix Interview Questions - Part 5ps -aef | grep <user_name>2. Write a command to display all the files recursively with path under current directory?find . -depth -print3. Display zero byte size files in the current directory?find -size 0 -type f
  • 83. 4. Write a command to display the third and fifth character from each line of a file?cut -c 3,5 filename5. Write a command to print the fields from 10th to the end of the line. The fields in the line are delimitedby a comma?cut -d, -f10- filename6. How to replace the word "Gun" with "Pen" in the first 100 lines of a file?sed 1,00 s/Gun/Pen/ < filename7. Write a Unix command to display the lines in a file that do not contain the word "RAM"?grep -v RAM filenameThe -v option tells the grep to print the lines that do not contain the specified pattern.8. How to print the squares of numbers from 1 to 10 using awk commandawk BEGIN { for(i=1;i<=10;i++) {print "square of",i,"is",i*i;}}9. Write a command to display the files in the directory by file size?ls -l | grep ^- |sort -nr -k 510. How to find out the usage of the CPU by the processes?The top utility can be used to display the CPU usage by the processes.Top Unix Interview Questions - Part 6The basename utility deletes any prefix ending in /. The usage is mentioned below:basename /usr/local/bin/fileThis will display only file2. How to display zero byte size files?ls -l | grep ^- | awk /^-/ {if ($5 !=0 ) print $9 }3. How to replace the second occurrence of the word "bat" with "ball" in a file?sed s/bat/ball/2 < filename4. How to remove all the occurrences of the word "jhon" except the first one in a line with in the entirefile?sed s/jhon//2g < filename5. How to replace the word "lite" with "light" from 100th line to last line in a file?sed 100,$ s/lite/light/ < filename6. How to list the files that are accessed 5 days ago in the current directory?find -atime 5 -type f
  • 84. 7. How to list the files that were modified 5 days ago in the current directory?find -mtime 5 -type f8. How to list the files whose status is changed 5 days ago in the current directory?find -ctime 5 -type f9. How to replace the character / with , in a file?sed s///,/ < filenamesed s|/|,| < filename10. Write a command to find the number of files in a directory.ls -l|grep ^-|wc -lTop Unix Interview Questions - Part 7The Yes utility can be used to repeatedly output a line with the specified string or y.yes <your_name> | head -1002. Write a command to display the first 10 characters from each line of a file?cut -c -10 filename3. The fields in each line are delimited by comma. Write a command to display third field from each lineof a file?cut -d, -f2 filename4. Write a command to print the fields from 10 to 20 from each line of a file?cut -d, -f10-20 filename5. Write a command to print the first 5 fields from each line?cut -d, -f-5 filename6. By default the cut command displays the entire line if there is no delimiter in it. Which cut option isused to supress these kind of lines?The -s option is used to supress the lines that do not contain the delimiter.7. Write a command to replace the word "bad" with "good" in file?sed s/bad/good/ < filename8. Write a command to replace the word "bad" with "good" globally in a file?sed s/bad/good/g < filename9. Write a command to replace the word "apple" with "(apple)" in a file?sed s/apple/(&)/ < filename10. Write a command to switch the two consecutive words "apple" and "mango" in a file?
  • 85. sed s/(apple) (mango)/2 1/ < filename11. Write a command to display the characters from 10 to 20 from each line of a file?cut -c 10-20 filename1. Write a command to print the lines that has the the pattern "july" in all the files in a particulardirectory?grep july *This will print all the lines in all files that contain the word “july” along with the file name. If any of thefiles contain words like "JULY" or "July", the above command would not print those lines.2. Write a command to print the lines that has the word "july" in all the files in a directory and alsosuppress the filename in the output.grep -h july *3. Write a command to print the lines that has the word "july" while ignoring the case.grep -i july *The option i make the grep command to treat the pattern as case insensitive.4. When you use a single file as input to the grep command to search for a pattern, it wont print thefilename in the output. Now write a grep command to print the filename in the output without using the -H option.grep pattern filename /dev/nullThe /dev/null or null device is special file that discards the data written to it. So, the /dev/null is alwaysan empty file.Another way to print the filename is using the -H option. The grep command for this isgrep -H pattern filename5. Write a command to print the file names in a directory that does not contain the word "july"?grep -L july *The -L option makes the grep command to print the filenames that do not contain the specified pattern.6. Write a command to print the line numbers along with the line that has the word "july"?grep -n july filenameThe -n option is used to print the line numbers in a file. The line numbers start from 17. Write a command to print the lines that starts with the word "start"?grep ^start filenameThe ^ symbol specifies the grep command to search for the pattern at the start of the line.8. In the text file, some lines are delimited by colon and some are delimited by space. Write a commandto print the third field of each line.awk { if( $0 ~ /:/ ) { FS=":"; } else { FS =" "; } print $3 } filename9. Write a command to print the line number before each line?awk {print NR, $0} filename10. Write a command to print the second and third line of a file without using NR.awk BEGIN {RS="";FS="n"} {print $2,$3} filename
  • 86. 11. How to create an alias for the complex command and remove the alias?The alias utility is used to create the alias for a command. The below command createsalias for ps -aefcommand.alias pg=ps -aefIf you use pg, it will work the same way as ps -aef.To remove the alias simply use the unalias command asunalias pg12. Write a command to display todays date in the format of yyyy-mm-dd?The date command can be used to display todays date with timedate +%Y-%m-%d