<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kislay Keshari on Medium]]></title>
        <description><![CDATA[Stories by Kislay Keshari on Medium]]></description>
        <link>https://medium.com/@kislay_keshari?source=rss-a1c3bc4dc33f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*hOtgJGmEl6I_VZ3I.jpg</url>
            <title>Stories by Kislay Keshari on Medium</title>
            <link>https://medium.com/@kislay_keshari?source=rss-a1c3bc4dc33f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:24:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kislay_keshari/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Top 65 SQL Interview Questions You must Prepare For 2021]]></title>
            <link>https://medium.com/edureka/sql-interview-questions-162f97f37ac2?source=rss-a1c3bc4dc33f------2</link>
            <guid isPermaLink="false">https://medium.com/p/162f97f37ac2</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[structured-query-language]]></category>
            <category><![CDATA[sql-interview-questions]]></category>
            <dc:creator><![CDATA[Kislay Keshari]]></dc:creator>
            <pubDate>Tue, 01 Oct 2019 07:58:27 GMT</pubDate>
            <atom:updated>2022-03-26T08:52:16.643Z</atom:updated>
            <content:encoded><![CDATA[<h3>Top 65 SQL Interview Questions You Must Prepare For 2021</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QIkURZDP-zz7mGZdxYlTcQ.jpeg" /></figure><p>RDBMS is one of the most commonly used databases till date, and therefore <strong><em>SQL skills</em></strong> are indispensable in most of the job roles. In this SQL Interview Questions article, I will introduce you to the most frequently asked questions on SQL (Structured Query Language). This blog is the perfect guide for you to learn all the concepts related to SQL, Oracle, MS SQL Server, and MySQL database.</p><p>Our SQL Interview Questions blog is the <em>one-stop resource</em> from where you can boost your interview preparation. It has a set of <strong>top 65 questions</strong> which an interviewer plans to ask during an interview process. It starts with the basic SQL interview questions and later continues to advanced questions based on your discussions and answers. These SQL Interview questions will help you with different expertise levels to reap the maximum benefit from this article.</p><p>Let’s get started!</p><h3>SQL Interview Questions</h3><h4>Q1. What is the difference between DELETE and TRUNCATE statements?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bA4OTnQngDnAKKjs7Ik95w.png" /></figure><h4>Q2. What are the different subsets of SQL?</h4><ul><li><em>DDL (Data Definition Language) </em>— It allows you to perform various operations on the database such as CREATE, ALTER and DELETE objects.</li><li><em>DML ( Data Manipulation Language)</em> — It allows you to access and manipulate data. It helps you to insert, update, delete and retrieve data from the database.</li><li><em>DCL ( Data Control Language)</em> — It allows you to control access to the database. Example — Grant, Revoke access permissions.</li></ul><h4>Q3. What do you mean by DBMS? What are its different types?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*vV2dmNgeek7Ug_87JuhQ0g.png" /></figure><p>A database is a structured collection of data.</p><p>A <strong>Database Management System</strong> ( <strong>DBMS</strong>) is a software application that interacts with the user, applications and the database itself to capture and analyze data.</p><p>A DBMS allows a user to interact with the database. The data stored in the database can be modified, retrieved and deleted and can be of any type like strings, numbers, images, etc.</p><p>There are two types of DBMS:</p><ul><li><strong><em>Relational Database Management System</em>:</strong> The data is stored in relations (tables). Example — MySQL.</li><li><strong><em>Non-Relational Database Management System</em>: </strong>There is no concept of relations, tuples, and attributes. Example — MongoDB</li></ul><h4>Q4. What do you mean by table and field in SQL?</h4><p>A table refers to a collection of data in an organized manner in the form of rows and columns. A field refers to the number of columns in a table. For example:</p><p><strong><em>Table</em></strong>: StudentInformation<br><strong><em>Field</em></strong>: Stu Id, Stu Name, Stu Marks</p><h4>Q5. What are joins in SQL?</h4><p>A JOIN clause is used to combine rows from two or more tables, based on a related column between them. It is used to merge two tables or retrieve data from there. There are 4 joins in SQL namely:</p><ul><li>Inner Join</li><li>Right Join</li><li>Left Join</li><li>Full Join</li></ul><h4>Q6. What is the difference between CHAR and VARCHAR2 datatype in SQL?</h4><p>Both Char and Varchar2 are used for characters datatype but varchar2 is used for character strings of variable length whereas Char is used for strings of fixed length. For example, char(10) can only store 10 characters and will not be able to store a string of any other length whereas varchar2(10) can store any length i.e 6,8,2 in this variable.</p><h4>Q7. What is the Primary key?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*KdlstccAFcUdDYhpQMun0w.png" /></figure><ul><li>A<strong> </strong>Primary key<strong> </strong>is a column (or collection of columns) or a set of columns that uniquely identifies each row in the table.</li><li>Uniquely identifies a single row in the table</li><li>Null values not allowed</li></ul><p>Example- In the Student table, Stu_ID is the primary key.</p><h4>Q8. What are Constraints?</h4><p>Constraints are used to specify the limit on the data type of the table. It can be specified while creating or altering the table statement. The sample of constraints are:</p><ul><li>NOT NULL</li><li>CHECK</li><li>DEFAULT</li><li>UNIQUE</li><li>PRIMARY KEY</li><li>FOREIGN KEY</li></ul><h4>Q9. What is the difference between SQL and MySQL?</h4><p>SQL is a standard language which stands for Structured Query Language based on the English language whereas MySQL is a database management system. SQL is the core of the relational database which is used for accessing and managing database, MySQL is an RDMS (Relational Database Management System) such as SQL Server, Informix, etc.</p><h4>Q10. What is a Unique key?</h4><ul><li>Uniquely identifies a single row in the table.</li><li>Multiple values allowed per table.</li><li>Null values allowed.</li></ul><h4>Q11. What is a Foreign key?</h4><ul><li>Foreign key maintains referential integrity by enforcing a link between the data in two tables.</li><li>The foreign key in the child table references the primary key in the parent table.</li><li>The foreign key constraint prevents actions that would destroy links between the child and parent tables.</li></ul><h4>Q12. What do you mean by data integrity?</h4><p>Data Integrity defines accuracy as well as the consistency of the data stored in a database. It also defines integrity constraints to enforce business rules on the data when it is entered into an application or a database.</p><h4>Q13. What is the difference between clustered and non clustered index in SQL?</h4><p>The differences between the clustered and non clustered index in SQL are :</p><ol><li>The clustered index is used for easy retrieval of data from the database and its faster whereas reading from a non clustered index is relatively slower.</li><li>Clustered index alters the way records are stored in a database as it sorts out rows by the column which is set to be clustered index whereas in a non clustered index, it does not alter the way it was stored but it creates a separate object within a table which points back to the original table rows after searching.</li><li>One table can only have one clustered index whereas it can have many non clustered index.</li></ol><h4>Q14. Write a SQL query to display the current date?</h4><p>In SQL, there is a built-in function called GetDate() which helps to return the current timestamp/date.</p><h4>Q15. List the different type of joins</h4><p>There are various types of joins which are used to retrieve data between the tables. There are four types of joins, namely:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhHTwm5vzHe-xCD3ijKP0w.png" /></figure><ul><li><strong>Inner join:</strong> Inner Join in MySQL is the most common type of join. It is used to return all the rows from multiple tables where the join condition is satisfied.</li><li><strong>Left Join:</strong> Left Join in MySQL is used to return all the rows from the left table but only the matching rows from the right table where the join condition is fulfilled.</li><li><strong>Right Join:</strong> Right Join in MySQL is used to return all the rows from the right table but only the matching rows from the left table where the join condition is fulfilled.</li><li><strong>Full Join:</strong> Full join returns all the records when there is a match in any of the tables. Therefore, it returns all the rows from the left-hand side table and all the rows from the right-hand side table.</li></ul><h4>Q16. What do you mean by Denormalization?</h4><p>Denormalization refers to a technique which is used to access data from higher to lower forms of a database. It helps the database managers to increase the performance of the entire infrastructure as it introduces redundancy into a table. It adds the redundant data into a table by incorporating database queries that combine data from various tables into a single table.</p><h4>Q17. What are Entities and Relationships?</h4><p><strong>Entities</strong>: A person, place, or thing in the real world about which data can be stored in a database. Tables store data that represents one type of entity. For example — A bank database has a customer table to store customer information. Customer table stores this information as a set of attributes (columns within the table) for each customer.</p><p><strong>Relationships</strong>: Relation or links between entities that have something to do with each other. For example — The customer name is related to the customer account number and contact information, which might be in the same table. There can also be relationships between separate tables (for example, customer to accounts).</p><h4>Q18. What is an Index?</h4><p>An index refers to a performance tuning method of allowing faster retrieval of records from the table. An index creates an entry for each value and hence it will be faster to retrieve data.</p><h4>Q19. Explain different types of index.</h4><p>There are three types of index namely:</p><p><strong>Unique Index:</strong></p><p>This index does not allow the field to have duplicate values if the column is unique indexed. If a primary key is defined, a unique index can be applied automatically.</p><p><strong>Clustered Index:</strong></p><p>This index reorders the physical order of the table and searches based on the basis of key values. Each table can only have one clustered index.</p><p><strong>Non-Clustered Index:</strong></p><p>Non-Clustered Index does not alter the physical order of the table and maintains a logical order of the data. Each table can have many nonclustered indexes.</p><h4>Q20. What is Normalization and what are the advantages of it?</h4><p>Normalization is the process of organizing data to avoid duplication and redundancy. Some of the advantages are:</p><ul><li>Better Database organization</li><li>More Tables with smaller rows</li><li>Efficient data access</li><li>Greater Flexibility for Queries</li><li>Quickly find the information</li><li>Easier to implement Security</li><li>Allows easy modification</li><li>Reduction of redundant and duplicate data</li><li>More Compact Database</li><li>Ensure Consistent data after modification</li></ul><h4>Q21. What is the difference between DROP and TRUNCATE commands?</h4><p>DROP command removes a table and it cannot be rolled back from the database whereas TRUNCATE command removes all the rows from the table.</p><h4>Q22. Explain different types of Normalization.</h4><p>There are many successive levels of normalization. These are called <strong>normal forms</strong>. Each consecutive normal form depends on the previous one. The first three normal forms are usually adequate.</p><ul><li><strong><em>First Normal Form (1NF)</em> </strong>— No repeating groups within rows</li><li><strong><em>Second Normal Form (2NF)</em></strong> — Every non-key (supporting) column value is dependent on the whole primary key.</li><li><strong><em>Third Normal Form (3NF)</em> </strong>— Dependent solely on the primary key and no other non-key (supporting) column value.</li></ul><h4>Q23. What is ACID property in a database?</h4><p>ACID stands for Atomicity, Consistency, Isolation, Durability. It is used to ensure that the data transactions are processed reliably in a database system.</p><ul><li><strong>Atomicity:</strong> Atomicity refers to the transactions that are completely done or failed where transaction refers to a single logical operation of a data. It means if one part of any transaction fails, the entire transaction fails and the database state is left unchanged.</li><li><strong>Consistency:</strong> Consistency ensures that the data must meet all the validation rules. In simple words, you can say that your transaction never leaves the database without completing its state.</li><li><strong>Isolation:</strong> The main goal of isolation is concurrency control.</li><li><strong>Durability:</strong> Durability means that if a transaction has been committed, it will occur whatever may come in between such as power loss, crash or any sort of error.</li></ul><h4>Q24. What do you mean by “Trigger” in SQL?</h4><p>Trigger in SQL is are a special type of stored procedures that are defined to execute automatically in place or after data modifications. It allows you to execute a batch of code when an insert, update or any other query is executed against a specific table.</p><h4>Q25. What are the different operators available in SQL?</h4><p>There are three operators available in SQL, namely:</p><ol><li>Arithmetic Operators</li><li>Logical Operators</li><li>Comparison Operators</li></ol><h4>Q26. Are NULL values the same as that of zero or a blank space?</h4><p>A NULL value is not at all same as that of zero or a blank space. The NULL value represents a value which is unavailable, unknown, assigned or not applicable whereas zero is a number and blank space is a character.</p><h4>Q27. What is the difference between cross join and natural join?</h4><p>The cross join produces the cross product or Cartesian product of two tables whereas the natural join is based on all the columns having the same name and data types in both the tables.</p><h4>Q28. What is subquery in SQL?</h4><p>A subquery is a query inside another query where a query is defined to retrieve data or information back from the database. In a subquery, the outer query is called as the main query whereas the inner query is called subquery. Subqueries are always executed first and the result of the subquery is passed on to the main query. It can be nested inside a SELECT, UPDATE or any other query. A subquery can also use any comparison operators such as &gt;,&lt; or =.</p><h4>Q29. What are the different types of subquery?</h4><p>There are two types of subquery namely, Correlated and Non-Correlated.</p><ul><li><strong>Correlated subquery</strong>: These are queries which select the data from a table referenced in the outer query. It is not considered as an independent query as it refers to another table and refers the column in a table.</li><li><strong>Non-Correlated subquery</strong>: This query is an independent query where the output of subquery is substituted in the main query.</li></ul><h4>Q30. List the ways to get the count of records in a table?</h4><p>To count the number of records in a table, you can use the below commands:</p><pre>SELECT * FROM table1<br>SELECT COUNT(*) FROM table1<br>SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid &lt; 2</pre><h4>Q31. Write a SQL query to find the names of employees that begin with ‘A’?</h4><p>To display the name of the employees that begin with ‘A’, type in the below command:</p><pre>SELECT * FROM Table_name WHERE EmpName like &#39;A%&#39;</pre><h4>Q32. Write a SQL query to get the third-highest salary of an employee from employee_table?</h4><pre>SELECT TOP 1 salary<br>FROM(<br>SELECT TOP 3 salary<br>FROM employee_table<br>ORDER BY salary DESC) AS emp<br>ORDER BY salary ASC;</pre><h4><strong>Q33. What is the need for group functions in SQL?</strong></h4><p>Group functions work on the set of rows and return one result per group. Some of the commonly used group functions are AVG, COUNT, MAX, MIN, SUM, VARIANCE.</p><h4>Q34. What is a Relationship and what are they?</h4><p>Relation or links are between entities that have something to do with each other. Relationships are defined as the connection between the tables in a database. There are various relationships, namely:</p><ul><li>One to One Relationship.</li><li>One to Many Relationship.</li><li>Many to One Relationship.</li><li>Self-Referencing Relationship.</li></ul><h4>Q35. How can you insert NULL values in a column while inserting the data?</h4><p>NULL values can be inserted in the following ways:</p><ul><li>Implicitly by omitting column from column list.</li><li>Explicitly by specifying NULL keyword in the VALUES clause</li></ul><h4>Q36. What is the main difference between ‘BETWEEN’ and ‘IN’ condition operators?</h4><p>BETWEEN operator is used to display rows based on a range of values in a row whereas the IN condition operator is used to check for values contained in a specific set of values.</p><p><strong>Example of BETWEEN:</strong></p><pre>SELECT * FROM Students where ROLL_NO BETWEEN 10 AND 50;</pre><p><strong>Example of IN:</strong></p><pre>SELECT * FROM students where ROLL_NO IN (8,15,25);</pre><h4><strong>Q37. Why are SQL functions used?</strong></h4><p>SQL functions are used for the following purposes:</p><ul><li>To perform some calculations on the data</li><li>To modify individual data items</li><li>To manipulate the output</li><li>To format dates and numbers</li><li>To convert the data types</li></ul><h4>Q38. What is the need of the MERGE statement?</h4><p>This statement allows conditional update or insertion of data into a table. It performs an UPDATE if a row exists, or an INSERT if the row does not exist.</p><h4>Q39. What do you mean by recursive stored procedure?</h4><p>Recursive stored procedure refers to a stored procedure which calls by itself until it reaches some boundary condition. This recursive function or procedure helps the programmers to use the same set of code n number of times.</p><h4>Q40. What is CLAUSE in SQL?</h4><p>SQL clause helps to limit the result set by providing a condition to the query. A clause helps to filter the rows from the entire set of records.</p><p>For example — WHERE, HAVING clause.</p><h4>Q41. What is the difference between ‘HAVING’ CLAUSE and a ‘WHERE’ CLAUSE?</h4><p>HAVING clause can be used only with SELECT statement. It is usually used in a GROUP BY clause and whenever GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is only used with the GROUP BY function in a query whereas WHERE Clause is applied to each row before they are a part of the GROUP BY function in a query.</p><h4>Q42. List the ways in which Dynamic SQL can be executed?</h4><p>Following are the ways in which dynamic SQL can be executed:</p><ul><li>Write a query with parameters.</li><li>Using EXEC.</li><li>Using sp_executesql.</li></ul><h4>Q43. What are the various levels of constraints?</h4><p>Constraints are the representation of a column to enforce data entity and consistency. There are two levels of a constraint, namely:</p><ul><li>column-level constraint</li><li>table-level constraint</li></ul><h4>Q44. How can you fetch common records from two tables?</h4><p>You can fetch common records from two tables using INTERSECT. For example:</p><pre>Select studentID from student INTERSECT Select StudentID from ExaM</pre><h4>Q45. List some case manipulation functions in SQL?</h4><p>There are three case manipulation functions in SQL, namely:</p><ul><li><strong>LOWER:</strong> This function returns the string in lowercase. It takes a string as an argument and returns it by converting it into lower case. Syntax:</li></ul><pre>LOWER(&#39;string&#39;)</pre><ul><li><strong>UPPER: </strong>This function returns the string in uppercase. It takes a string as an argument and returns it by converting it into uppercase. Syntax:</li></ul><pre>UPPER(&#39;string&#39;</pre><ul><li><strong>INITCAP:</strong> This function returns the string with the first letter in uppercase and the rest of the letters in lowercase. Syntax:</li></ul><pre>INITCAP(‘string’)</pre><h4>Q46. What are the different set operators available in SQL?</h4><p>Some of the available set operators are — Union, Intersect or Minus operators.</p><h4>Q47. What is an ALIAS command?</h4><p>ALIAS name can be given to any table or a column. This alias name can be referred in WHERE clause to identify a particular table or a column.</p><p>For example-</p><pre>Select emp.empID, dept.Result from employee emp, department as dept where emp.empID=dept.empID</pre><p>In the above example, emp refers to alias name for employee table and dept refers to alias name for department table.</p><h4>Q48. What are the aggregate and scalar functions?</h4><p>Aggregate functions are used to evaluate mathematical calculation and return a single value. These calculations are done from the columns in a table. For example- max(),count() are calculated with respect to numeric.</p><p>Scalar functions return a single value based on the input value. For example — UCASE(), NOW() are calculated with respect to the string.</p><h4>Q49. How can you fetch alternate records from a table?</h4><p>You can fetch alternate records i.e both odd and even row numbers. For example- To display even numbers, use the following command:</p><p>Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0</p><p>Now, to display odd numbers:</p><pre>Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1</pre><h4><strong>Q50. Name the operator which is used in the query for pattern matching?</strong></h4><p>LIKE operator is used for pattern matching, and it can be used as -.</p><ol><li>% — It matches zero or more characters.</li></ol><p>For example- select * from students where studentname like ‘a%’</p><p>_ (Underscore) — it matches exactly one character. For example- select * from student where studentname like ‘abc_’</p><h4>Q51. How can you select unique records from a table?</h4><p>You can select unique records from a table by using the DISTINCT keyword.</p><pre>Select DISTINCT studentID from Student</pre><p>Using this command, it will print unique student id from the table Student.</p><h4>Q52. How can you fetch first 5 characters of the string?</h4><p>There are a lot of ways to fetch characters from a string. For example:</p><pre>Select SUBSTRING(StudentName,1,5) as studentname from student</pre><h4>Q53. What is the main difference between SQL and PL/SQL?</h4><p>SQL is a query language that allows you to issue a single query or execute a single insert/update/delete whereas PL/SQL is Oracle’s “Procedural Language” SQL, which allows you to write a full program (loops, variables, etc.) to accomplish multiple operations such as selects/inserts/updates/deletes.</p><h4>Q54. What is a View?</h4><p>A view is a virtual table which consists of a subset of data contained in a table. Since views are not present, it takes less space to store. View can have data of one or more tables combined and it depends on the relationship.</p><h4>Q55. What are Views used for?</h4><p>A view refers to a logical snapshot based on a table or another view. It is used for the following reasons:</p><ul><li>Restricting access to data.</li><li>Making complex queries simple.</li><li>Ensuring data independence.</li><li>Providing different views of the same data.</li></ul><h4>Q56. What is a Stored Procedure?</h4><p>A Stored Procedure is a function which consists of many SQL statements to access the database system. Several SQL statements are consolidated into a stored procedure and execute them whenever and wherever required which saves time and avoid writing code again and again.</p><h4>Q57. List some advantages and disadvantages of Stored Procedure</h4><p><strong>Advantages:</strong></p><p>A Stored Procedure can be used as modular programming which means create once, store and call for several times whenever it is required. This supports faster execution. It also reduces network traffic and provides better security to the data.</p><p><strong>Disadvantages:</strong></p><p>The only disadvantage of Stored Procedure is that it can be executed only in the database and utilizes more memory in the database server.</p><h4>Q58. List all the types of user-defined functions?</h4><p>There are three types of user-defined functions, namely:</p><ul><li>Scalar Functions</li><li>Inline Table-valued functions</li><li>Multi-statement valued functions</li></ul><p>Scalar returns the unit, variant defined the return clause. Other two types of defined functions return table.</p><h4>Q59. What do you mean by Collation?</h4><p>Collation is defined as a set of rules that determine how data can be sorted as well as compared. Character data is sorted using the rules that define the correct character sequence along with options for specifying case-sensitivity, character width, etc.</p><h4>Q60. What are the different types of Collation Sensitivity?</h4><p>Following are the different types of collation sensitivity:</p><ul><li>Case Sensitivity</li><li>Kana Sensitivity</li><li>Width Sensitivity</li><li>Accent Sensitivity</li></ul><h4>Q61. What are Local and Global variables?</h4><p><strong>Local variables:</strong></p><p>These variables can be used or exist only inside the function. These variables are not used or referred by any other function.</p><p><strong>Global variables:</strong></p><p>These variables are the variables which can be accessed throughout the program. Global variables cannot be created whenever that function is called.</p><h4>Q62. What is Auto Increment in SQL?</h4><p>Autoincrement keyword allows the user to create a unique number to get generated whenever a new record is inserted into the table. This keyword is usually required whenever the PRIMARY KEY is used.</p><p>AUTOINCREMENT keyword can be used in Oracle and IDENTITY keyword can be used in SQL SERVER.</p><h4>Q63. What is a Datawarehouse?</h4><p>Datawarehouse refers to a central repository of data where the data is assembled from multiple sources of information. Those data are consolidated, transformed and made available for the mining as well as online processing. Warehouse data also have a subset of data called Data Marts.</p><h4>Q64. What are the different authentication modes in SQL Server? How can it be changed?</h4><p>Windows mode and Mixed Mode — SQL and Windows. You can go to the below steps to change authentication mode in SQL Server:</p><ul><li>Click Start&gt; Programs&gt; Microsoft SQL Server and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group.</li><li>Then select the server from the Tools menu.</li><li>Select SQL Server Configuration Properties, and choose the Security page.</li></ul><h4>Q65. What are STUFF and REPLACE function?</h4><p><strong>STUFF Function</strong>: This function is used to overwrite an existing character or inserts a string into another string. Syntax:</p><pre>STUFF(string_expression,start, length, replacement_characters)</pre><p>where,</p><ul><li><em>string_expression</em>: it is the string that will have characters substitute</li><li><em>start:</em> This refers to the starting position</li><li><em>length</em>: It refers to the number of characters in the string which are substituted.</li><li><em>replacement_string</em>: They are the new characters which are injected in the string.</li></ul><p><strong>REPLACE function</strong>: This function is used to replace the existing characters of all the occurrences. Syntax:</p><pre>REPLACE (string_expression, search_string, replacement_string)</pre><p>Here every search_string in the string_expression will be replaced with the replacement_string.</p><p>So this brings us to the end of the SQL interview questions article. I hope this set of SQL Interview Questions will help you ace your job interview. <strong>All the best for your interview! </strong>If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to <a href="https://www.edureka.co/blog/?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=sql-interview-questions">Edureka’s official site.</a></p><p>Do look out for other articles in this series which will explain the various other aspects of SQL.</p><blockquote><em>1. </em><a href="https://medium.com/edureka/sql-vs-nosql-db-5d9b69ace6ac"><em>Differences Between SQL &amp; NoSQL Databases</em></a></blockquote><blockquote><em>2. </em><a href="https://medium.com/edureka/oracle-interview-and-answers-d1a99534e2d0"><em>Top 50 Oracle Interview Questions</em></a></blockquote><blockquote><em>3. </em><a href="https://medium.com/edureka/sql-for-data-science-a8fe10fe2ef9"><em>SQL For Data Science</em></a></blockquote><p><em>Originally published at </em><a href="https://www.edureka.co/blog/interview-questions/sql-interview-questions"><em>https://www.edureka.co</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=162f97f37ac2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edureka/sql-interview-questions-162f97f37ac2">Top 65 SQL Interview Questions You must Prepare For 2021</a> was originally published in <a href="https://medium.com/edureka">Edureka</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 50 Oracle Interview Questions and Answers]]></title>
            <link>https://medium.com/edureka/oracle-interview-and-answers-d1a99534e2d0?source=rss-a1c3bc4dc33f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1a99534e2d0</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[oracle]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[oracle-database]]></category>
            <dc:creator><![CDATA[Kislay Keshari]]></dc:creator>
            <pubDate>Wed, 18 Sep 2019 14:46:53 GMT</pubDate>
            <atom:updated>2020-04-30T13:53:46.011Z</atom:updated>
            <content:encoded><![CDATA[<h3>Top 50 Oracle Interview Questions You Should Master</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*VOsetdGC5OC6Ym_SCRzfag.png" /><figcaption>Oracle Interview Questions — Edureka</figcaption></figure><p>Knowledge of SQL is a must because the demand for <a href="https://www.edureka.co/blog/sql-for-data-science/"><em>SQL-expertise</em></a> is high and is valued in the market. Oracle is a very popular secured database that is widely used across multinational companies. So, this article on Oracle interview questions will cover the most frequently asked interview questions and help you to brush up your knowledge before the interview.</p><p>If you are a fresher or an experienced, this is the right platform for you which will help you to start your preparation.</p><p>Let’s begin by taking a look at the most frequently asked questions.</p><ul><li>Oracle Basic Interview Questions</li><li>SQL Interview Questions</li><li>PL/SQL Interview Questions</li></ul><p>So, let’s begin!</p><h3>Oracle Basic Interview Questions</h3><p>Q1. How will you differentiate between varchar &amp; varchar2<br>Q2. What are the components of logical database structure in Oracle database?<br>Q3. Describe an Oracle table<br>Q4. Explain the relationship among database, tablespace and data file?<br>Q5. What are the various Oracle database objects?<br>Q6. Explain about the ANALYZE command in Oracle?<br>Q7. What types of joins are used in writing subqueries?<br>Q8. RAW datatype in Oracle<br>Q9. What is the use of Aggregate functions in Oracle?<br>Q10. Explain Temporal data types in Oracle</p><h4><strong>Q1. How will you differentiate between Varchar &amp; Varchar2?</strong></h4><p>Both Varchar &amp; Varchar2 are the Oracle data types which are used to store character strings of variable length. To point out the major differences between these,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXOrPACc7dd-2buNBPt1pw.png" /></figure><h4><strong>Q2. What are the components of logical database structure in Oracle database?</strong></h4><p>The components of the logical database structure in Oracle database are:</p><ul><li><strong>Tablespaces</strong>: A database mainly contains the Logical Storage Unit called <em>tablespaces</em>. This <em>tablespace</em> is a set of related logical structures. To be precise, tablespace groups are related to logical structures together.</li><li><strong>Database schema objects:</strong> A schema is a collection of database objects owned by a specific user. The objects include tables, indexes, views, stored procedures, etc. And in Oracle, the user is the account and the schema is the object. It is also possible in the database platforms to have a schema without a user-specified.</li></ul><h4><strong>Q3. Describe an Oracle table</strong></h4><p>A table is a basic unit of data storage in the Oracle database. A table basically contains all the accessible information of a user in rows and columns.</p><p>To create a new table in the database, use the “CREATE TABLE” statement. First, you have to name that table and define its columns and datatype for each column.</p><p>CREATE TABLE table_name<br>(<br>column1 datatype [ NULL | NOT NULL ],<br>column2 datatype [ NULL | NOT NULL ],<br>…<br>column_n datatype [ NULL | NOT NULL ]<br>);</p><p>Here,</p><ul><li><strong>table_name:</strong> This specifies the name of the table that you want to create.</li><li><strong>column..n: </strong>It specifies the number of columns which you want to add in the table. Here, every column must have a datatype and should either be defined as “NULL” or “NOT NULL”. If in case, the value is left blank, it is treated as “<em>NULL</em>” as default.</li></ul><h4><strong>Q4. Explain the relationship among database, tablespace and data file?</strong></h4><p>An Oracle database possesses one or more logical storage units called <em>tablespaces</em>. Each tablespace in Oracle database consists of one or more files called the datafiles. These tablespaces collectively store the entire data of databases. Talking about the data files, these are the physical structure that confirms with the operating system as to which Oracle program is running.</p><h4><strong>Q5. What are the various Oracle database objects?</strong></h4><p>These are the Oracle Database Objects:</p><ul><li><strong>Tables:</strong> This is a set of elements organized in a vertical and horizontal manner.</li><li><strong>Tablespaces:</strong> It is a logical storage unit in Oracle.</li><li><strong>Views:</strong> Views are a virtual table derived from one or more tables.</li><li><strong>Indexes:</strong> This is a performance tuning method to process the records.</li><li><strong>Synonyms:</strong> It is a name for tables.</li></ul><h4><strong>Q6. Explain about the ANALYZE command in Oracle?</strong></h4><p>This “Analyze” command is used to perform various functions on index, table, or cluster. The following list specifies the usage of ANALYZE command in Oracle:</p><ul><li><em>Analyze</em> command is used to identify migrated and chained rows of the table or a cluster.</li><li>It is used to validate the structure of an object.</li><li>This helps in collecting the statistics about the object used by the user and are then stored on to the data dictionary.</li><li>It also helps in deleting statistics that are used by an object from the data dictionary.</li></ul><h4><strong>Q7. What types of joins are used in writing subqueries?</strong></h4><p>A <em>Join </em>is used to compare and combine, this means literally join and return specific rows of data from two or more tables in a database.</p><p>There are three types of joins in <em>SQL</em> that are used to write the subqueries.</p><ul><li><strong>Self Join</strong>: This is a join in which a table is joined with itself, especially when the table has a foreign key which references its own primary key.</li><li><strong>Outer Join: </strong>An outer join helps to find and returns matching data and some dissimilar data from tables.</li><li><strong>Equi-join: </strong>An equijoin is a join with a join condition containing an <em>equality operator</em>. An equijoin returns only the rows that have equivalent values for the specified columns.</li></ul><h4><strong>Q8. RAW datatype in Oracle</strong></h4><p>The RAW datatype in Oracle is used to store variable-length binary data or byte string values. The maximum size for a raw in a given table in 32767 bytes.</p><p>You might get confused as to when to use RAW, varchar, and varchar2. Let me point out the major differences between them. PL/SQL does not recognize the data type and hence, it cannot have any conversions when RAW data is transferred to different systems. This data type can only be queried or can be inserted in a table.</p><h4><strong>Q9. What is the use of Aggregate functions in Oracle?</strong></h4><p>An aggregate function in Oracle is a function where values of multiple rows or records are joined together to get a single value output. It performs the summary operations on a set of values in order to provide a single value. There are several aggregate functions that you can use in your code to perform calculations.<br>Some common Aggregate functions are:</p><ul><li>Average</li><li>Count</li><li>Sum</li></ul><h4><strong>Q10. Explain Temporal data types in Oracle</strong></h4><p>Oracle mainly provides these following temporal data types:</p><ul><li><strong>Date Data Type:</strong> Different formats of Dates.</li><li><strong>TimeStamp Data Type:</strong> Has different formats of <em>Time Stamp</em>.</li><li><strong>Interval Data Type: </strong>Interval between dates and time.</li></ul><h4><strong>Q11. What is a View?</strong></h4><p>A view is a logical table based on one or more tables or views. A View is also referred to as a user-defined database object that is used to store the results of a SQL query, that can be referenced later in the course of time. Views do not store the data physically but as a virtual table, hence it can be referred to as a logical table. The corresponding tables upon which the views are signified are called <em>Base Tables</em> and this doesn’t contain data.</p><h4><strong>Q12. How to store pictures on to the database?</strong></h4><p>It is possible to store pictures on to the database by using Long Raw Data type. This data type is used to store binary data of length 2GB. Although, the table can have only on Long Raw data type.</p><h4><strong>Q13. Where do you use DECODE and CASE Statements?</strong></h4><p>Both these statements Decode and Case will work similar to the if-then-else statement and also they are the alternatives for each of them. These functions are used in Oracle for data value transformation.</p><p><strong>Example:</strong></p><p><em>Decode function</em></p><p>Select OrderNum,<br>DECODE (Status,’O’, ‘Ordered’,’P’, ‘Packed,’ S’,’ Shipped’, ’A’,’Arrived’)<br>FROM Orders;</p><p><em>Case function</em></p><p>Select OrderNum<br>, Case(When Status=’O’ then ‘Ordered’<br>When Status =’P’ then Packed<br>When Status=’ S’ then ’Shipped’<br>else ’Arrived’) end<br>FROM Orders;</p><p>Both these commands will display Order Numbers with their respective Statuses like this,</p><p>Status O= Ordered<br>Status P= Packed<br>Status S= Shipped<br>Status A= Arrived</p><h4><strong>Q14. What do you mean by <em>Merge</em> in Oracle and how can you merge two tables?</strong></h4><p><em>Merge</em> statement is used to merge the data from two tables subsequently. It selects the data from the source table and then inserts/updates it in the other table based on the condition provided in the query. It is also useful in data warehousing applications.</p><h4><strong>Q15. What is the data type of DUAL table?</strong></h4><p>The Dual table is basically a one-column table that is present in the Oracle database. This table has a single Varchar2(1) column called Dummy which has a value of ‘X’.</p><h3>SQL Interview Questions</h3><h4><strong>Q16. Explain about integrity constraint?</strong></h4><p>An integrity constraint is actually a declaration that is defined as a business rule for a table column. They are used to ensure accuracy and consistency of data in the database. It can also be called as <em>a declarative way</em> to define a business rule for a table’s column. There are a few types, namely:</p><ul><li>Domain Integrity</li><li>Referential Integrity</li><li>Domain Integrity</li></ul><h4><strong>Q17. What is SQL and also describe types of SQL statements?</strong></h4><p>SQL stands for <em>Structured Query Language</em>. SQL is used to communicate with the server in order to access, manipulate and control data. There are 5 different types of SQL statements available. They are:</p><ol><li><em>Select: </em>Data Retrieval</li><li><em>Insert, Update, Delete, Merge</em>: Data Manipulation Language (DML)</li><li><em>Create, Alter, Drop, Rename, Truncate</em>: Data Definition Language (DDL)</li><li><em>Commit, Rollback, Savepoint:</em> Transaction Control Statements</li><li><em>Grant, Revoke</em>: Data Control Language (DCL)</li></ol><h4><strong>Q18. Briefly explain what is Literal? Give an example where it can be used?</strong></h4><p>A <em>Literal</em> is a string that contains a character, a number, or a date that is included in the <em>Select</em> list and which is not a column name or a column alias.</p><p>Also note that Date and character literals must be enclosed within single quotes (‘ ‘), whereas you don’t have to do that for the number literals.</p><p>For example: Select last_name||’is a’||job_id As “emp details” from employee;</p><p>In this case, “is a” is literal.</p><h4><strong>Q19. How to display row numbers with the records?</strong></h4><p>In order to display row numbers along with their records numbers you can do this:</p><p>Select rownum &lt;fieldnames&gt; from table;</p><p>The above query will display the row numbers and the field values from the given table. This query will display row numbers and the field values from the given table.</p><h4><strong>Q20. What is the difference between SQL and iSQL*Plus?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwxwsrI3lXaolUiwvcEDTQ.png" /></figure><h4><strong>Q21. What are SQL functions? Describe in brief different types of SQL functions?</strong></h4><p>SQL Functions are a very powerful feature of SQL. These functions can take arguments but always return some value. There are two distinct types of SQL functions available. They are:</p><ul><li><strong>Single-Row functions:</strong> These functions operate on a single row to give one result per row.</li></ul><p><strong><em>Types of Single-Row functions are:</em></strong></p><ol><li>Character</li><li>Number</li><li>Date</li><li>Conversion</li><li>General</li></ol><ul><li><strong>Multiple-Row functions:</strong> These functions operate on groups of rows to give one result per group of rows.</li></ul><p><strong><em>Types of Multiple-Row functions:</em></strong></p><ol><li>avg</li><li>count</li><li>max</li><li>min</li><li>sum</li><li>stddev</li><li>variance</li></ol><h4><strong>Q22. Describe different types of General Function used in SQL?</strong></h4><p>General functions are of following types:</p><ol><li><strong>NVL:</strong> Converts a null value to an actual value. NVL (exp1, exp2) .If exp1 is null then NVL function return value of exp2.</li><li><strong>NVL2:</strong> If exp1 is not null, nvl2 returns exp2, if exp1 is null, nvl2 returns exp3. The argument exp1 can have any data type. NVL2 (exp1, exp2, exp3)</li><li><strong>NULLIF:</strong> Compares two expressions and returns null if they are equal or the first expression if they are not equal. NULLIF (exp1, exp2)</li><li><strong>COALESCE:</strong> Returns the first non-null expression in the expression list. COALESCE (exp1, exp2… expn). The advantage of the COALESCE function over NVL function is that the COALESCE function can take multiple alternative values.</li><li><strong>Conditional Expressions:</strong> Provide the use of IF-THEN-ELSE logic within a SQL statement. Example: CASE Expression and DECODE Function.</li></ol><h4><strong>Q23. What is a Sub Query? Describe its Types?</strong></h4><p>A subquery is a <em>SELECT</em> statement that is embedded in a clause of another <em>SELECT</em> statement. A subquery can be placed in <em>where having</em> and <em>from</em> clause.</p><p><strong><em>Guidelines for using subqueries:</em></strong></p><ol><li>You should enclose the sub-queries within parenthesis.</li><li>Place these subqueries on the right side of the comparison condition.</li><li>Use Single-row operators with single-row subqueries.</li><li>Use Multiple-row operators with multiple-row subqueries.</li></ol><p><strong>Types of subqueries:</strong></p><ol><li><strong>Single-Row Subquery: </strong>Queries that return only one row from the inner select statement. Single-row comparison operators are: =, &gt;, &gt;=, &lt;, &lt;=, &lt;&gt;</li><li><strong>Multiple-Row Subquery: </strong>These are queries that return more than one row from the inner Select statement. You will also find multiple-column subqueries that return more than one column from the inner select statement. Operators include: <em>IN, ANY, ALL.</em></li></ol><h4><strong>Q24. What is the use of Double Ampersand (&amp;&amp;) in SQL Queries? Give an example</strong></h4><p>You can use <em>&amp;&amp;</em> if you want to reuse the variable value without prompting the user each time.</p><p>For example: Select empno, ename, &amp;&amp;column_name from employee order by &amp;column_name;</p><h4><strong>Q25. Describe VArray</strong></h4><p><em>VArray</em> is basically an Oracle data type used to have columns containing multivalued attributes and it can hold a bounded array of values. All Varrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*YpvQUcIlUmi2UnDKyf48dg.png" /></figure><p>Each element in a Varray has an index associated with it. It has a maximum size (max_size) that can be changed dynamically.</p><h4><strong>Q26. What are the attributes of the Cursor?</strong></h4><p>Each Cursor in Oracle has a set of attributes that enables an application program to test the state of the Cursor. The attributes can be used to check whether the cursor is opened or closed, found or not found and also find row count.</p><h4><strong>Q27. Name the various constraints used in Oracle</strong></h4><p>These are the following constraints used:</p><ul><li><strong><em>NULL</em>: </strong>It is to indicate that a particular column can contain NULL values.</li><li><strong><em>NOT NULL:</em></strong> It is to indicate that a particular column cannot contain NULL values.</li><li><strong><em>CHECK</em>: </strong>Validate that values in the given column to meet the specific criteria.</li><li><strong><em>DEFAULT</em>:</strong> It is to indicate the value is assigned to a default value.</li></ul><h4><strong>Q28. What is the fastest query method to fetch data from the table?</strong></h4><p>The fastest query method to fetch data from the table is by using the Row ID. A row can be fetched from a table by using RowID.</p><h4><strong>Q29. Difference between Cartesian Join and Cross Join?</strong></h4><p>There are no such differences between these Joins. Cartesian and Cross join are the same.</p><p><em>Cross join</em> gives a cartesian product of two tables i.e., the rows from the first table is multiplied with another table that is called cartesian product.</p><p>Cross join without the <em>where clause</em> gives a <em>Cartesian product</em>.</p><h4><strong>Q30. How does the ON-DELETE-CASCADE statement work?</strong></h4><p>Using this <em>On Delete Cascade</em> you can automatically delete a record in the child table when the same record is deleted from the parent table. This statement can be used with <em>Foreign Keys</em> as well.</p><p>You can add this <em>On Delete Cascade</em> option on an existing table.</p><p><strong>Syntax:</strong></p><p>Alter Table Child_T1 ADD Constraint Child_Parent_FK References<br>Parent_T1(Column1) ON DELETE CASCADE;</p><p>Now let’s move on to the next part of this Oracle Interview Questions article.</p><h3>Oracle PL/SQL Interview Questions</h3><h4><strong>Q31. What is PL SQL?</strong></h4><p>PL/SQL is an extension of Structured Query Language (SQL) that is used in Oracle. It combines the data manipulation power of SQL with the processing power of procedural language in order to create super-powerful <a href="https://www.edureka.co/blog/sql-basics/"><em>SQL queries</em></a>. PL SQL means instructing the compiler <em>what to do</em> through SQL and <em>how to do it</em> through its procedural way.</p><h4><strong>Q32. Enlist the characteristics of PL/SQL?</strong></h4><p>There are a lot of characteristics of PL/SQL. Some notable ones among them are:</p><ul><li>PL/SQL is a block-structured language.</li><li>It is portable to all environments that support Oracle.</li><li>PL/SQL is integrated with the Oracle data dictionary.</li><li>Stored procedures help better sharing of application.</li></ul><h4><strong>Q33. What are the data types available in PL/SQL?</strong></h4><p>There are two data types available in PL/SQL. They are namely:</p><ul><li><strong>Scalar data types</strong></li></ul><p>Example: Char, Varchar, Boolean, etc.</p><ul><li><strong>Composite datatypes</strong></li></ul><p>Example: Record, table etc.</p><h4><strong>Q34. What are the uses of a database trigger</strong></h4><p><em>Triggers</em> are the programs which are automatically executed when some events occur:</p><ul><li>Implement complex security authorizations.</li><li>Drive column values.</li><li>Maintain duplicate tables.</li><li>Implement complex business rules.</li><li>Bring transparency in log events.</li></ul><h4><strong>Q35. Show how functions and procedures are called in a PL SQL block</strong></h4><p>A <em>Procedure </em>can have a return statement to return the control to the calling block, but, it cannot return any values through the return statement. They cannot be called directly from <em>Select</em> statements but they can be called from another block or through EXEC keyword.</p><p>The procedure can be called in the following ways:<br>a) CALL &lt;procedure name&gt; direc<br>b) EXECUTE &lt;procedure name&gt; from calling environment<br>c) &lt;Procedure name&gt; from other procedures or functions or packages</p><p>Functions can be called in the following ways<br>a) Execute&lt;Function name&gt; from calling environment. Always use a variable to get the return value.<br>b) As part of an SQL/PL SQL Expression</p><h4><strong>Q36. What are the two virtual tables available at the time of database trigger execution?</strong></h4><p>Columns are referred as Then.column_name and Now.column_name.</p><ul><li><em>INSERT</em> related triggers, Now.column_name values are available only.</li><li>DELETE related triggers, Then.column_name values are available only.</li><li>UPDATE related triggers, both Table columns are available.</li></ul><h4><strong>Q37. What are the differences between Primary Key and Unique Key?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9EYt_Al1tkrpLsu9hy_7cA.png" /></figure><h4><strong>Q38. Explain the purpose of %TYPE and %ROWTYPE data types with the example?</strong></h4><p>%ROWTYPE and %TYPE are the attributes in PL/SQL which can inherit the datatypes of a table that are defined in a database. The main purpose of using these attributes in Oracle is to provide data independence and integrity. Also note that, if any of the datatypes gets changed in the database, PL/SQL code gets updated automatically including the change in the datatypes.</p><p><strong>%TYPE: </strong>This is used for declaring a variable that needs to have the same data type as of a table column.<br><strong>%ROWTYPE: </strong>This is used to define a complete row of record having a structure similar to the structure of a table.</p><h4><strong>Q39. Explain the difference between Triggers and Constraints?</strong></h4><p>Triggers are very different from Constraints in the following ways:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhVs6N_b1FYBxoA-1j3bkw.png" /></figure><h4><strong>Q40. Exception handling in PL/SQL</strong></h4><p>When an error occurs in PL/SQL, the corresponding exception is raised. This also means, to handle undesired situations where PL/SQL scripts gets terminated unexpectedly, error-handling code is included in the program. In PL/SQL, all exception handling code is placed in the Exception section.</p><p>There are 3 types of Exceptions:</p><ul><li><strong>Predefined Exceptions:</strong> Common errors with predefined names.</li><li><strong>Undefined Exceptions:</strong> Less common errors with no predefined names.</li><li><strong>User-defined Exceptions:</strong> Do not cause runtime error but violate business rules.</li></ul><h3>Comparison based Interview Questions</h3><h4><strong>Q41. What is the difference between COUNT (*), COUNT (expression), COUNT (distinct expression)?</strong></h4><p><strong>COUNT (*): </strong>This returns a number of rows in a table including the duplicates rows and the rows containing null values in the columns.<br><strong>COUNT (EXP): </strong>This returns the number of non-null values in the column identified by an expression.<br><strong>COUNT (DISTINCT EXP): </strong>It returns the number of <em>unique</em>, non-null values in the column identified by an expression.</p><h4><strong>Q42. Difference between the “VERIFY” and “FEEDBACK” command?</strong></h4><p>The major differences between Verify and Feedback commands are:</p><ul><li><strong>Verify Command: </strong>You can use this command to confirm the changes in the SQL statement which can have old and new values that are defined with Set Verify On/OFF.</li><li><strong>Feedback Command</strong>: It displays the number of records that are returned by a query.</li></ul><h4><strong>Q43. List out the difference between Commit, Rollback, and Savepoint?</strong></h4><p>The major differences between these are listed below:</p><ul><li><strong>Commit</strong>: This ends the current transaction by ensuring that all pending data changes are made permanent.</li><li><strong>Rollback</strong>: This ends the current transaction by discarding or deleting all pending data changes.</li><li><strong>Savepoint</strong>: It divides a transaction into smaller parts. You can rollback the transaction until you find a particular named savepoint.</li></ul><h4><strong>Q44. What is the difference between SUBSTR and INSTR?</strong></h4><p>SUBSTR returns a specific portion of a string whereas INSTR provides the character position in which a pattern is found in a <em>string</em>. SUBSTR returns string whereas INSTR returns numeric values.</p><h4><strong>Q45. Point out the difference between USER TABLES and DATA DICTIONARY?</strong></h4><p><strong>User Tables:</strong> This is a collection of tables created and maintained by the user. It also contains user information.<br><strong>Data dictionary: </strong>This is a collection of tables that are created and maintained by the Oracle Server. It contains database information. All data dictionary tables are owned by the<em> SYS user</em>.</p><h4><strong>Q46. Major difference between Truncate and Delete?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4cPlnU1EpmxWraz_o8MZeg.png" /></figure><h4><strong>Q47. Point the difference between TRANSLATE and REPLACE?</strong></h4><p><em>Translate</em> is used for character by character substitution whereas <em>Replace</em> is used to substitute a single character with a word.</p><h4><strong>Q48. What is the difference between $ORACLE_BASE and $ORACLE_HOME?</strong></h4><p><em>$Oracle_base</em> is the main or root directory of Oracle whereas <em>Oracle_Home</em> is located beneath the base folder in which all Oracle products reside.</p><h4><strong>Q49. What do you understand by Redo Log file mirroring?</strong></h4><p><em>Mirroring</em> is a process of having a copy of Redo log files. This is done by creating a group of log files altogether. It ensures that the LGWR automatically writes it to all the members of the current on-line redo log group. If the group fails, the database automatically switches over to the next group and it diminishes the performance of the database.</p><h4><strong>Q50. What is the difference between a hot backup and a cold backup in Oracle? Explain about their benefits as well</strong></h4><p><strong>Hot backup (Online Backup):</strong> A hot backup is also known as an online backup because it is done while the database is active. Some sites can’t shut down their database while making a backup copy and they are used 24*7.</p><p><strong>Cold backup (Offline Backup):</strong> A cold backup is also known as an offline backup because it is done while the database has been shut down using the SHUTDOWN command. If the database is suddenly shutdown with an uncertain condition, it should be restarted with <em>RESTRICT</em> mode and then shutdown with the NORMAL option. For a complete <em>cold backup</em>, the corresponding files must be backed up i.e., all data files, All control files, All online redo log files and the init.ora file (you can recreate it manually).</p><p>I hope this set of Oracle Interview Questions will help you in preparing for your interviews. All the best!</p><p>Now with this, we come to an end of this comparison on <strong>SQL vs NoSQL</strong>. I hope you guys enjoyed this article and understood all the differences. If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to <a href="https://www.edureka.co/blog/?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=top-50-oracle-interview-and-answers">Edureka’s official site.</a></p><p>Do look out for other articles in this series which will explain the various other aspects of SQL.</p><blockquote><em>1. </em><a href="https://medium.com/edureka/sql-vs-nosql-db-5d9b69ace6ac"><em>Differences Between SQL &amp; NoSQL Databases</em></a></blockquote><blockquote><em>2. </em><a href="https://medium.com/edureka/sql-for-data-science-a8fe10fe2ef9"><em>SQL For Data Science</em></a></blockquote><blockquote><a href="https://medium.com/edureka/sql-interview-questions-162f97f37ac2"><em>3.Top 65 SQL Interview Questions</em></a></blockquote><p><em>Originally published at </em><a href="https://www.edureka.co/blog/interview-questions/top-50-oracle-interview-and-answers/"><em>www.edureka.co</em></a><em> on Sep 12, 2019</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1a99534e2d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edureka/oracle-interview-and-answers-d1a99534e2d0">Top 50 Oracle Interview Questions and Answers</a> was originally published in <a href="https://medium.com/edureka">Edureka</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL For Data Science — One-stop Solution for Beginners]]></title>
            <link>https://medium.com/edureka/sql-for-data-science-a8fe10fe2ef9?source=rss-a1c3bc4dc33f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8fe10fe2ef9</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[sql-for-data-science]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kislay Keshari]]></dc:creator>
            <pubDate>Tue, 13 Aug 2019 13:01:21 GMT</pubDate>
            <atom:updated>2020-04-30T13:50:13.315Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL For Data Science — One-stop Solution for Beginners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*SMIahXbaI5ZdKIp8G6PHrw.png" /><figcaption>SQL For Data Science — Edureka</figcaption></figure><p>Since the time Data Science has been ranked at number 1 for being the most promising job of the era, we’re all trying to join the race of learning Data Science. This blog post on SQL for Data Science will help you understand how SQL can be used to store, access and retrieve data to perform data analysis.</p><p>Here’s a list of topics that will be covered in this blog:</p><ol><li>Why Is SQL Needed For Data Science?</li><li>What Is SQL?</li><li>Basics Of SQL</li><li>Installing MySQL</li><li>Hands-On</li></ol><h3>Why Is SQL Needed For Data Science?</h3><p>Did you know that we’re generating more than 2.5 quintillion bytes of data each day? This pace of data generation is the reason behind the popularity of high-end technologies such as Data Science, Artificial Intelligence, Machine Learning and so on.</p><p><em>Deriving useful insights from data is what is termed as Data Science. Data Science involves extracting, processing, and analyzing tons of data. At present what we need are tools that can be used to store and manage this vast amount of data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/0*Zgzvg3JW5B308AV4.jpg" /></figure><p>This is where SQL comes in.</p><p>SQL can be used to store, access and extract massive amounts of data in order to carry out the whole Data Science process more smoothly.</p><h3>What Is SQL?</h3><p>SQL which stands for Structured Query Language is a querying language aimed to manage Relational Databases.</p><p>But what exactly is a Relational Database?</p><p>A relational database is a group of well-defined tables from which data can be accessed, edited, updated and so on, without having to alter the database tables. SQL is the standard (API) for relational databases.</p><p>Coming back to SQL, SQL programming can be used to perform multiple actions on data such as querying, inserting, updating, deleting database records. Examples of relational databases that use SQL include MySQL Database, Oracle, etc.</p><p>Before we get started with a demo on SQL, let’s get familiar with the basic SQL commands.</p><h3>Basics Of SQL</h3><p>SQL provides a set of simple commands to modify data tables, let’s go through some of the basic SQL commands:</p><ul><li>CREATE DATABASE — <em>creates a new database</em></li><li>CREATE TABLE — <em>creates a new table</em></li><li>INSERT INTO — <em>inserts new data into a database</em></li><li>SELECT — <em>extracts data from a database</em></li><li>UPDATE — <em>updates data in a database</em></li><li>DELETE — <em>deletes data from a database</em></li><li>ALTER DATABASE — <em>modifies a database</em></li><li>ALTER TABLE — <em>modifies a table</em></li><li>DROP TABLE — <em>deletes a table</em></li><li>CREATE INDEX — <em>creates an index to search an element</em></li><li>DROP INDEX — <em>deletes an index</em></li></ul><p>To better understand SQL, let’s install MySQL and see how you can play with data.</p><h3>Installing MySQL</h3><p>Installing MySQL is a simple task. Here’s a <a href="https://www.edureka.co/blog/install-mysql?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=sql-for-data-science">step by step guide</a> that will help you install MySQL on your system.</p><p>Once you’re done installing MySQL, follow the below section for a simple demo that will show you how can you insert, manipulate and modify data.</p><h3><strong>SQL For Data Science — MySQL Demo</strong></h3><p>In this demonstration, we will see how to create databases and process them. This is a beginner level demonstration to get you started with data analysis on SQL.</p><p>So let’s get started!</p><p><strong>Step 1: Create a SQL Database</strong></p><p>A SQL database is a storage warehouse where data can be stored in a structured format. Now let’s create a database by using <a href="https://www.edureka.co/blog/what-is-mysql/">MySQL</a>:</p><pre>CREATE DATABASE edureka; <br>USE edureka;</pre><p>In the above code, there are two SQL commands:</p><p><strong>Note</strong>: SQL commands are defined in capital letters and a semi-colon is used to terminate a SQL command.</p><ol><li><strong>CREATE DATABASE: </strong>This command creates a database called ‘edureka’</li><li><strong>USE:</strong> This command is used to activate the database. Here we’re activating the ‘edureka’ database.</li></ol><h4><strong>Step 2: Create a table with the required data features</strong></h4><p>Creating a table is as simple as creating a database. You just have to define the variables or the features of the table with their respective data types. Let’s see how this can be done:</p><pre>CREATE TABLE toys (TID INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, Item_name TEXT, Price INTEGER, Quantity INTEGER);</pre><p>In the above code snippet the following things occur:</p><ol><li>Use the ‘CREATE TABLE’ command to create a table called toys.</li><li>The toy table contains 4 features, namely, TID (Transaction ID), Item_name, Price and Quantity.</li><li>Each variable is defined with their respective data types.</li><li>The TID variable is declared as a primary key. A primary key basically denotes a variable that can store a unique value.</li></ol><p>You can further check the details of the defined table by using the following command:</p><pre>DESCRIBE toys;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*rzgib9L5pPAMGe2PGrswNQ.png" /></figure><h4><strong>Step 3: Inserting data into the table</strong></h4><p>Now that we’ve created a table, let’s fill it up with some values. Earlier in this blog, I mentioned how you can add data into a table by just using a single command, i.e., INSERT INTO.</p><p>Let’s see how this is done:</p><pre>INSERT INTO toys VALUES (NULL, &quot;Train&quot;, 550, 88);<br>INSERT INTO toys VALUES (NULL, &quot;Hotwheels_car&quot;, 350, 80);<br>INSERT INTO toys VALUES (NULL, &quot;Magic_Pencil&quot;, 70, 100);<br>INSERT INTO toys VALUES (NULL, &quot;Dog_house&quot;, 120, 54);<br>INSERT INTO toys VALUES (NULL, &quot;Skateboard&quot;, 700, 42);<br>INSERT INTO toys VALUES (NULL, &quot;G.I. Joe&quot;, 300, 120);</pre><p>In the above code snippet, we simply inserted 6 observations into our ‘toys’ table by using the INSERT INTO command. For each observation, within the brackets, I’ve specified the value of each variable or feature that was defined while creating the table.</p><p>The TID variable is set to NULL since it auto-increments from 1.</p><p>Now let’s display all the data present in our table. This can be done by using the below command:</p><pre>SELECT * FROM toys;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Kj1hH9No5sUtgfIu8OCFeg.png" /></figure><h4><strong>Step 4: Modify the data entries</strong></h4><p>Let’s say that you decided to increase the price of the G.I. Joe since it is getting you a lot of customers. How would you update the price of the variable in a database?</p><p>It’s simple, just use the below command:</p><pre>UPDATE toys SET Price=350 WHERE TID=6;</pre><p>The UPDATE command allows you to modify any values/variables stored in the table. The SET parameter allows you to select a particular feature and the WHERE parameter is used to identify the variable/ value that you want to change. In the above command, I’ve updated the price of the data entry whose TID is 6 (G.I. Joe).</p><p>Now let’s view the updated table:</p><pre>SELECT * FROM toys;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*FyqIDuTy-rR_s62U29ATZQ.png" /></figure><p>You can also modify what you want to be displayed by just referring to the columns you want to view. For example, the below command will display only the name of the toy and its respective price:</p><pre>SELECT Item_name, Price FROM toys;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*v7Zq15anvHus7shfi7fsDA.png" /></figure><h4><strong>Step 5: Retrieving data</strong></h4><p>So after inserting the data and modifying it, it’s finally time to extract and retrieve the data according to the business requirements. This is where data can be retrieved for further data analysis and data modeling.</p><p>Note that is a simple example to get you started with SQL, however, in real-world scenarios the data is much more complicated and big in size. Despite this, the SQL commands still remain the same and that’s what makes SQL so simple and understandable. It can process complex data sets with a set of simple SQL commands.</p><p>Now let’s retrieve data with a couple of modifications. Refer the code below and try to understand what it does without looking at the output:</p><pre>SELECT * FROM toys LIMIT 2;</pre><p>You guessed it! It displays the first two observations present in my table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*0bQFnoZm50joWP9fZ2_aIQ.png" /></figure><p>Let’s try something more interesting.</p><pre>SELECT * FROM toys ORDER BY Price ASC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*RhR6d8tYprtNzuGSQCYQ8A.png" /></figure><p>As shown in the figure, the values are arranged with respect to the ascending order of the price variable. If you want to look for the three most frequently bought items, what would you do?</p><p>It’s quite simple really!</p><pre>SELECT * FROM toys ORDER BY Quantity DESC LIMIT 3;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*zT2uUgnpxOIyJsjJPh83cg.png" /></figure><p>Let’s try one more.</p><pre>SELECT * FROM toys WHERE Price &gt; 400 ORDER BY Price ASC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*eD5o0vffIRqaBzQ_B2n4Rw.png" /></figure><p>So that’s how you can process data by using SQL. If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to <a href="https://www.edureka.co/blog/?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=sql-for-data-science">Edureka’s official site.</a></p><p>Do look out for other articles in this series which will explain the various other aspects of SQL.</p><blockquote><em>1. </em><a href="https://medium.com/edureka/sql-vs-nosql-db-5d9b69ace6ac"><em>Differences Between SQL &amp; NoSQL Databases</em></a></blockquote><blockquote><em>2. </em><a href="https://medium.com/edureka/oracle-interview-and-answers-d1a99534e2d0"><em>Top 50 Oracle Interview Questions</em></a></blockquote><blockquote><a href="https://medium.com/edureka/sql-interview-questions-162f97f37ac2"><em>3.Top 65 SQL Interview Questions</em></a></blockquote><p><em>Originally published at </em><a href="https://www.edureka.co/blog/sql-for-data-science/"><em>https://www.edureka.co</em></a><em> on August 13, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8fe10fe2ef9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edureka/sql-for-data-science-a8fe10fe2ef9">SQL For Data Science — One-stop Solution for Beginners</a> was originally published in <a href="https://medium.com/edureka">Edureka</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Differences Between SQL & NoSQL Databases — MySQL & MongoDB Comparison]]></title>
            <link>https://medium.com/edureka/sql-vs-nosql-db-5d9b69ace6ac?source=rss-a1c3bc4dc33f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d9b69ace6ac</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[sql-vs-nosql]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Kislay Keshari]]></dc:creator>
            <pubDate>Tue, 16 Apr 2019 07:20:22 GMT</pubDate>
            <atom:updated>2020-04-30T13:49:02.752Z</atom:updated>
            <content:encoded><![CDATA[<h3>Differences Between SQL &amp; NoSQL Databases — MySQL &amp; MongoDB Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ohteOOd2Mft15MXB1BdS7w.png" /><figcaption>SQL vs NoSQL — Edureka</figcaption></figure><p>With the amount of data present in the world, it is almost next to impossible, to manage data without proper databases. In today’s market, there are different kinds of databases present, and deciding on the best database which suits your business can be an overwhelming task. So, in this article on SQL vs NoSQL, I will compare these two type of databases to help you choose which type of database can help you and your organization.</p><p>The following topics will be covered in this article:</p><ul><li>What is SQL?</li><li>What is NoSQL?</li><li>SQL vs NoSQL</li><li>Examples of SQL and NoSQL</li><li>What is MySQL?</li><li>What is MongoDB?</li><li>MySQL vs MongoDB</li><li>Demo: Insert values into tables and collections</li></ul><p>So, let us get started, folks!!</p><h3>What is SQL?</h3><p>SQL aka Structured Query Language is the core of the relational database which is used for accessing and managing the databases. This language is used to manipulate and retrieve data from a structured data format in the form of tables and holds relationships between those tables. The relations could be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eoOOYXSjXWB1qUne2YJ61A.png" /></figure><ul><li>A One-to-One Relationship is when a single row in Table A is related to a single row in Table B.</li><li>A One-to-Many Relationship is when a single row in Table A is related to many rows in table B.</li><li>A Many-to-Many Relationship is when many rows in table A can be related to many rows in table B.</li><li>A Self -Referencing Relationship is when a record in table A is related to the same table itself.</li></ul><p>Now, next in this article let us understand what is NoSQL?</p><h3>What is NoSQL?</h3><p>NoSQL, or most commonly known as Not only SQL database, provides a mechanism for storage and retrieval of unstructured data. This type of database can handle a humongous amount of data and has a dynamic schema. So, a NoSQL database has no specific query language, no or a very few relationships, but has data stored in the format of collections and documents.</p><p>So, a database can have a ’n’ number of collections and each collection can have ‘m <strong>‘</strong> number of documents. Consider the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrNEIAkQdkNf6I9tEX4wUA.png" /></figure><p>As you can see from the above image, there is an Employee Database which has 2 collections i.e. the Employee and Projects Collection. Now, each of these collections has Documents, which are basically the data values. So, you can assume the<em> collections to be your tables and the Documents to be your fields in the tables</em>.</p><p>Alright, So, now that you know what is SQL &amp; NoSQL, let us now see, how these databases stand against each other.</p><h3>SQL vs NoSQL</h3><p>So, in this face off, I will be comparing both these databases based on the following grounds:</p><ol><li>Type of Database</li><li>Schema</li><li>Database Categories</li><li>Complex Queries</li><li>Hierarchical Data Storage</li><li>Scalability</li><li>Language</li><li>Online Processing</li><li>Base Properties</li><li>External Support</li></ol><h4>Type of database</h4><p>SQL is called <strong><em>a relational database</em></strong> as it organizes structured data into defined rows and columns, with each table being related to the other tables in the database.</p><p>NoSQL, on the other hand, is known <strong><em>as a non-relational database</em></strong>. This is because data is stored in the form of collections with no or few relations between them.</p><h4>Schema</h4><p>SQL needs a <strong><em>predefined schema</em></strong> for structured data. So, before you start using SQL to extract and manipulate data, you need to make sure that your data structure is pre-defined in the form of tables.</p><p>However, NoSQL, have a <strong><em>dynamic schema</em></strong> for unstructured data. So, if you are using a NoSQL database, then there is no pre-defined schema present, and the complete schema of your data completely depends upon how you wish to store data. i.e. which fields do you want to store in documents and collections.</p><h4>Database Categories</h4><p>The SQL databases are . So, you can have ’n’ number of tables related to each other and each table can have rows and columns which store data in each cell of the table.</p><p>Now, if we talk about NoSQL Databases, then NoSQL databases have the following categories of databases:</p><ul><li><strong><em>Document Database</em></strong>– It pairs each key with a complex data structure known as the document. It can contain many different key-value pairs, or key array pairs or even nested documents</li><li><strong><em>Key value stores</em></strong>– They are the simplest NoSQL databases. Every single item in the database is stored as an attribute name or key together with its value.</li><li><strong><em>Graph store</em></strong>– They are used to store information about networks, such as social connections. Graph stores include Neo4J and HyperGraphDB.</li><li><strong><em>Wide column stores</em></strong>– Wide column stores such as Cassandra and HBase are optimized for queries over large datasets, and store columns of data together, instead of rows.</li></ul><p>So, SQL databases store data in the form of tables and NoSQL databases store data in the form of key-value pair, documents, graph databases or wide-column stores.</p><h4>Complex Queries</h4><p>SQL is a <strong><em>better fit for complex query environment</em></strong> when compared to NoSQL as the schema in SQL databases is structured and has data stored in a tabular format. So, even if you wish to apply nested queries with many subqueries inside the outer query, you can easily do by using the proper table and column names.</p><p>Now, the reason why <strong><em>NoSQL databases isn’t a good fit for complex queries</em></strong> is because the NoSQL databases aren’t queried in a standard language like SQL.</p><h4>Hierarchical Data Storage</h4><p>Well, when we compare the databases on this factor, <strong><em>NoSQL fits better for hierarchical storage</em></strong><em> </em>when compared to SQL databases.</p><p>This is because as the number of tables increases, the complexity of maintaining relations between them also keeps increasing. So, in such a scenario, you cannot relate the humongous amount of tables with many columns in them to each other. But, when you consider a NoSQL database, this kind of database fits better for the hierarchical data storage as it follows the key-value pair way of storing data which is similar to JSON data.</p><h4>Scalability</h4><p>The SQL databases are<strong><em> vertically scalable</em></strong>. You can load balance the data servers by optimizing hardware such as increasing CPU, RAM, SSD, etc.</p><p>On the other hand, NoSQL databases are <strong><em>horizontally scalable</em></strong>. You can perform load balancing by adding more servers to your cluster to handle a large amount of traffic.</p><h4>Language</h4><p>The <strong><em>SQL databases have a specific language,</em></strong> and it does not vary from databases to databases. This kind of databases uses the SQL ( Structured Query Language ) for retrieving and manipulating the data.</p><p>The<strong><em> NoSQL databases have no specific language</em></strong> used for queries, and it varies from database to database. In the NoSQL database, the queries are mainly focused on the collection of documents and the language is known as UnQL (Unstructured Query Language).</p><h4>Online Processing</h4><p>On comparing SQL and NoSQL, based on this factor, SQL databases are used for <strong><em>heavy-duty transactional type applications. </em></strong>Well, this is because SQL provides atomicity, integrity, and stability of the data. Also, you can use NoSQL for transactions purpose, but, it is still not stable enough in high load and for complex transactional applications. So, you can understand that SQL is mainly used for OLTP(Online Transactional Processing) and NoSQL is mainly used for OLAP(Online Analytical Processing).</p><h4>Base Properties</h4><p>SQL databases are based on <strong><em>ACID properties</em></strong><em> </em>( Atomicity, Consistency, Isolation, and Durability) whereas the NoSQL databases are based on the <strong><em>Brewers CAP theorem</em></strong> ( Consistency, Availability, and Partition tolerance ).</p><p>Let me explain you the ACID properties first:</p><ul><li><strong>Atomicity</strong>: Atomicity refers to the transactions that are completely done or failed where transaction refers to a single logical operation of a data. It means if one part of any transaction fails, the entire transaction fails and the database state is left unchanged.</li><li><strong>Consistency</strong>: Consistency ensures that the data must meet all the validation rules. In simple words, you can say that your transaction never leaves the database without completing its state.</li><li><strong>Isolation</strong>: The main goal of isolation is concurrency control.</li><li><strong>Durability</strong>: Durability means that if a transaction has been committed, it will occur whatever may come in between such as power loss, crash or any sort of error.</li></ul><p>Coming to CAP Theorem,</p><p>Brewers CAP Theorem states that a database can only achieve at most two out of three guarantees: Consistency, Availability and Partition Tolerance. Here</p><ul><li><strong>Consistency: </strong>All the nodes see the same data at the same time.</li><li><strong>Availability: </strong>Guarantees whether every request is successful in failed.</li><li><strong>Partition Tolerance: </strong>Guarantees whether a system continues to operate despite message loss or failure of part of the system.</li></ul><p>NoSQL can not provide consistency and high availability together.</p><h4>External Support</h4><p>All the SQL vendors offer excellent support since SQL has been into existence for more than the past 40 years. However, for some NoSQL database, only limited experts are available and you still have to rely on community support to deploy your large scale NoSQL deployments. This is because NoSQL has come into existence in the late 2000s and people haven’t explored it yet much.</p><p>So, if I have to summarize the differences for SQL and NoSQL in this article on SQL vs NoSQL, you can refer to the below table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeQrHqjVIesDYAH99fFvOg.png" /></figure><p>So, folks, with this we come to an end of this face-off between SQL and NoSQL. Now, that we have discussed so much about SQL and NoSQL, let me show you some examples of the same.</p><h3>Examples of SQL and NoSQL</h3><p>Examples of SQL and NoSQL are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tBC3kpUwR0VwyCTs1kMd3A.png" /></figure><p>Now, the most popular databases from SQL and NoSQL are <strong><em>MySQL</em></strong> and <strong><em>MongoDB</em></strong>.</p><p>So, next in this article on SQL vs NoSQL, we will be comparing MySQL and MongoDB.</p><h3>What is MySQL?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*eD4mBMkMN4zMG--42sgJBQ.png" /></figure><p>MySQL is an open-source relational database management system that works on many platforms. It provides multi-user access to support many storage engines and is backed by Oracle. So, you can buy a commercial license version from Oracle to get premium support services.</p><p>The following are the features of MySQL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0mA_IwXHonK2vQxcg42KA.png" /></figure><ul><li><strong><em>Ease of Management</em></strong><em> </em>— The software very easily gets downloaded and also uses an event scheduler to schedule the tasks automatically.</li><li><strong><em>Robust Transactional Support</em></strong> — Holds the ACID (Atomicity, Consistency, Isolation, Durability) property, and also allows distributed multi-version support.</li><li><strong><em>Comprehensive Application Development</em></strong> — MySQL has plugin libraries to embed the database into any application. It also supports stored procedures, triggers, functions, views and many more for application development.</li><li><strong><em>High Performance</em></strong> — Provides fast load utilities with distinct memory caches and table index partitioning.</li><li><strong><em>Low Total Cost Of Ownership</em></strong> — This reduces licensing costs and hardware expenditures.</li><li><strong><em>Open Source &amp; 24 * 7 Support</em></strong> — This RDBMS can be used on any platform and offers 24*7 support for open source and enterprise edition.</li><li><strong><em>Secure Data Protection</em></strong><em> </em>— MySQL supports powerful mechanisms to ensure that only authorized users have access to the databases.</li><li><strong><em>High Availability</em></strong><em> </em>— MySQL can run high-speed master/slave replication configurations and it offers cluster servers.</li><li><strong><em>Scalability &amp; Flexibility</em></strong> — With MySQL you can run deeply embedded applications and create data warehouses holding a humongous amount of data.</li></ul><p>Next, in this article let us understand what is MongoDB?</p><h3>What is MongoDB?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*NMOuXxR-hT_gBenfjDsjcQ.jpeg" /></figure><p>MongoDB is a non-relational database which stores the data in documents. This type of database stores the related information together for quick query processing.</p><p>The features of MongoDB are as follows:</p><ul><li><strong>Indexing:</strong> It indexes are created in order to improve the search performance.</li><li><strong>Replication:</strong> MongoDB distributes the data across different machines.</li><li><strong>Ad-hoc Queries:</strong> It supports ad-hoc queries by indexing the BSON documents &amp; using a unique query language.</li><li><strong>Schemaless:</strong> It is very flexible because of its schema-less database that is written in C++.</li><li><strong>Sharding:</strong> MongoDB uses sharding to enable deployments with very large data sets and high throughput operations.</li></ul><p>Alright, So, now that you know what is MySQL &amp; MongoDB, let us now see, how these databases stand against each other.</p><h3>MySQL vs MongoDB</h3><p>So, in this face off, I will be comparing both these databases based on the following grounds:</p><ol><li>Query Language</li><li>Flexibility of Schema</li><li>Relationships</li><li>Security</li><li>Performance</li><li>Support</li><li>Key Features</li><li>Replication</li><li>Usage</li><li>Active Community</li></ol><h3>Query Language</h3><p>MongoDB, on the other hand,<strong><em>MySQL uses the Structured Query language(SQL)</em></strong>. This language is simple and consists of mainly DDL, DML DCL &amp; TCL commands to retrieve and manipulate data. MongoDB on the other hand <strong><em>uses an Unstructured Query Language</em></strong>. So, the query language is basically the MongoDB query language. Refer to the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yp1lV5SzLwgZ9K_fcm7KQw.png" /></figure><h4>Flexibility of Schema</h4><p><strong><em>MySQL has good flexibility of schema for structured data</em></strong> as you just need to clearly define tables and columns. Now, <strong><em>has no restrictions on schema design</em></strong>. You can directly mention, a couple of documents inside a collection without having any relations between those documents. But, the only problem with MongoDB is that you need to optimize your schema based on how you want to access the data .</p><h4>Relationships</h4><p>On comparing MySQL and MongoDB based on this factor, <strong><em>MySQL support relationships with the help of JOIN statements</em></strong> but <strong><em>MongoDB does not support the JOIN statements</em></strong>. But, it supports placing one document inside another document (also known as the embedding of documents) and multi-dimensional data types such as arrays.</p><h4>Security</h4><p>MySQL basically uses a <strong><em>privilege-based security model</em></strong>. This kind of security model authenticates a user and facilitates the user privileges on a particular database.</p><p>MongoDB, on the other hand, uses a<strong><em> role-based access control</em></strong> with a flexible set of privileges providing security features such as authorization, and authentication.</p><h4>Performance</h4><p>On comparing MySQL and MongoDB on this parameter, let me tell you that <strong><em>MySQL is quite slow in comparison to MongoDB</em></strong> when large databases are considered. This is mainly due to because MySQL cannot be used for large and unstructured amounts of data.</p><p>However, MongoDB has the ability to handle large unstructured data. So, it is faster than MySQL where large databases are considered as it allows users to query in such a way that the load on servers are reduced.</p><blockquote><strong>NOTE:</strong> There is as such no hard and fast rule that MongoDB will be faster for your data all the time, It completely depends on your data and infrastructure.</blockquote><h4>Support</h4><p>Well, <strong><em>both of them offer excellent support 24*7</em></strong> for security fixes, maintenance releases, bug fixes, patches, and updates. So, there is as such no difference between both of them based on this parameter.</p><h4>Key Features</h4><p>You can refer to the following image for the key features of MySQL and MongoDB:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7VCHB5fDi8FiWk4Se4F44g.png" /></figure><h4>Replication</h4><p><strong><em>MySQL supports master-slave replication</em></strong> and master-master replication. MongoDB, on the other hand, <strong><em>supports built-in replication, sharding, and auto-elections.</em></strong> So, with the help of auto-elections in MongoDB, you can set up another or secondary database to automatically take over if the primary database fails.</p><h4>Usage</h4><p>You can refer to the following image for understanding where to use MySQL and MongoDB:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_LeYNB5cWftUwXsNsrcNg.png" /></figure><h4>Active Community</h4><p>On comparing MySQL with MongoDB based on this factor,<strong><em> MySQL databases offer a better community than MongoDB</em></strong> as it is owned, and maintained by the Oracle Corporation.</p><p>So, if I have to summarize the differences between MySQL and MongoDB, you can refer to the below table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lbf5-dxZP6QZQOANBFHUZw.png" /></figure><p>So, folks, with this we come to an end of this face-off between MySQL and MongoDB. Now, knowing so much more about MySQL and MongoDB might have raised a question on your mind i.e.<strong><em>Wether businesses should go for MySQL or MongoDB?</em></strong></p><p>Well, there is no clear winner between both of them. The choice of database completely depends upon the schema of your database and how you wish to access it. Nevertheless, you can use MySQL when you have a fixed schema, high transaction, low maintenance, data security with a limited budget and MongoDB while you have an unstable schema, high availability, cloud computing, with in-built sharding.</p><p>So, there won’t be any final verdict as to which among them is the best as each one of these excel based on your requirement.</p><p>Now, that you know the differences between MySQL and MongoDB, next in this article on SQL vs NoSQL let me show you how to insert data into tables and collections in MySQL Workbench and MongoDB Compass respectively.</p><h3>Demo: Insert Data Into Tables And Collections</h3><p>Let us start with inserting data into a table using MySQL Workbench.</p><h4>Insert data into a table using MySQL Workbench</h4><p>To insert data into tables using MySQL Workbench, you can follow the below steps:</p><p><strong>Step 1:</strong> Open MySQL Workbench and create a connection.</p><p><strong>Step 2:</strong> Now, once your connection has been created, open your connection and then you will be redirected to the following dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*qt_kcqHl7F_t7HWnQ-fHAw.png" /></figure><p><strong>Step 3:</strong> Now to create a database and a table, follow the below queries:</p><pre>//Create Database<br>CREATE DATABASE Employee_Info;<br>//Use Database<br>USE Employee_Info;<br>//Create Table<br>CREATE TABLE Employee<br>(EmpID int,<br>EmpFname varchar(255),<br>EmpLname varchar(255),<br>Age int,<br>EmailID varchar(255),<br>PhoneNo int8,<br>Address varchar(255));</pre><p><strong>Step 4:</strong> Now, once your table is created, to insert values into the table, use the INSERT INTO syntax as below:</p><pre>//Insert Data into a Table<br>INSERT INTO Employee(EmpID, EmpFname, EmpLname,Age, EmailID, PhoneNo, Address)<br>VALUES (&#39;1&#39;, &#39;Vardhan&#39;,&#39;Kumar&#39;, &#39;22&#39;, &#39;<a href="/service/mailto:vardy@abc.com">vardy@abc.com</a>&#39;, &#39;9876543210&#39;, &#39;Delhi&#39;);</pre><p><strong>Step 5:</strong> When you view your table, you will the output as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*WHFZq1E2IboHKZFv-r8g1Q.png" /></figure><p>Now, next in this article on SQL vs NoSQL, let us see how to create database and collections in MongoDB Compass.</p><h4>Insert data into a collection using MongoDB Compass</h4><p>To insert data into tables using MongoDB Compass, you can follow the below steps:</p><p><strong>Step 1:</strong> Open <strong>MongoDB Compass</strong> and <strong>create a host</strong>. Once your host is created click on<strong> Connect.</strong> Refer below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*WlMYwgSmYNW4CAI5Iwh_6Q.png" /></figure><p><strong>Step 2:</strong> Now, once your host is connected, to create a database, click on the <strong>Create Database </strong>option and mention the<strong> Database and the Collection Name.</strong></p><p><strong>Step 3:</strong> Now, open your database, and choose the collection. Here I have chosen samplecollection. To add documents into the collection, choose the <strong>Insert Document</strong> option and<strong> mention the parameters</strong>. Here I have mentioned the EmpID and EmpName.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*9aCvs-Zq-3mRc7Sb6M-4ZQ.png" /></figure><p>Now with this, we come to an end of this comparison on <strong>SQL vs NoSQL</strong>. I Hope you guys enjoyed this article and understood all the differences. If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to <a href="https://www.edureka.co/blog/?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=sql-vs-nosql-db">Edureka’s official site.</a></p><p>Do look out for other articles in this series which will explain the various other aspects of SQL.</p><blockquote><em>1. </em><a href="https://medium.com/edureka/sql-for-data-science-a8fe10fe2ef9"><em>SQL For Data Science</em></a></blockquote><blockquote><em>2. </em><a href="https://medium.com/edureka/oracle-interview-and-answers-d1a99534e2d0"><em>Top 50 Oracle Interview Questions</em></a></blockquote><blockquote><a href="https://medium.com/edureka/sql-interview-questions-162f97f37ac2"><em>3.Top 65 SQL Interview Questions</em></a></blockquote><p><em>Originally published at </em><a href="https://www.edureka.co/blog/sql-vs-nosql-db/"><em>https://www.edureka.co</em></a><em> on April 16, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d9b69ace6ac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edureka/sql-vs-nosql-db-5d9b69ace6ac">Differences Between SQL &amp; NoSQL Databases — MySQL &amp; MongoDB Comparison</a> was originally published in <a href="https://medium.com/edureka">Edureka</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PySpark Programming - Integrating Speed With Simplicity]]></title>
            <link>https://medium.com/edureka/pyspark-programming-e007e68fbccb?source=rss-a1c3bc4dc33f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e007e68fbccb</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <dc:creator><![CDATA[Kislay Keshari]]></dc:creator>
            <pubDate>Tue, 14 Aug 2018 15:32:36 GMT</pubDate>
            <atom:updated>2020-09-10T12:44:00.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hJqrr7tyTQZH4xXGo7xicg.jpeg" /><figcaption>PySpark Programming - Edureka</figcaption></figure><p>Python and Apache Spark are the hottest buzzwords in the analytics industry. Apache Spark is a popular open source framework that ensures data processing with lightning speed and supports various languages like Scala, Python, Java, and R. It then boils down to your language preference and scope of work. Through this PySpark programming article, I would be talking about Spark with Python to demonstrate how Python leverages the functionalities of Apache Spark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-2GDktS3fDMKMDgdBBnIQ.jpeg" /></figure><p>Before we embark on our journey of PySpark Programming, let me list down the topics that I will be covering in this article:</p><ul><li>What is PySpark</li><li>RDDs</li><li>DataFrame</li><li>PySpark SQL</li><li>PySpark Streaming</li><li>Machine Learning(MLlib)</li></ul><p>So, let get started with the first topic on our list, i.e., PySpark Programming.</p><h3>PySpark Programming</h3><p>PySpark is the collaboration of Apache Spark and Python.</p><p><strong>Apache Spark</strong> is an open-source cluster-computing framework, built around speed, ease of use, and streaming analytics whereas <strong>Python</strong> is a general-purpose, high-level programming language. It provides a wide range of libraries and is majorly used for Machine Learning and Real-Time Streaming Analytics.</p><p>In other words, it is a Python API for Spark that lets you harness the simplicity of Python and the power of Apache Spark in order to tame Big Data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTDEt8iL5ck37gWHsJ6_-w.jpeg" /></figure><p>You might be wondering, why I chose Python to work with Spark when there are other languages available. To answer this, I have listed down few of the advantages that you will enjoy with Python:</p><ul><li>Python is very easy to learn and implement.</li><li>It provides simple and comprehensive API.</li><li>With Python, the readability of code, maintenance, and familiarity is far better.</li><li>It provides various options for data visualization, which is difficult using Scala or Java.</li><li>Python comes with a wide range of libraries like numpy, pandas, scikit-learn, seaborn, matplotlib etc.</li><li>It is backed up by a huge and active community.</li></ul><h3>Resilient Distributed Datasets (RDDs)</h3><p><a href="https://www.edureka.co/blog/pyspark-rdd?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=pyspark-programming">RDDs</a> are the building blocks of any Spark application. RDDs Stands for:</p><ul><li><strong><em>Resilient:</em></strong> It is fault tolerant and is capable of rebuilding data on failure.</li><li><strong><em>Distributed:</em></strong> Data is distributed among the multiple nodes in a cluster.</li><li><strong><em>Dataset:</em></strong> Collection of partitioned data with values.</li></ul><p>It is a layer of abstracted data over the distributed collection. It is immutable in nature and follows <em>lazy transformations</em>.</p><p>With RDDs, you can perform two types of operations:</p><ol><li><strong>Transformations: </strong>These operations are applied to create a new RDD.</li><li><strong>Actions:</strong> These operations are applied on an RDD to instruct Apache Spark to apply computation and pass the result back to the driver.</li></ol><h3>DataFrame</h3><p>Dataframe in PySpark is the distributed collection of structured or semi-structured data. This data in Dataframe is stored in rows under named columns which is similar to the relational database tables or excel sheets.</p><p>It also shares some common attributes with RDD like Immutable in nature, follows lazy evaluations and is distributed in nature. It supports a wide range of formats like JSON, CSV, TXT and many more. Also, you can load it from the existing RDDs or by programmatically specifying the schema.</p><h3>PySpark SQL</h3><p>PySpark SQL is a higher-level abstraction module over the PySpark Core. It is majorly used for processing structured and semi-structured datasets. It also provides an optimized API that can read the data from the various data source containing different files formats. Thus, with PySpark you can process the data by making use of SQL as well as HiveQL. Because of this feature, PySpark SQL is slowly gaining popularity among database programmers and Apache Hive users.</p><h3>PySpark Streaming</h3><p>PySpark Streaming is a scalable, fault-tolerant system that follows the RDD batch paradigm. It is basically operated in mini-batches or batch intervals which can range from 500ms to larger interval windows.</p><p>In this, Spark Streaming receives a continuous input data stream from sources like <a href="https://www.edureka.co/blog/apache-flume-tutorial?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=pyspark-programming">Apache Flume</a>, Kinesis, Kafka, TCP sockets etc. These streamed data are then internally broken down into multiple smaller batches based on the <em>batch interval </em>and forwarded to the Spark Engine. Spark Engine processes these data batches using complex algorithms expressed with high-level functions like map, reduce, join and window. Once the processing is done, the processed batches are then pushed out to databases, file systems, and live dashboards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXWEuaknDWpY98Ee10VLQg.jpeg" /></figure><p>The key abstraction for Spark Streaming is Discretized Stream (DStream). DStreams are built on RDDs facilitating the Spark developers to work within the same context of RDDs and batches to solve the streaming issues. Moreover, Spark Streaming also integrates with MLlib, SQL, DataFrames, and GraphX which widens your horizon of functionalities. Being a high-level API, Spark Streaming provides fault-tolerance “<em>exactly-once” </em>semantics for stateful operations.</p><blockquote><strong><em>NOTE</em></strong><em>: “exactly-once” semantics means events will be processed “exactly once” by all operators in the stream application, even if any failure occurs.</em></blockquote><p>Below diagram, represents the basic components of Spark Streaming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v3hJF1Sj1eYeWP35SCoAGg.jpeg" /></figure><p>As you can see, Data is ingested into the Spark Stream from various sources like Kafka, Flume, Twitter, ZeroMQ, Kinesis, or TCP sockets, and many more. Further, this data is processed using complex algorithms expressed with high-level functions like map, reduce, join, and window. Finally, this processed data is pushed out to various file systems, databases, and live dashboards for further utilization.</p><p>I hope this gave you a clear picture of how PySpark Streaming works. Let’s now move on to the last but most enticing topic of this PySpark Programming article, i.e. Machine Learning.</p><h3>Machine Learning</h3><p>As you already know, Python is a mature language that is being heavily used for data science and machine learning since ages. In PySpark, machine learning is facilitated by a Python library called MLlib (Machine Learning Library). It is nothing but a wrapper over PySpark Core that performs data analysis using machine-learning algorithms like classification, clustering, linear regression and few more.</p><p>One of the enticing features of machine learning with PySpark is that it works on distributed systems and is highly scalable.</p><p>MLlib exposes three core machine learning functionalities with PySpark:</p><ol><li><strong>Data Preparation: </strong>It <strong>provides various features like extraction, transformation, selection, hashing etc.</strong></li><li><strong>Machine Learning Algorithms: </strong>It avails some popular and advanced regression, classification, and clustering algorithms for machine learning.</li><li><strong>Utilities: </strong>It has statistical methods such as chi-square testing, descriptive statistics, linear algebra and model evaluation methods.</li></ol><p>Let me show you how to implement machine learning using <em>classification</em> through logistic regression.</p><p>Here, I will be performing a simple predictive analysis on a food inspection data of Chicago City.</p><pre>##Importing the required libraries<br>from pyspark.ml import Pipeline<br>from pyspark.ml.classification import LogisticRegression<br>from pyspark.ml.feature import HashingTF, Tokenizer<br>from pyspark.sql import Row<br>from pyspark.sql.functions import UserDefinedFunction<br>from pyspark.sql.types import *<br> <br>##creating a RDD by importing and parsing the input data<br>def csvParse(s):<br>import csv<br>from StringIO import StringIO<br>sio = StringIO(s)<br>value = csv.reader(sio).next()<br>sio.close()<br>return value<br> <br>food_inspections = sc.textFile(&#39;file:////home/edureka/Downloads/Food_Inspections_Chicago_data.csv&#39;)\<br>.map(csvParse)<br> <br>##Display data format<br>food_inspections.take(1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*Pqdglektrs4kWgXs2qUaUg.jpeg" /></figure><pre>#Structuring the data<br>schema = StructType([<br>StructField(&quot;id&quot;, IntegerType(), False),<br>StructField(&quot;name&quot;, StringType(), False),<br>StructField(&quot;results&quot;, StringType(), False),<br>StructField(&quot;violations&quot;, StringType(), True)])<br>#creating a dataframe and a temporary table (Results) required for the predictive analysis. <br>##sqlContext is used to perform transformations on structured data<br>ins_df = spark.createDataFrame(food_inspections.map(lambda l: (int(l[0]), l[1], l[12], l[13])) , schema)<br>ins_df.registerTempTable(&#39;Count_Results&#39;)<br>ins_df.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*PeBNLs6C8OKLR41rzHY1TQ.jpeg" /></figure><pre>##Let&#39;s now understand our dataset<br>#show the distinct values in the results column<br>result_data = ins_df.select(&#39;results&#39;).distinct().show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*41y4-WiY8gHrLC4zgi6B2A.jpeg" /></figure><pre>##converting the existing dataframe into a new dataframe <br>###each inspection is represented as a label-violations pair. <br>####Here 0.0 represents a failure, 1.0 represents a success, and -1.0 represents some results besides those two<br>def label_Results(s):<br>if s == &#39;Fail&#39;:<br>return 0.0<br>elif s == &#39;Pass with Conditions&#39; or s == &#39;Pass&#39;:<br>return 1.0<br>else:<br>return -1.0<br>ins_label = UserDefinedFunction(label_Results, DoubleType())<br>labeled_Data = ins_df.select(ins_label(ins_df.results).alias(&#39;label&#39;), ins_df.violations).where(&#39;label &gt;= 0&#39;)<br>labeled_Data.take(1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*gJXoeiSF5CoR-Lj7wyDYZQ.jpeg" /></figure><pre>##Creating a logistic regression model from the input dataframe<br>tokenizer = Tokenizer(inputCol=&quot;violations&quot;, outputCol=&quot;words&quot;)<br>hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol=&quot;features&quot;)<br>lr = LogisticRegression(maxIter=10, regParam=0.01)<br>pipeline = Pipeline(stages=[tokenizer, hashingTF, lr])<br>model = pipeline.fit(labeled_Data)<br>## Evaluating with Test Data<br> <br>test_Data = sc.textFile(&#39;file:////home/edureka/Downloads/Food_Inspections_test.csv&#39;)\<br>.map(csvParse) \<br>.map(lambda l: (int(l[0]), l[1], l[12], l[13]))<br>test_df = spark.createDataFrame(test_Data, schema).where(&quot;results = &#39;Fail&#39; OR results = &#39;Pass&#39; OR results = &#39;Pass with Conditions&#39;&quot;)<br>predict_Df = model.transform(test_df)<br>predict_Df.registerTempTable(&#39;Predictions&#39;)<br>predict_Df.columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*VmD2hzn2JkQj5NKK6ZUqwg.jpeg" /></figure><pre>## Printing 1st row<br>predict_Df.take(1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*0VqsK9oDLxN0talPPc-TFw.jpeg" /></figure><pre>## Predicting the final result<br>numOfSuccess = predict_Df.where(&quot;&quot;&quot;(prediction = 0 AND results = &#39;Fail&#39;) OR<br>(prediction = 1 AND (results = &#39;Pass&#39; OR<br>results = &#39;Pass with Conditions&#39;))&quot;&quot;&quot;).count()<br>numOfInspections = predict_Df.count()<br>print &quot;There were&quot;, numOfInspections, &quot;inspections and there were&quot;, numOfSuccess, &quot;successful predictions&quot;<br>print &quot;This is a&quot;, str((float(numOfSuccess) / float(numOfInspections)) * 100) + &quot;%&quot;, &quot;success rate&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*GT8smOm_1dhLKnqbNYt1SQ.jpeg" /></figure><p>With this, we come to the end of this blog on PySpark Programming. Hope it helped in adding some value to your knowledge.</p><p>If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to<a href="https://www.edureka.co/blog/?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=pyspark-programming"> Edureka’s official site.</a></p><p>Do look out for other articles in this series which will explain the various other aspects of PySpark.</p><blockquote>1. <a href="https://medium.com/edureka/pyspark-tutorial-87d41dab9657">PySpark Tutorial</a></blockquote><blockquote>2.<a href="https://medium.com/edureka/pyspark-dataframe-tutorial-9335f3d09b4"> PySpark Dataframe Tutorial</a></blockquote><blockquote>3. <a href="https://medium.com/edureka/pyspark-rdd-ef9edd060a25">RDDs in PySpark</a></blockquote><blockquote>4. <a href="https://medium.com/edureka/pyspark-mllib-tutorial-759391dbb08a">PySpark MLlib Tutorial</a></blockquote><p><em>Originally published at </em><a href="https://www.edureka.co/blog/pyspark-programming/"><em>www.edureka.co</em></a><em> on August 14, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e007e68fbccb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edureka/pyspark-programming-e007e68fbccb">PySpark Programming - Integrating Speed With Simplicity</a> was originally published in <a href="https://medium.com/edureka">Edureka</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide To PySpark RDD]]></title>
            <link>https://medium.com/edureka/pyspark-rdd-ef9edd060a25?source=rss-a1c3bc4dc33f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef9edd060a25</guid>
            <category><![CDATA[spark-rdd]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Kislay Keshari]]></dc:creator>
            <pubDate>Fri, 10 Aug 2018 13:42:38 GMT</pubDate>
            <atom:updated>2019-06-05T14:54:28.622Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*z8UHd9GNnH9oPNrKASlKYA.jpeg" /><figcaption>PySpark RDD Tutorial — Edureka</figcaption></figure><p>Apache Spark is one of the best frameworks when it comes to Big Data analytics. No sooner this powerful technology integrates with a simple yet efficient language like<a href="https://www.edureka.co/blog/python-tutorial?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=pyspark-rdd"> Python</a>, it gives us an extremely handy and easy to use API called PySpark. In this article, I am going to throw some light on one of the <em>building blocks</em> of PySpark called <strong>Resilient Distributed Dataset</strong> or more popularly known as <strong>PySpark RDD</strong>.</p><p>By the end of this PySpark RDD tutorial, you would have an understanding of the below topics:</p><ul><li>Why RDDs?</li><li>What are PySpark RDDs?</li><li>Features Of RDDs</li><li>RDD Operations in PySpark</li><li>PySpark RDD Use Case</li></ul><h3>Why RDDs?</h3><p>Iterative distributed computing, i.e., processing of data over multiple jobs requires reusing and sharing of data among them. Before RDDs came into the picture, frameworks like Hadoop faced difficulty in processing multiple operations/jobs. Also, a stable and distributed intermediate data store was needed, like HDFS or Amazon S3. These media for <strong>Data sharing</strong> helped in performing various computations like Logistic Regression, K-means clustering, Page rank algorithms, ad-hoc queries, etc. But nothing comes for free, data sharing leads to slow data processing because of multiple I/O operation like replication and serialization. This scenario is depicted below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vayqc2S0di_aS_ol8LX47A.png" /></figure><p>Thus, there was a need for something which can overcome the issue of multiple I/O operations through data sharing and reduce its number. This is where <strong>RDDs</strong> exactly fit into the picture.</p><h3>What are PySpark RDDs?</h3><p><em>Resilient Distributed Datasets (RDDs) are a distributed memory abstraction that helps a programmer to perform in-memory computations on large clusters that too in a fault-tolerant manner.</em></p><p>RDDs are considered to be the <strong><em>backbone of PySpark</em></strong>. It’s one of the pioneers in the fundamental schema-less data structure, that can handle both structured and unstructured data. The in-memory data sharing makes RDDs <strong>10–100x</strong> <strong>faster</strong> than network and disk sharing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8xuvzoou0ZqNsxYGIuTPA.png" /></figure><p>Now you might be wondering about its working. Well, the data in an RDD is split into chunks based on a key. RDDs are highly resilient, i.e, they are able to recover quickly from any issues as the same data chunks are replicated across multiple executor nodes. Thus, even if one executor node fails, another will still process the data. This allows you to perform your functional calculations against your dataset very quickly by harnessing the power of multiple nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*-dIUvV-utOFO8VrqQHCg9A.png" /></figure><p>Moreover, once you create an RDD it becomes <strong>immutable</strong>. By immutable I mean, an object whose state cannot be modified after it is created, but they can surely be transformed.</p><p>Before I move ahead with this article, let me lay down a few more intriguing features of PySpark.</p><h3>Features Of RDDs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6jIWPHZ9bUIr0XSW6NjiA.png" /></figure><ol><li><strong><em>In-Memory Computations</em></strong><em>:</em> It improves the performance by an order of magnitudes.</li><li><strong><em>Lazy Evaluation</em></strong><em>:</em> All transformations in RDDs are lazy, i.e, doesn’t compute their results right away.</li><li><strong><em>Fault Tolerant</em></strong><em>:</em> RDDs track data lineage information to rebuild lost data automatically.</li><li><strong><em>Immutability</em></strong><em>:</em> Data can be created or retrieved anytime and once defined, its value can’t be changed.</li><li><strong><em>Partitioning</em></strong><em>:</em> It is the fundamental unit of parallelism in PySpark RDD.</li><li><strong><em>Persistence</em></strong><em>:</em> Users can reuse PySpark RDDs and choose a storage strategy for them.</li><li><strong><em>Coarse-Grained Operations</em></strong><em>:</em> These operations are applied to all elements in data sets through maps or filter or group by operation.</li></ol><p>In the next section of the article, I will introduce you to the various operations offered by PySpark RDDs.</p><h3>RDD Operations in PySpark</h3><p>RDD supports two types of operations namely:</p><h4><strong><em>Transformations</em></strong><em>:</em></h4><p>These are the operations which are applied to an RDD to create a new RDD. Transformations follow the principle of <strong>Lazy Evaluations</strong> (which means that the execution will not start until an action is triggered). This allows you to execute the operations at any time by just calling an action on the data. Few of the transformations provided by RDDs are:</p><ul><li>map</li><li>flatMap</li><li>filter</li><li>distinct</li><li>reduceByKey</li><li>mapPartitions</li><li>sortBy</li></ul><h4><strong><em>Actions</em></strong><em>:</em></h4><p>Actions are the operations which are applied on an RDD to instruct Apache Spark to apply computation and pass the result back to the driver. Few of the actions include:</p><ul><li>collect</li><li>collectAsMap</li><li>reduce</li><li>countByKey/countByValue</li><li>take</li><li>first</li></ul><p>Let me help you to create an RDD in PySpark and apply a few operations on them.</p><h4>Creating and displaying an RDD</h4><pre>myRDD = sc.parallelize([(&#39;JK&#39;, 22), (&#39;V&#39;, 24), (&#39;Jimin&#39;,24), (&#39;RM&#39;, 25), (&#39;J-Hope&#39;, 25), (&#39;Suga&#39;, 26), (&#39;Jin&#39;, 27)]) <br>myRDD.take(7)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*mKygpkzvDxEjFW4J_wefqA.png" /></figure><h4>Reading data from a text file and displaying the first 4 elements</h4><pre>New_RDD = sc.textFile(&quot;file:///home/edureka/Desktop/Sample&quot;) New_RDD.take(4)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e35cDDjHrFBIBhWyNcFCvg.png" /></figure><h4>Changing minimum number of partitions and mapping the data from a list of strings to list of lists</h4><pre>CSV_RDD = (sc.textFile(&quot;file:///home/edureka/Downloads/fifa_players.csv&quot;, minPartitions= 4).map(lambda element: element.split(&quot;\t&quot;))) CSV_RDD.take(3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SOXtc7-UpLI0H27RasZ8MA.png" /></figure><h4>Counting the total number of rows in RDD</h4><pre>CSV_RDD.count()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*xvafDIbCX7kvNa0LGYCq5g.png" /></figure><h4>Creating a function to convert the data into lower case and splitting it</h4><pre>def Func(lines):<br>lines = lines.lower()<br>lines = lines.split()<br>return lines<br>Split_rdd = New_RDD.map(Func)<br>Split_rdd.take(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*wU3zGk-vBM7orV8vGsckbw.png" /></figure><h4>Creating a new RDD with flattened data and filtering out the ‘stopwords’ from the entire RDD</h4><pre>stopwords = [&#39;a&#39;,&#39;all&#39;,&#39;the&#39;,&#39;as&#39;,&#39;is&#39;,&#39;am&#39;,&#39;an&#39;,&#39;and&#39;,&#39;be&#39;,&#39;been&#39;,&#39;from&#39;,&#39;had&#39;,&#39;I&#39;,&#39;I’d&#39;,&#39;why&#39;,&#39;with&#39;]<br>RDD = New_RDD.flatMap(Func)<br>RDD1 = RDD.filter(lambda x: x not in stopwords)<br>RDD1.take(4)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*cy8C45TwImJAZgAEdPmaMQ.png" /></figure><h4>Filtering the words starting with ‘c’</h4><pre>import re<br>filteredRDD = RDD.filter(lambda x: x.startswith(&#39;c&#39;))<br>filteredRDD.distinct().take(50)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*hUh5aqE89zucrIOqlWrlYQ.png" /></figure><h4>Grouping the data by key and then sorting it</h4><pre>rdd_mapped = RDD.map(lambda x: (x,1))<br>rdd_grouped = rdd_mapped.groupByKey()<br>rdd_frequency = rdd_grouped.mapValues(sum).map(lambda x: (x[1],x[0])).sortByKey(False)<br>rdd_frequency.take(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yavgdgkF_nKIO4BeBcQJ9Q.png" /></figure><h4>Creating RDDs with key-value pair</h4><pre>a = sc.parallelize([(&#39;a&#39;,2),(&#39;b&#39;,3)]) <br>b = sc.parallelize([(&#39;a&#39;,9),(&#39;b&#39;,7),(&#39;c&#39;,10)])</pre><h4><strong>Performing Join operation on the RDDs</strong></h4><pre>c = a.join(b) <br>c.collect()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmsPR3Ycv2cva479QJCT8A.png" /></figure><h4>Creating an RDD and performing a lambda function to get the sum of elements in the RDD</h4><pre>num_rdd = sc.parallelize(range(1,5000))<br>num_rdd.reduce(lambda x,y: x+y)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fl7E-_X4kP5TJYPhKfA4qA.png" /></figure><h4>Using ReduceByKey transformation to reduce the data</h4><pre>data_keydata_key = sc.parallelize([(&#39;a&#39;, 4),(&#39;b&#39;, 3),(&#39;c&#39;, 2),(&#39;a&#39;, 8),(&#39;d&#39;, 2),(&#39;b&#39;, 1),(&#39;d&#39;, 3)],4) data_keydata_key.reduceByKey(lambda x, y: x + y).collect()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKk7BDVd55RGFrJc7sL5UQ.png" /></figure><h4>Saving the data in a text file</h4><pre>RDD3.saveAsTextFile(&quot;file:///home/edureka/Desktop/newoutput.txt&quot;)</pre><h4>Sorting the data based on a key</h4><pre>test = [(&#39;a&#39;, 1), (&#39;b&#39;, 2), (&#39;1&#39;, 3), (&#39;d&#39;, 4), (&#39;2&#39;, 5)] sc.parallelize(test).sortByKey(True, 1).collect()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEjZ7J_LNO8OiLJvodZz6Q.png" /></figure><h4>Performing Set Operations</h4><pre>##Creating two new RDDs <br>rdd_a = sc.parallelize([1,2,3,4]) <br>rdd_b = sc.parallelize([3,4,5,6])</pre><ul><li><strong>Intersection</strong></li></ul><pre>rdd_a.intersection(rdd_b).collect()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qD1Nv34OzfSmdLePV5qwkw.png" /></figure><ul><li><strong>Subtraction</strong></li></ul><pre>rdd_a.subtract(rdd_b).collect()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Ev2pYEtAK3zFz1sfQ-iIg.png" /></figure><ul><li><strong>Cartesian</strong></li></ul><pre>rdd_a.cartesian(rdd_b).collect()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Y9MVTBwenuT0sxkDJQO-w.png" /></figure><ul><li><strong>Union</strong></li></ul><pre>rdd_a.union(rdd_b).collect()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*sB-4GmkSb8JDng-zZbyAJQ.png" /></figure><p>I hope you are familiar with PySpark RDDs by now. So let’s dive deeper and see how you can use these RDDs to solve a real-life use case.</p><h3>PySpark RDD Use Case</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*E_lkvSFfLkPHVG24ODLraQ.png" /></figure><h4>Problem Statement</h4><p>You have to calculate the page rank of a set of web pages based on the illustrated web page system. Below is a diagram representing four web pages, Amazon, Google, Wikipedia, and YouTube, in our system. For the ease of access, let’s name them a,b,c, and d respectively. Here, the web page ‘a’ has outbound links to pages b, c, and d. Similarly, page ‘b’ has an outbound link to pages d and c. Web page ‘c’ has an outbound link to page b, and page ‘d’ has an outbound link to pages a and c.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*JNUlCFW3AO5S_-abZfTekQ.png" /></figure><h4>Solution</h4><p>To solve this, we will be implementing the page-rank algorithm that was developed by <em>Sergey Brin</em> and <em>Larry Page. </em>This algorithm helps in determining the rank of a particular web page within a group of web pages. Higher the page rank, higher it will appear in a search result list. Thus, will hold more relevance.</p><p>The contribution to page rank is given by the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*9SXR1M3SIwmM9ptkyrqsSA.png" /></figure><p>Let me break it down for you:</p><p><strong>PRt+1(Pi) </strong>= Page rank of a site</p><p><strong>PRt(Pj) </strong>= Page rank of an inbound link</p><p><strong>C(Pj) </strong>= Number of links on that page</p><p>In our problem statement, it is shown that the web page ‘a’ has three outbound links. So, according to the algorithm, the contribution to page rank of page d by page a is PR(a) / 3. Now we have to calculate the contribution of page b to page d. Page b has two outbound links: the first to page c, and the second to page d. Hence, the contribution by page b is PR(b) / 2.</p><p>So the page rank of page d will be updated as follows, where s is known as the damping factor :</p><p>PR(d) = 1 — s + s × (PR(a)/3 + PR(b)/2)</p><p>Let’s now execute this using PySpark RDDs.</p><pre>##Creating Nested Lists of Web Pages with Outbound Links<br>pageLinks = [[&#39;a&#39;, [&#39;b&#39;,&#39;c&#39;,&#39;d&#39;]],<br>[&#39;c&#39;, [&#39;b&#39;]],[&#39;b&#39;, [&#39;d&#39;,&#39;c&#39;]],[&#39;d&#39;, [&#39;a&#39;,&#39;c&#39;]]]<br> <br>##Initializing Rank #1 to all the webpages<br>pageRanks = [[&#39;a&#39;,1],[&#39;c&#39;,1],[&#39;b&#39;,1],[&#39;d&#39;,1]]<br> <br>##Defining the number of iterations for running the page rank<br>###It will return the contribution to the page rank for the list of URIs<br>def rankContribution(uris, rank):<br>numberOfUris = len(uris)<br>rankContribution = float(rank) / numberOfUris<br>newrank =[]<br>for uri in uris:<br>newrank.append((uri, rankContribution))<br>return newrank<br> <br>##Creating paired RDDs of link data<br>pageLinksRDD = sc.parallelize(pageLinks, 2)<br>pageLinksRDD.collect()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-yIMGUMbtldQJ22jqNonA.png" /></figure><pre>##Creating the paired RDD of our rank data <br>pageRanksRDD = sc.parallelize(pageRanks, 2)<br>pageRanksRDD.collect()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Il3UADyLoToSRMxPBAA9CA.png" /></figure><pre>##Defining the number of iterations and the damping factor, s<br>numIter = 20<br>s = 0.85<br> <br>##Creating a Loop for Updating Page Rank<br>for i in range(numIter):<br>linksRank = pageLinksRDD.join(pageRanksRDD)<br>contributedRDD = linksRank.flatMap(lambda x : rankContribution(x[1][0],x[1][1]))<br>sumRanks = contributedRDD.reduceByKey(lambda v1,v2 : v1+v2)<br>pageRanksRDD = sumRanks.map(lambda x : (x[0],(1-s)+s*x[1]))<br> <br>pageRanksRDD.collect()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TUsc86slCl8W3KRd6J6_A.png" /></figure><p>This gives us the result that <strong><em>‘c’ has the highest page rank followed by ‘a’, ‘d’ and ‘b’</em></strong>.</p><p>With this, we come to an end of this PySpark RDD. Hope it helped in adding some value to your knowledge.</p><p>If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to <a href="https://www.edureka.co/blog/?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=pyspark-rdd">Edureka’s official site.</a></p><p>Do look out for other articles in this series which will explain the various other aspects of PySpark.</p><blockquote>1. <a href="https://medium.com/edureka/pyspark-tutorial-87d41dab9657">PySpark Tutorial</a></blockquote><blockquote>2. <a href="https://medium.com/edureka/pyspark-dataframe-tutorial-9335f3d09b4">PySpark Dataframe Tutorial</a></blockquote><blockquote>3. <a href="https://medium.com/edureka/pyspark-mllib-tutorial-759391dbb08a">PySpark MLlib Tutorial</a></blockquote><blockquote>4. <a href="https://medium.com/edureka/pyspark-programming-e007e68fbccb">PySpark Programming</a></blockquote><p><em>Originally published at </em><a href="https://www.edureka.co/blog/pyspark-rdd/"><em>www.edureka.co</em></a><em> on August 10, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef9edd060a25" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edureka/pyspark-rdd-ef9edd060a25">A Comprehensive Guide To PySpark RDD</a> was originally published in <a href="https://medium.com/edureka">Edureka</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Churn Prediction Using PySpark MLlib]]></title>
            <link>https://medium.com/edureka/pyspark-mllib-tutorial-759391dbb08a?source=rss-a1c3bc4dc33f------2</link>
            <guid isPermaLink="false">https://medium.com/p/759391dbb08a</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Kislay Keshari]]></dc:creator>
            <pubDate>Tue, 24 Jul 2018 07:43:59 GMT</pubDate>
            <atom:updated>2019-06-05T14:57:22.428Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*4rKAUTm5nZSXHuZYB2zhxw.jpeg" /></figure><p>Machine learning has gone through many recent developments and is becoming more popular day by day. Machine Learning is being used in various projects to find hidden information in data by people from all domains, including Computer Science, Mathematics, and Management. It was just a matter of time that Apache Spark Jumped into the game of Machine Learning with Python, using its MLlib library. So, in this PySpark MLlib Tutorial, I’ll be discussing the following topics:</p><ul><li>What is Machine Learning?</li><li>What is PySpark MLlib?</li><li>Machine Learning (Python) Industrial Use Cases</li><li>Machine Learning Lifecycle</li><li>PySpark MLlib Features and Algorithms</li><li>Finding Hackers with PySpark MLlib</li><li>Customer Churn Prediction with PySpark MLlib</li></ul><h3>What is Machine Learning?</h3><p>Machine learning is a method of Data Analysis that automates Analytical Model building. Using algorithms that iteratively learn from data, machine learning allows computers to <strong>find hidden insights</strong> without being explicitly programmed where to look. It focuses on the development of computer programs that can <strong>teach themselves</strong> to grow and change when exposed to new data. Machine Learning uses the data to detect patterns in a dataset and adjust program actions accordingly.</p><p>Most industries working with large amounts of data have recognized the value of machine learning technology. By gleaning insights from this data, often in real time, organizations are able to work more efficiently or gain an advantage over competitors.</p><p>Now that you have got a brief idea of what is Machine Learning, Let’s move forward with this article and understand what is MLlib and what are its features?</p><h3>What is PySpark MLlib?</h3><p>PySpark MLlib is a machine-learning library. It is a wrapper over PySpark Core to do data analysis using machine-learning algorithms. It works on distributed systems and is scalable. We can find implementations of classification, clustering, linear regression, and other machine-learning algorithms in PySpark MLlib.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*us-gytTZlbr_mZletfh9yQ.png" /></figure><h3>Machine Learning(Python) Industrial Use Cases</h3><p><a href="https://www.edureka.co/blog/machine-learning-algorithms?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=pyspark-mllib-tutorial">Machine learning algorithms</a>, applications, and platforms are helping manufacturers find new business models, fine-tune product quality, and optimize manufacturing operations to the shop floor level. So Let’s continue our article and understand how the various industries are using Machine Learning.</p><h4><strong>Government:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*VEzC8_5pA4KHWxiRyaohpw.png" /></figure><p>Government agencies such as public safety and utilities have a particular need for machine learning. They use it for face detection, security and fraud detection. Public sector agencies are making use of machine learning for government initiatives to gain vital insights into policy data.</p><h4><strong>Marketing and E-commerce:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*flMZ5EY3s3YIhOeDXvLgTA.png" /></figure><p>The number of purchases made online is steadily increasing, which allows companies to gather detailed data on the whole customer experience. Websites recommending items you might like based on previous purchases are using machine learning to analyze your buying history and promote other items you’d be interested in.</p><h4><strong>Transportation:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*EhpWXNcTd_4JjZWSg6Nhpg.png" /></figure><p>Analyzing data to identify patterns and trends is key to the transportation industry, which relies on making <strong>routes more efficient</strong> and predicting potential problems to increase profitability. Companies use ML to enable an efficient ride-sharing marketplace, identify suspicious or fraudulent accounts, suggest optimal pickup and drop-off points.</p><h4><strong>Finance:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*HkTb7M_FdtEhqfFkJz_YcQ.png" /></figure><p>Today, machine learning has come to play an integral role in many phases of the financial ecosystem, from approving loans to managing assets, to assessing risks. Banks and other businesses in the financial industry use machine learning technology to <strong>prevent fraud.</strong></p><h4><strong>Healthcare:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*0GjClGavzKtt-jYgar7FfQ.png" /></figure><p>Machine learning is a fast-growing trend in the healthcare industry, thanks to the advent of wearable devices and sensors that can use data to assess a patient’s health in real time. <strong>Google</strong> has developed a machine learning algorithm to help identify cancerous tumors on mammograms. <strong>Stanford</strong> is using a deep learning algorithm to identify skin cancer.</p><p>Now that you have an idea of what is Machine Learning and what are the various areas in the industry where it is used, let’s continue our article and understand what a typical Machine Learning Lifecycle looks like.</p><h3>Machine Learning Lifecycle</h3><p>A typical Machine Learning Cycle involves majorly two phases:</p><ul><li>Training</li><li>Testing</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*6lX2SdJzuwzhok3V8umkAQ.png" /></figure><p>In Machine Learning, we basically try to create a model to predict on the test data. So, we use the training data to fit the model and testing data to test it. The models generated are to predict the results unknown which is named as the test set. As you pointed out, the dataset is divided into train and test set in order to check accuracies, precisions by training and testing it on it.</p><ol><li><strong>Training Set</strong>: Here, you have the complete training dataset. You can extract features and train to fit a model and so on.</li><li><strong>Testing Set</strong>: Here, once the model is obtained, you can predict using the model obtained on the training set.</li></ol><p>Now that you have an idea of what a Typical Machine Learning Lifecycle works, let’s move forward with our article with MLlib features and the various languages supported by it.</p><h3>MLlib Features and Algorithms</h3><p>We know that PySpark is good for iterative algorithms. Using iterative algorithms, many machine-learning algorithms have been implemented in PySpark MLlib. Apart from PySpark efficiency and scalability, PySpark MLlib APIs are very user-friendly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*D08wKE8Yu2i_Awt4NRbEOA.png" /></figure><h3>Finding Hackers with MLlib</h3><p>A company system was hacked and lots of data were stolen. Fortunately, metadata for each session hackers used to connect was recorded and is available to us. There are 3 potential hackers, or even more.</p><p>A common practice among hackers is the tradeoff of the job. This means that hackers do roughly the same amount of hacks. So here we are going to use clustering to find out the number of hackers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*Xb41c6g_GloJ0ufPH7txUA.png" /></figure><h4>Initializing Spark Session</h4><p>Firstly we need to initialize spark session.</p><pre>from pyspark.sql import SparkSession <br>spark = SparkSession.builder.appName(&#39;find_hacker&#39;).getOrCreate()</pre><h4>Importing KMeans Library and Loading the Dataset</h4><p>We will be using Kmeans Algorithm to do our analysis and for that, we need to import the Kmeans Library and then we’ll load our dataset with <strong>spark.read</strong> method.</p><pre>from pyspark.ml.clustering import KMeans <br>dataset = spark.read.csv(&quot;file:///home/edureka/Downloads/hack_data.csv&quot;,header=True,inferSchema=True)</pre><h4>Schema of the Data retrieved</h4><p>Let’s have a look at the schema of data to get a better understanding of what we are dealing with.</p><pre>dataset.printSchema()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*JS9zfhAqvXUWMAdWk7QE_Q.png" /></figure><h4>Importing VectorAssembler and creating our Features</h4><p>We must transform our data using the VectorAssembler function to a single column where each row of the DataFrame contains a feature vector. In order to create our clusters, we need to select columns based on which we will then create our features column. Here we are using the columns:</p><ul><li>Session_Connection_Time</li><li>Bytes Transferred</li><li>Kali_Trace_Used</li><li>Servers_Corrupted</li><li>Pages_Corrupted</li><li>WPM_Typing_Speed : Words Per Minute</li></ul><pre>from pyspark.ml.linalg import Vectors<br>from pyspark.ml.feature import VectorAssembler<br> <br>feat_cols = [&#39;Session_Connection_Time&#39;, &#39;Bytes Transferred&#39;, &#39;Kali_Trace_Used&#39;,<br>&#39;Servers_Corrupted&#39;, &#39;Pages_Corrupted&#39;,&#39;WPM_Typing_Speed&#39;]<br> <br>vec_assembler = VectorAssembler(inputCols = feat_cols, outputCol=&#39;features&#39;)<br> <br>final_data = vec_assembler.transform(dataset)</pre><h4>Importing the StandardScaler Library and Creating Scaler</h4><p>Centering and Scaling happen independently on each feature by computing the relevant statistics on the samples in the training set. Mean and standard deviation are then stored to be used on later data using the transform method.</p><p>Standardization of a dataset is a common requirement for many machine learning estimators: they might behave badly if the individual feature does not more or less look like standard normally distributed data.</p><pre>from pyspark.ml.feature import StandardScaler <br>scaler = StandardScaler(inputCol=&quot;features&quot;, outputCol=&quot;scaledFeatures&quot;, withStd=True, withMean=False)</pre><h4>Computing Summary Statistics</h4><p>Let’s Compute summary statistics by fitting the StandardScaler. Then Normalize each feature to have a unit standard deviation.</p><pre>scalerModel = scaler.fit(final_data)<br> <br>cluster_final_data = scalerModel.transform(final_data)<br> <br>kmeans3 = KMeans(featuresCol=&#39;scaledFeatures&#39;,k=3)<br>kmeans2 = KMeans(featuresCol=&#39;scaledFeatures&#39;,k=2)</pre><h4>Building KMeans Model and Calculating WSSE (Within Set of Squared Errors)</h4><p>We have to first build our Model. The number of desired clusters is then passed to the algorithm. We then compute Within Set Sum of Squared Error (WSSSE). We use the values derived from these to figure out whether we have 2 or 3 hackers.</p><pre>model_k3 = kmeans3.fit(cluster_final_data)<br>model_k2 = kmeans2.fit(cluster_final_data)<br> <br>wssse_k3 = model_k3.computeCost(cluster_final_data)<br>wssse_k2 = model_k2.computeCost(cluster_final_data)<br> <br>print(&quot;With K=3&quot;)<br>print(&quot;Within Set Sum of Squared Errors = &quot; + str(wssse_k3))<br>print(&#39;--&#39;*30)<br>print(&quot;With K=2&quot;)<br>print(&quot;Within Set Sum of Squared Errors = &quot; + str(wssse_k2))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*TE42AEVGypNqmPd83WwAdA.png" /></figure><h4>Checking the Elbow Point (WSSSE)</h4><p>We’ll check the values of WSSSE for 2 to 8 and see if we have an elbow in the list.</p><pre>for k in range(2,9):<br>kmeans = KMeans(featuresCol=&#39;scaledFeatures&#39;,k=k)<br>model = kmeans.fit(cluster_final_data)<br>wssse = model.computeCost(cluster_final_data)<br>print(&quot;With K={}&quot;.format(k))<br>print(&quot;Within Set Sum of Squared Errors = &quot; + str(wssse))<br>print(&#39;--&#39;*30)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*iWnb_0rflyHWtQ9fnCB3QA.png" /></figure><p>Here we can see that the value of WSSSE is continuously decreasing and we don’t have an elbow. So most probably the value of K is 2 and not 3. Let’s continue this PySpark MLlib Tutorial and get to the verdict.</p><h4>Final Check for the number of Hacker</h4><p>Let’s find out how many hackers were involved based on the number of hacks done.</p><pre>model_k3.transform(cluster_final_data).groupBy(&#39;prediction&#39;).count().show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*D28qHq8E50m0Dht-S-lsXA.png" /></figure><pre>model_k2.transform(cluster_final_data).groupBy(&#39;prediction&#39;).count().show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*mlUYsW-3n3F-eKxHSlTX9w.png" /></figure><p>So, here we can see that for 3 hackers, our model has produced 167,79 and 88 hacks. This is not possible as the hackers usually divide the tasks in between them. In our model where K =2, we get 167 number of hacks for both the hackers. Hence there were only 2 hackers involved.</p><p>Let’s continue our article and solve another problem faced by many companies ie. Customer Churn.</p><h3>Customer Churn Prediction with MLlib</h3><p>Churn prediction is big business. It minimizes customer defection by predicting which customers are likely to cancel a subscription to a service. Though originally used within the telecommunications industry, it has become common practice across banks, ISPs, insurance firms, and other verticals.</p><p>The prediction process is heavily data-driven and often utilizes advanced machine learning techniques. Here, we’ll take a look at what types of customer data are typically used, do some preliminary analysis of the data, and generate churn prediction models — all with PySpark and its machine learning frameworks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*dFtn5qpUTsaepcy-jssb3A.png" /></figure><p>A marketing agency has many customers that use their service to produce ads for the client/customer websites. They’ve noticed that they have quite a bit of churn in clients. They basically randomly assign account managers right now but want you to create a machine learning model that will help predict which customers will churn (stop buying their service) so that they can correctly assign the customers most at risk to churn an account manager. Luckily they have some historical data.</p><p>So, can you help them out?</p><h4>Loading the libraries</h4><p>Let’s load up the required libraries. Here we are going to use Logistic Regression.</p><pre>from pyspark.ml.classification import LogisticRegression</pre><h4>Reading the training and testing Data</h4><p>Let’s load up the training data and the testing data (incoming data for testing purposes)</p><pre>input_data=spark.read.csv(&#39;file:///home/edureka/Downloads/customer_churn.csv&#39;,header=True,inferSchema=True)<br> <br>test_data=spark.read.csv(&#39;file:///home/edureka/Downloads/new_customers.csv&#39;,header=True,inferSchema=True)</pre><h4>Schema of Data</h4><p>We are going to have a look at the schema of data to get a better understanding of what we are dealing with.</p><pre>input_data.printSchema() //training data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*JrJgalNz3vXBPgmLiiD2dQ.png" /></figure><p>Here we have column Churn. Let’s see the schema of the testing data as well.</p><pre>test_data.printSchema() //testing data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*L-ty15C1d7YJopcYpyWhjg.png" /></figure><h4>Using VectorAssembler</h4><pre>from pyspark.ml.linalg import Vectors<br>from pyspark.ml.feature import VectorAssembler<br> <br>assembler=VectorAssembler(inputCols=[&#39;Age&#39;,&#39;Total_Purchase&#39;,&#39;Account_Manager&#39;,&#39;Years&#39;,&#39;Num_Sites&#39;],outputCol=&#39;features&#39;)<br> <br>output_data=assembler.transform(input_data)</pre><h4>Schema of Output Data</h4><p>Let’s have a look at the schema of the output data.</p><pre>output_data.printSchema()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*6JAjxKZJ8blstVSJwJ4jUQ.png" /></figure><p>As you guys can see, we have a features column here, based on which the Classification will occur.</p><h4>Using Logistic Regression on the data</h4><pre>final_data=output_data.select(&#39;features&#39;,&#39;churn&#39;)         //creating final data with only 2 columns<br> <br>train,test=final_data.randomSplit([0.7,0.3])          //splitting data<br> <br>model=LogisticRegression(labelCol=&#39;churn&#39;)           //creating model<br> <br>model=model.fit(train)        //fitting model on training dataset<br> <br>summary=model.summary<br> <br>summary.predictions.describe().show()         //summary of the predictions on training data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*hAg__sAgT3DG-MOU5Byf-w.png" /></figure><h4>Importing BinaryClassificationEvaluator Library and Testing</h4><p>The evaluation of binary classifiers compares two methods of assigning a binary attribute, one of which is usually a standard method and the other is being investigated. There are many metrics that can be used to measure the performance of a classifier or predictor; different fields have different preferences for specific metrics due to different goals.</p><pre>from pyspark.ml.evaluation import BinaryClassificationEvaluator predictions=model.evaluate(test)</pre><p>Next, we’ll create an evaluator and use the Binary Classification Evaluator to predict the churn.</p><pre>evaluator=BinaryClassificationEvaluator(rawPredictionCol=&#39;prediction&#39;,labelCol=&#39;churn&#39;)<br> <br>evaluator.evaluate(predictions.predictions)<br> <br>model1=LogisticRegression(labelCol=&#39;churn&#39;)<br>model1=model1.fit(final_data)<br> <br>test_data=assembler.transform(test_data)</pre><h4>Finding Results</h4><p>Now we are going to use the model to evaluate the new data</p><pre>results=model1.transform(test_data) results.select(&#39;Company&#39;,&#39;prediction&#39;).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*5qhnd64oxL8fnFsl92auCQ.png" /></figure><p>So here we can see the potential client that can leave the organization and with this analysis, we come to the end of this article.</p><p>I hope you enjoyed this article. If you are reading this, Congratulations! You are no longer a newbie to PySpark MLlib. Try out these simple example on your systems now.</p><p>If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to <a href="https://www.edureka.co/blog/?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=pyspark-mllib-tutorial">Edureka’s official site.</a></p><p>Do look out for other articles in this series which will explain the various other aspects of PySpark.</p><blockquote>1. <a href="https://medium.com/edureka/pyspark-tutorial-87d41dab9657">PySpark Tutorial</a></blockquote><blockquote>2.<a href="https://medium.com/edureka/pyspark-dataframe-tutorial-9335f3d09b4"> PySpark Dataframe Tutorial</a></blockquote><blockquote>3. <a href="https://medium.com/edureka/pyspark-rdd-ef9edd060a25">RDDs in PySpark</a></blockquote><blockquote>4.<a href="https://medium.com/edureka/pyspark-programming-e007e68fbccb"> PySpark Programming</a></blockquote><p><em>Originally published at </em><a href="https://www.edureka.co/blog/pyspark-mllib-tutorial/"><em>www.edureka.co</em></a><em> on July 24, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=759391dbb08a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edureka/pyspark-mllib-tutorial-759391dbb08a">Customer Churn Prediction Using PySpark MLlib</a> was originally published in <a href="https://medium.com/edureka">Edureka</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn PySpark Dataframes With FIFA World Cup & Superheroes Dataset]]></title>
            <link>https://medium.com/edureka/pyspark-dataframe-tutorial-9335f3d09b4?source=rss-a1c3bc4dc33f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9335f3d09b4</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[spark-dataframe]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Kislay Keshari]]></dc:creator>
            <pubDate>Thu, 12 Jul 2018 14:20:17 GMT</pubDate>
            <atom:updated>2019-06-05T14:58:28.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*y-wETBpjKYs57dh-gqtMLg.jpeg" /><figcaption>PySpark Dataframes Tutorial — Edureka</figcaption></figure><p>Dataframes is a buzzword in the Industry nowadays. People tend to use it with popular languages used for <a href="https://www.edureka.co/blog/what-is-data-analytics?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=pyspark-dataframe-tutorial">Data Analysis</a> like Python, Scala, and R. So, why is it that everyone is using it so much? Let’s understand this with our article. In this article I’ll be covering the following topics:</p><ul><li>What are Dataframes?</li><li>Why we need Dataframes?</li><li>Features of Dataframes</li><li>PySpark Dataframe Sources</li><li>Dataframe Creation</li><li>Pyspark Dataframes with FIFA World Cup &amp; Superheroes Dataset</li></ul><h3>What are Dataframes?</h3><p>Dataframes generally refers to a data structure, which is tabular in nature. It represents Rows, each of which consists of a number of observations. Rows can have a variety of data formats (<strong>Heterogeneous</strong>), whereas a column can have data of the same data type (<strong>Homogeneous</strong>). Data frames usually contain some metadata in addition to data; for example, column and row names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*y0u2-p4TITPVdodujURY9Q.jpeg" /></figure><p>We can say that Dataframes are nothing, but 2-Dimensional Data Structure, similar to an SQL table or a spreadsheet. Now let’s move ahead with this article and understand why exactly we need Pyspark Dataframe?</p><h3>Why do we need Dataframes?</h3><h4><strong>1.Processing Structured and Semi-Structured Data</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*dbGsEW9R3ZHPk76vXeU7ww.jpeg" /></figure><p>Dataframes are designed to process a <strong>large collection of structured as well as Semi-Structured data</strong>. Observations in Spark DataFrame are organized under named columns, which helps Apache Spark to understand the schema of a DataFrame. This helps Spark optimize execution plan on these queries. It can also handle <strong>Petabytes</strong> of data.</p><h4><strong>2.Slicing and Dicing</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*0fbl_qpz8evHo6slJVB91w.jpeg" /></figure><p>Data frame APIs usually supports elaborate methods for <strong>slicing-and-dicing</strong> the data. It includes operations such as “selecting” rows, columns, and cells by name or by number, filtering out rows, etc. Statistical data is usually very messy and contain lots of missing and wrong values and range violations. So a critically important feature of data frames is the explicit management of missing data.</p><h4><strong>3.Data Sources</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*u3O5QFdn71HGsMXB4vEGRw.jpeg" /></figure><p>DataFrame has support for a wide range of data format and sources, we’ll look into this later on in this article. They can take in data from various sources.</p><h4><strong>4.Support for Multiple Languages</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*_1KsnVxPUt1Ety4sfPFvBA.jpeg" /></figure><p>It has API support for different languages like Python, R, Scala, Java, which makes it easier to be used by people having different programming backgrounds.</p><h3>Features of Dataframes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*byLfPbYiOvqJKuvZmG1q8A.jpeg" /></figure><ul><li>Dataframes are <strong>Distributed</strong> in Nature, which makes it Fault Tolerant and Highly Available Data Structure.</li><li><strong>Lazy evaluation</strong> is an evaluation strategy which holds the evaluation of an expression until its value is needed. It avoids repeated evaluation. Lazy evaluation in Spark means that the execution will not start until an action is triggered. In Spark, the picture of lazy evaluation comes when Spark transformations occur.</li><li>Dataframes are <strong>Immutable</strong> in nature. By immutable I mean that it is an object whose state <strong>cannot be modified</strong> after it is created. But we can transform its values by applying a certain transformation, like in RDDs.</li></ul><h3>PySpark Dataframe Sources</h3><p>Dataframes in Pyspark can be created in multiple ways:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*P-fhGJBb_zMD4_LLnp2n2g.jpeg" /></figure><p>Data can be loaded in through a <strong>CSV, JSON, XML</strong> or a Parquet file. It can also be created using an existing<strong> RDD</strong> and through any other database, like <a href="https://www.edureka.co/blog/hive-tutorial?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=pyspark-dataframe-tutorial"><strong>Hive</strong></a> or <strong>Cassandra</strong> as well. It can also take in data from <a href="https://www.edureka.co/blog/hdfs-tutorial?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=pyspark-dataframe-tutorial">HDFS</a> or the local file system.</p><h3>Dataframe Creation</h3><p>Let’s move forward with this article and understand how to create Dataframes.</p><p>We’ll create Employee and Department instances.</p><pre>from pyspark.sql import *<br> <br>Employee = Row(&quot;firstName&quot;, &quot;lastName&quot;, &quot;email&quot;, &quot;salary&quot;)<br> <br>employee1 = Employee(&#39;Basher&#39;, &#39;armbrust&#39;, &#39;<a href="/service/mailto:bash@edureka.co">bash@edureka.co</a>&#39;, 100000)<br>employee2 = Employee(&#39;Daniel&#39;, &#39;meng&#39;, &#39;<a href="/service/mailto:daniel@stanford.edu">daniel@stanford.edu</a>&#39;, 120000 )<br>employee3 = Employee(&#39;Muriel&#39;, None, &#39;<a href="/service/mailto:muriel@waterloo.edu">muriel@waterloo.edu</a>&#39;, 140000 )<br>employee4 = Employee(&#39;Rachel&#39;, &#39;wendell&#39;, &#39;<a href="/service/mailto:rach_3@edureka.co">rach_3@edureka.co</a>&#39;, 160000 )<br>employee5 = Employee(&#39;Zach&#39;, &#39;galifianakis&#39;, &#39;<a href="/service/mailto:zach_g@edureka.co">zach_g@edureka.co</a>&#39;, 160000 )<br> <br>print(Employee[0])<br> <br>print(employee3)<br> <br>department1 = Row(id=&#39;123456&#39;, name=&#39;HR&#39;)<br>department2 = Row(id=&#39;789012&#39;, name=&#39;OPS&#39;)<br>department3 = Row(id=&#39;345678&#39;, name=&#39;FN&#39;)<br>department4 = Row(id=&#39;901234&#39;, name=&#39;DEV&#39;)</pre><p>Next, we’ll create a DepartmentWithEmployees instance from the Employee and Departments</p><pre>departmentWithEmployees1 = Row(department=department1, employees=[employee1, employee2, employee5]) departmentWithEmployees2 = Row(department=department2, employees=[employee3, employee4]) departmentWithEmployees3 = Row(department=department3, employees=[employee1, employee4, employee3]) departmentWithEmployees4 = Row(department=department4, employees=[employee2, employee3])</pre><p>Let’s create our Dataframe from the list of Rows</p><pre>departmentWithEmployees1 = Row(department=department1, employees=[employee1, employee2, employee5])<br>departmentWithEmployees2 = Row(department=department2, employees=[employee3, employee4])<br>departmentWithEmployees3 = Row(department=department3, employees=[employee1, employee4, employee3])<br>departmentWithEmployees4 = Row(department=department4, employees=[employee2, employee3])</pre><h3>Pyspark Dataframes Example 1: FIFA World Cup Dataset</h3><p>Here we have taken FIFA World Cup Players Dataset. We are going to load this data which is in CSV format into a dataframe and then we’ll learn about the different transformations and actions that can be performed on this dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*j4qbETuMc05rL9Y6fBNcRw.jpeg" /></figure><h4>Reading Data from CSV file</h4><p>Let’s load the data from a CSV file. Here we are going to use the <strong>spark.read.csv</strong> method to load the data into a dataframe fifa_df. The actual method is <strong>spark.read.format[csv/json]</strong>.</p><pre>fifa_df = spark.read.csv(&quot;path-of-file/fifa_players.csv&quot;, inferSchema = True, header = True) <br>fifa_df.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*Ose97nrPbegvwfqI82G3Sg.jpeg" /></figure><h4>Schema of Dataframe</h4><p>To have a look at the schema ie. the structure of the dataframe, we’ll use the <strong>printSchema</strong> method. This will give us the different columns in our dataframe along with the data type and the nullable conditions for that particular column.</p><pre>fifa_df.printSchema()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*f63hD3bdmsCzHrr3YquQRg.jpeg" /></figure><h4>Column Names and Count (Rows and Column)</h4><p>When we want to have a look at the names and a count of the number of Rows and Columns of a particular Dataframe, we use the following methods.</p><pre>fifa_df.columns //Column Names <br>fifa_df.count() // Row Count <br>len(fifa_df.columns) //Column Count</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*o5v9YbZ4lszAmiNEf6LcDw.jpeg" /></figure><pre>37784 <br>8</pre><h4>Describing a Particular Column</h4><p>If we want to have a look at the summary of any particular column of a Dataframe, we use the <strong>describe</strong> method. This method gives us the statistical summary of the given column, if not specified, it provides the statistical summary of the dataframe.</p><pre>fifa_df.describe(&#39;Coach Name&#39;).show() fifa_df.describe(&#39;Position&#39;).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*lhwHE-sRVdqoMKSF4xTu5w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*x2eroB8PsdH1-CrQCUTfQA.jpeg" /></figure><h4>Selecting Multiple Columns</h4><p>If we want to select particular columns from the dataframe, we use the <strong>select</strong> method.</p><pre>fifa_df.select(&#39;Player Name&#39;,&#39;Coach Name&#39;).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*spnKZdeBYR-OL_UAyBVvPw.jpeg" /></figure><h4>Selecting Distinct Multiple Columns</h4><pre>fifa_df.select(&#39;Player Name&#39;,&#39;Coach Name&#39;).distinct().show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*iZdHM6n3rS-eaxDJzCqb5g.jpeg" /></figure><h4>Filtering Data</h4><p>In order to filter the data, according to the condition specified, we use the <strong>filter</strong> command. Here we are filtering our dataframe based on the condition that Match ID must be equal to 1096 and then we are calculating how many records/rows are there in the filtered output.</p><pre>fifa_df.filter(fifa_df.MatchID==&#39;1096&#39;).show() fifa_df.filter(fifa_df.MatchID==&#39;1096&#39;).count() //to get the count</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*sLdCr8j0n0qy-WNqFj2WSQ.jpeg" /></figure><h4>Filtering Data (Multiple Parameters)</h4><p>We can filter our data based on multiple conditions (AND or OR)</p><pre>fifa_df.filter((fifa_df.Position==&#39;C&#39;) &amp;&amp; (fifa_df.Event==&quot;G40&#39;&quot;)).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*AZOlZ7OfRNf613XBNTmRmQ.jpeg" /></figure><h4>Sorting Data (OrderBy)</h4><p>To sort the data we use the <strong>OrderBy</strong> method. By Default, it sorts in ascending order, but we can change it to descending order as well.</p><pre>fifa_df.orderBy(fifa_df.MatchID).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*XTEyC9s2xlgiyYqYfbx1tg.jpeg" /></figure><h3>PySpark Dataframes Example 2: Superheros Dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*hDDh6upUXimr9MofPt_fsw.jpeg" /></figure><h4>Loading the data</h4><p>Here we will load the data in the same way as we did earlier.</p><pre>Superhero_df = spark.read.csv(&quot;path-of file/superheros.csv&quot;, inferSchema = True, header = True) <br>Superhero_df.show(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*5NjsTM8PcOWpNYPmS6Yn-Q.jpeg" /></figure><h4>Filtering the Data</h4><pre>Superhero_df.filter(Superhero_df.Gender == &#39;Male&#39;).count() //Male Heros Count <br>Superhero_df.filter(Superhero_df.Gender == &#39;Female&#39;).count() //Female Heros Count</pre><h4>Grouping the Data</h4><p><strong>GroupBy</strong> is used to group the dataframe based on the column specified. Here, we are grouping the dataframe based on the column Race and then with the <strong>count</strong> function, we can find the count of the particular race.</p><pre>Race_df = Superhero_df.groupby(&quot;Race&quot;)\<br>.count()\<br>.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*cUzB05OglE1tYzNZSRaE6Q.jpeg" /></figure><h4>Performing SQL Queries</h4><p>We can also pass SQL queries directly to any dataframe, for that we need to create a table from the dataframe using the <strong>registerTempTable</strong> method and then use the <strong>sqlContext.sql()</strong> to pass the SQL queries.</p><pre>Superhero_df.registerTempTable(&#39;superhero_table&#39;)<br>sqlContext.sql(&#39;select * from superhero_table&#39;).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*5NjsTM8PcOWpNYPmS6Yn-Q.jpeg" /></figure><pre>sqlContext.sql(‘select distinct(Eye_color) from superhero_table’).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*FbXHCXye_XEvvnZViHJr5A.jpeg" /></figure><pre>sqlContext.sql(&#39;select distinct(Eye_color) from superhero_table&#39;).count()</pre><p>23</p><pre>sqlContext.sql(‘select max(Weight) from superhero_table’).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*WmJuqSAlJMnCLnpkUpOYwQ.jpeg" /></figure><p>If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to <a href="https://www.edureka.co/blog/?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=pyspark-dataframe-tutorial">Edureka’s official site.</a></p><p>Do look out for other articles in this series which will explain the various other aspects of PySpark.</p><blockquote>1. <a href="https://medium.com/edureka/pyspark-tutorial-87d41dab9657">PySpark Tutorial</a></blockquote><blockquote>2. <a href="https://medium.com/edureka/pyspark-rdd-ef9edd060a25">RDDs in PySpark</a></blockquote><blockquote>3. <a href="https://medium.com/edureka/pyspark-mllib-tutorial-759391dbb08a">PySpark MLlib Tutorial</a></blockquote><blockquote>4. <a href="https://medium.com/edureka/pyspark-programming-e007e68fbccb">PySpark Programming</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9335f3d09b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edureka/pyspark-dataframe-tutorial-9335f3d09b4">Learn PySpark Dataframes With FIFA World Cup &amp; Superheroes Dataset</a> was originally published in <a href="https://medium.com/edureka">Edureka</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PySpark Tutorial - Learn Apache Spark Using Python]]></title>
            <link>https://medium.com/edureka/pyspark-tutorial-87d41dab9657?source=rss-a1c3bc4dc33f------2</link>
            <guid isPermaLink="false">https://medium.com/p/87d41dab9657</guid>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[spark-rdd]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Kislay Keshari]]></dc:creator>
            <pubDate>Thu, 28 Jun 2018 06:23:52 GMT</pubDate>
            <atom:updated>2019-06-05T15:06:09.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*CfeqJDg8gBVBhhhTINmeFw.png" /><figcaption>PySpark Tutorial — Edureka</figcaption></figure><p>In a world where data is being generated at such an alarming rate, the correct analysis of that data at the correct time is very useful. One of the most amazing framework to handle big data in real-time and perform the analysis is <a href="https://www.edureka.co/blog/spark-tutorial?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=pyspark-tutorial">Apache Spark</a>. Together,<strong> </strong><em>Python for Spark</em> or PySpark is one of the most sought-after certification courses, giving Scala for Spark a run for its money. So in this article, I’ll discuss the following topics:</p><ul><li>What is PySpark?</li><li>PySpark in the Industry</li><li>Why Go for Python?</li><li>Spark RDDs</li><li>Machine Learning with PySpark</li></ul><h3>What is PySpark?</h3><p>Apache Spark is a fast cluster computing framework which is used for processing, querying and analyzing Big data. Being based on In-memory computation, it has an advantage over several other Big Data Frameworks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*SPaFcajWvoZxSbLIzAcexw.png" /></figure><p>Originally written in Scala Programming Language, the open source community has developed an amazing tool to support Python for Apache Spark. PySpark helps data scientists interface with RDDs in Apache Spark and Python through its library <strong>Py4j. </strong>There are many features that make PySpark a better framework than others:</p><ul><li><strong>Speed: </strong>It is 100x faster than traditional large-scale data processing frameworks</li><li><strong>Powerful Caching:</strong> Simple programming layer provides powerful caching and disk persistence capabilities</li><li><strong>Deployment:</strong> Can be deployed through Mesos, Hadoop via Yarn, or Spark’s own cluster manager</li><li><strong>Real Time:</strong> Real-time computation &amp; low latency because of in-memory computation</li><li><strong>Polyglot:</strong> Supports programming in Scala, Java, Python and R</li></ul><p>Let’s move ahead with our article and see where is Spark used in the industry.</p><h3>PySpark in the Industry</h3><p>Every<a href="https://www.edureka.co/blog/big-data-applications-revolutionizing-various-domains?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=pyspark-tutorial"> Industry revolves around Big Data</a> and where there’s Big Data there’s Analysis involved. So let’s have a look at the various industries where Apache Spark is used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*wMmkz_YYevsCizlDkgJrNA.jpeg" /></figure><p><strong>Media</strong> is one of the biggest industry growing towards online streaming. <strong>Netflix</strong> uses Apache Spark for real-time stream processing to provide personalized online recommendations to its customers. It processes <strong>450 billion</strong> events per day which flow to server-side applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ynWyP1lI4OWSMUlbGhXahQ.jpeg" /></figure><p><strong>Finance</strong> is another sector where Apache Spark’s Real-Time processing plays an important role. Banks are using Spark to access and analyze the social media profiles, to gain insights which can help them make right business decisions for <strong>credit risk assessment</strong>, targeted ads, and customer segmentation. <strong>Customer Churn</strong> is also reduced using Spark. <strong>Fraud Detection</strong> is one of the most widely used areas of Machine Learning where Spark is involved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*GfEGj-uOr7sLrEFEen2oUQ.jpeg" /></figure><p><strong>Healthcare</strong> providers are using Apache Spark to <strong>Analyse patient records</strong> along with past clinical data to identify which patients are likely to face health issues after being discharged from the clinic. Apache Spark is used in <strong>Genomic Sequencing</strong> to reduce the time needed to process genome data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ua4yh-YDhr8JNS95prsJyg.jpeg" /></figure><p><strong>Retail and E-commerce</strong> is an industry where one can’t imagine it running without the use of Analysis and Targeted Advertising. One of the largest E-commerce platform today <strong>Alibaba </strong>runs some of the largest Spark Jobs in the world in order to analyse petabytes of data. Alibaba performs <strong>feature extraction</strong> in image data. <strong>eBay </strong>uses Apache Spark to provide <strong>Targeted Offers</strong>, enhance customer experience and optimize overall performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*ZQ8jXZWeGIhAcHH7hulhSw.jpeg" /></figure><p><strong>Travel</strong> Industries also use Apache Spark. <strong>TripAdvisor</strong>, a leading travel website that helps users plan a perfect trip is using Apache Spark to speed up its <strong>personalized customer recommendations</strong>.TripAdvisor uses apache spark to provide advice to millions of travelers by <strong>comparing hundreds of websites</strong> to find the best hotel prices for its customers.</p><p>An important aspect of this PySpark Tutorial is to understand why we need to go for Python? Why not Java, Scala or R?</p><h3>Why Go for Python?</h3><p><strong>Easy to Learn:</strong> For programmers Python is comparatively easier to learn because of its syntax and standard libraries. Moreover, it’s a dynamically typed language, which means RDDs can hold objects of multiple types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*0-pD1Aukai3-_61hoH21bg.png" /></figure><p><strong>A vast set of Libraries: </strong>Scala does not have sufficient data science tools and libraries like Python for machine learning and natural language processing. Moreover, Scala lacks good visualization and local data transformations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*_AcK_HFsVCABtannoTv-8w.png" /></figure><p><strong>Huge Community Support: </strong>Python has a global community with millions of developers that interact online and offline in thousands of virtual and physical locations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*wuvxLiTtEAgrDecwWAFOYw.png" /></figure><p>One of the most important topics in this PySpark Tutorial is the use of RDDs. Let’s understand what are RDDs</p><h3>Spark RDDs</h3><p>When it comes to iterative distributed computing, i.e. processing data over multiple jobs in computations, we need to reuse or share data among multiple jobs. Earlier frameworks like Hadoop had problems while dealing with multiple operations/jobs like</p><ul><li>Storing Data in Intermediate Storage such as HDFS</li><li>Multiple I/O jobs make the computations slow</li><li>Replications and serializations which in turn makes the process even slower</li></ul><p>RDDs try to solve all the problems by enabling fault-tolerant distributed In-memory computations. RDD is short for <strong>Resilient Distributed Datasets. </strong>RDD is a distributed memory abstraction which lets programmers perform in-memory computations on large clusters in a fault-tolerant manner. They are the <strong>read-only collection of objects</strong> partitioned across a set of machines that can be rebuilt if a partition is lost. There are several operations performed on RDDs:</p><ul><li><strong>Transformations: </strong>Transformations create a new dataset from an existing one. Lazy Evaluation</li><li><strong>Actions: </strong>Spark forces the calculations for execution only when actions are invoked on the RDDs</li></ul><p>Let’s understand a few Transformations, Actions and Functions</p><h4><strong>Reading a file and Displaying Top n elements:</strong></h4><pre>rdd = sc.textFile(&quot;file:///home/edureka/Desktop/Sample&quot;) <br>rdd.take(n)</pre><p><strong>Output:</strong></p><pre>[u&#39;Deforestation is arising as the main environmental and social issue which has now taken the form of more than a powerful demon. &#39;,<br> u&#39;We must know about the causes, effects and ways to solve the problems arisen because of the deforestation. &#39;,<br> u&#39;We have provided many paragraphs, long and short essay on deforestation in order to help your kids and children to get aware about the problem as well as get participated in the essay writing competition in the school or outside the school. &#39;,<br> u&#39;You can select any deforestation essay given below according to the class standard. &#39;,<br> u&#39;Deforestation is arising as the major global problem to the society and environment.&#39;]</pre><h4><strong>Converting to lowercase and Splitting:(Lower and Split)</strong></h4><pre>def Func(lines):<br>lines = lines.lower()<br>lines = lines.split()<br>return lines<br>rdd1 = rdd.map(Func)<br> <br>rdd1.take(5)</pre><p><strong>Output:</strong></p><pre>[[u&#39;deforestation&#39;,<br>  u&#39;is&#39;,<br>  u&#39;arising&#39;,<br>  u&#39;as&#39;,<br>  u&#39;the&#39;,<br>  u&#39;main&#39;,<br>  u&#39;environmental&#39;,<br>  u&#39;and&#39;,<br>  u&#39;social&#39;,<br>  u&#39;issue&#39;,<br>  u&#39;which&#39;,<br>  u&#39;has&#39;,<br>  u&#39;now&#39;,<br>  u&#39;taken&#39;,<br>.....<br>.<br>.<br>.<br>]</pre><h4><strong>Removing StopWords:(Filter)</strong></h4><pre>stop_words = [&#39;a&#39;,&#39;all&#39;,&#39;the&#39;,&#39;as&#39;,&#39;is&#39;,&#39;am&#39;,&#39;an&#39;,&#39;and&#39;,&#39;be&#39;,&#39;been&#39;,&#39;from&#39;,&#39;had&#39;,&#39;I&#39;,&#39;I’d&#39;,&#39;why&#39;,&#39;with&#39;]<br>rdd2 = rdd1.filter(lambda z: z not in stop_words)<br>rdd2.take(10)</pre><p><strong>Output:</strong></p><pre>[u&#39;deforestation&#39;,<br> u&#39;arising&#39;,<br> u&#39;main&#39;,<br> u&#39;environmental&#39;,<br> u&#39;social&#39;,<br> u&#39;issue&#39;,<br> u&#39;which&#39;,<br> u&#39;has&#39;,<br> u&#39;now&#39;,<br> u&#39;taken&#39;]</pre><h4><strong>Sum of Numbers from 1 to 500: (Reduce)</strong></h4><pre>sum_rdd = sc.parallelize(range(1,500))<br>sum_rdd.reduce(lambda x,y: x+y)</pre><p><strong>Output:</strong></p><pre>124750</pre><h3>Machine Learning with PySpark</h3><p>Continuing our article, let’s analyze some BasketBall Data and do some future Prediction. So, here we are going to use the Basketball Data of all the players of NBA since <strong>1980 </strong>[year of introduction of 3 Pointers].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*C9yydLywrMRA2v7oZ8xE3A.png" /></figure><h4><strong>Data Loading:</strong></h4><pre>df = spark.read.option(&#39;header&#39;,&#39;true&#39;)\<br>.option(&#39;inferSchema&#39;,&#39;true&#39;)<br>.csv(&quot;file:///home/edureka/Downloads/season_totals.csv&quot;)</pre><h4><strong>Printing Columns:</strong></h4><pre>print(df.columns)</pre><p><strong>Output:</strong></p><pre>[&#39;_c0&#39;, &#39;player&#39;, &#39;pos&#39;, &#39;age&#39;, &#39;team_id&#39;, &#39;g&#39;, &#39;gs&#39;, &#39;mp&#39;, &#39;fg&#39;, &#39;fga&#39;, &#39;fg_pct&#39;, &#39;fg3&#39;, &#39;fg3a&#39;, &#39;fg3_pct&#39;, &#39;fg2&#39;, &#39;fg2a&#39;, &#39;fg2_pct&#39;, &#39;efg_pct&#39;, &#39;ft&#39;, &#39;fta&#39;, &#39;ft_pct&#39;, &#39;orb&#39;, &#39;drb&#39;, &#39;trb&#39;, &#39;ast&#39;, &#39;stl&#39;, &#39;blk&#39;, &#39;tov&#39;, &#39;pf&#39;, &#39;pts&#39;, &#39;yr&#39;]</pre><h4><strong>Sorting Players(OrderBy) and toPandas:</strong></h4><p>Here we are sorting players based on point scored in a season.</p><pre>df.orderBy(&#39;pts&#39;,ascending = False).limit(10).toPandas()[[&#39;yr&#39;,&#39;player&#39;,&#39;age&#39;,&#39;pts&#39;,&#39;fg3&#39;]]</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*OV-yfjvd1p6k0EfFx5_4GQ.png" /></figure><h4><strong>Using DSL and matplotlib:</strong></h4><p>Here we are analyzing the average number of <strong>3 point attempts</strong> for each season in a time limit of <strong>36 min</strong>[an interval corresponding to an approximate full NBA game with adequate rest]. We compute this metric using the number of 3-point field goal attempts (fg3a) and minutes played (mp) and then plot the result using <strong>matlplotlib</strong>.</p><pre>from pyspark.sql.functions import col<br>fga_py = df.groupBy(&#39;yr&#39;)\<br>.agg({&#39;mp&#39; : &#39;sum&#39;, &#39;fg3a&#39; : &#39;sum&#39;})<br>.select(col(&#39;yr&#39;), (36*col(&#39;sum(fg3a)&#39;)/col(&#39;sum(mp)&#39;)).alias(&#39;fg3a_p36m&#39;))\<br>.orderBy(&#39;yr&#39;)<br> <br>from matplotlib import pyplot as plt<br>import seaborn as sns<br>plt.style.use(&#39;fivethirtyeight&#39;)<br> <br> <br>_df = fga_py.toPandas()<br>plt.plot(_df.yr,_df.fg3a_p36m, color = &#39;#CD5C5C&#39;)<br>plt.xlabel(&#39;Year&#39;)<br>_=plt.title(&#39;Player average 3-point attempts (per 36 minutes)&#39;)<br>plt.annotate(&#39;3 pointer introduced&#39;, xy=(1980, .5), xytext=(1981, 1.1), fontsize = 9,<br>arrowprops=dict(facecolor=&#39;grey&#39;, shrink=0, linewidth = 2))<br>plt.annotate(&#39;NBA moved in 3-point line&#39;, xy=(1996, 2.4), xytext=(1991.5, 2.7), fontsize = 9,<br>arrowprops=dict(facecolor=&#39;grey&#39;, shrink=0, linewidth = 2))<br>plt.annotate(&#39;NBA moved back\n3-point line&#39;, xy=(1998, 2.), xytext=(1998.5, 2.4), fontsize = 9, arrowprops=dict(facecolor=&#39;grey&#39;, shrink=0, linewidth = 2))</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*694g6lGcBx8Zs4STE2Q2Zg.png" /></figure><h4><strong>Linear Regression and VectorAssembler:</strong></h4><p>We can fit a linear regression model to this curve to model the number of shot attempts for the next 5 years. We have to transform our data using the VectorAssembler function to a single column. This is a <strong>requirement</strong> for the linear regression API in MLlib.</p><pre>from pyspark.ml.feature import VectorAssembler<br>t = VectorAssembler(inputCols=[&#39;yr&#39;], outputCol = &#39;features&#39;)<br>training = t.transform(fga_py)\<br>.withColumn(&#39;yr&#39;,fga_py.yr)\<br>.withColumn(&#39;label&#39;,fga_py.fg3a_p36m)<br>training.toPandas().head()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*tCopuHMAmD0NFpAhqY3LjQ.png" /></figure><h4><strong>Building Model:</strong></h4><p>We then build our linear regression model object using our transformed data.</p><pre>from pyspark.ml.regression import LinearRegression <br>lr = LinearRegression(maxIter=10)<br>model = lr.fit(training)</pre><h4><strong>Applying Trained Model to Dataset:</strong></h4><p>We apply our trained model object model to our original training set along with 5 years of future data</p><pre>from pyspark.sql.types import Row<br> <br># apply model for the 1979-80 season thru 2020-21 season<br>training_yrs = training.select(&#39;yr&#39;).rdd.map(lambda x: x[0]).collect()<br>training_y = training.select(&#39;fg3a_p36m&#39;).rdd.map(lambda x: x[0]).collect()<br>prediction_yrs = [2017, 2018, 2019, 2020, 2021]<br>all_yrs = training_yrs + prediction_yrs<br> <br># built testing DataFrame<br>test_rdd = sc.parallelize(all_yrs)<br>row = Row(&#39;yr&#39;)&amp;amp;amp;lt<br>all_years_features = t.transform(test_rdd.map(row).toDF())<br> <br># apply linear regression model<br>df_results = model.transform(all_years_features).toPandas()</pre><h4><strong>Plotting the final Prediction:</strong></h4><p>We can then plot our results and save the graph in a specified location.</p><pre>plt.plot(df_results.yr,df_results.prediction, linewidth = 2, linestyle = &#39;--&#39;,color = &#39;#224df7&#39;, label = &#39;L2 Fit&#39;)<br>plt.plot(training_yrs, training_y, color = &#39;#f08080&#39;, label = None)<br>plt.xlabel(&#39;Year&#39;)<br>plt.ylabel(&#39;Number of attempts&#39;)<br>plt.legend(loc = 4)<br>_=plt.title(&#39;Player average 3-point attempts (per 36 minutes)&#39;)<br>plt.tight_layout()<br>plt.savefig(&quot;/home/edureka/Downloads/Images/REGRESSION.png&quot;)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*VtWwZut0kjgsSJTmxFR5sQ.png" /></figure><p>And with this graph, we come to the end of this article.</p><p>So This is it, Guys!</p><p>I hope you guys got an idea of what PySpark is, why Python is best suited for Spark, the RDDs and a glimpse of Machine Learning with Pyspark in this article. Congratulations, you are no longer a Newbie to PySpark.</p><p>If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to <a href="https://www.edureka.co/blog/?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=pyspark-tutorial">Edureka’s official site</a>.</p><p>Do look out for other articles in this series which will explain the various other aspects of PySpark.</p><blockquote>1. <a href="https://medium.com/edureka/pyspark-dataframe-tutorial-9335f3d09b4">PySpark Dataframe Tutorial</a></blockquote><blockquote>2. <a href="https://medium.com/edureka/pyspark-rdd-ef9edd060a25">RDDs in PySpark</a></blockquote><blockquote>3. <a href="https://medium.com/edureka/pyspark-mllib-tutorial-759391dbb08a">PySpark MLlib Tutorial</a></blockquote><blockquote>4. <a href="https://medium.com/edureka/pyspark-programming-e007e68fbccb">PySpark Programming</a></blockquote><p><em>Originally published at </em><a href="https://www.edureka.co/blog/pyspark-tutorial/"><em>www.edureka.co</em></a><em> on June 28, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87d41dab9657" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edureka/pyspark-tutorial-87d41dab9657">PySpark Tutorial - Learn Apache Spark Using Python</a> was originally published in <a href="https://medium.com/edureka">Edureka</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>