You are on page 1of 35

MySQL Aggregate Function The group (aggregate) functions that operate on set of values.

Sometimes we need information that is not actually stored in the database but we can compute it by operating on some set of stored data. Aggregate functions can be used for this purpose. Aggregate functions perform a calculation on a set of records and return a single value. An aggregate function ignores NULL values when it performs the calculation except the COUNT function. The aggregate functions are often used with GROUP BY clause in the SELECT statement. In the following section, we will discuss the most common aggregate functions in MySQL. The following are the Aggregate function: Name AVG() BIT_AND() BIT_OR() BIT_XOR() COUNT(DISTINCT) COUNT() GROUP_CONCAT() MAX() MIN() STD() STDDEV_POP() STDDEV_SAMP() STDDEV() SUM() VAR_POP() VAR_SAMP() VARIANCE() Description It Return the average value of the argument It Return bitwise and It Return bitwise or It Return bitwise xor It Return the count of a number of different values It Return a count of the number of rows returned It Return a concatenated string It Return the maximum value It Return the minimum value It Return the population standard deviation It Return the population standard deviation It Return the sample standard deviation It Return the population standard deviation It Return the sum It Return the population standard variance It Return the sample variance It Return the population standard variance

The 'COUNT' function is used to count the all rows of the table.

Query Output

SELECT COUNT(*) FROM employee; +----------+ | COUNT(*) | +----------+ |8 | +----------+

The 'MIN' function is used to find the minimum value of the specific field and the 'MAX' function is used to find the maximum value of the field. Query SELECT designation, MIN(salary), MAX(salary) FROM employee GROUP BY designation;

+----------------------+-------------+-------------+ | designation | MIN(salary) | MAX(salary) | +----------------------+-------------+-------------+ Output | content writer | 110 | 110 | | graphic designer | 50 | 120 | | programmer | 105 | 160 | | sr. graphic designer | 101 | 101 | +----------------------+-------------+-------------+ The 'SUM' function is used to sum all the values of the specific column of the table. Query select SUM(salary) FROM employee;

+-------------+ Output | SUM(salary) | +-------------+ | 926 | +-------------+ SUM Function SUM function returns the sum of all values in an expression. To get the total sales of each product, we can use the SUM function and GROUP BY clause as follows: SELECT productCode,sum(priceEach * quantityOrdered) total FROM orderdetails GROUP by productCode productCode total ----------- --------S10_1678 90157.77 S10_1949 190017.96 S10_2016 109998.82 S10_4698 170686

S10_4757 127924.32 S10_4962 123123.01 S12_1099 161531.48 To see the result more detail, we can join the orderdetails table with the product table. SELECT P.productCode,P.productName,SUM(priceEach * quantityOrdered) total FROM orderdetails O INNER JOIN products P ON O.productCode=P.productCode GROUP by productCode ORDER BY total productCode productName total ----------- ------------------------------------------- --------S24_1937 1939 Chevrolet Deluxe Coupe 28052.94 S24_3969 1936 Mercedes Benz 500k Roadster 29763.39 S24_2972 1982 Lamborghini Diablo 30972.87 S24_2840 1958 Chevy Corvette Limited Edition 31627.96 S32_2206 1982 Ducati 996 R 33268.76 S24_2022 1938 Cadillac V-16 Presidential Limousine 38449.09 S50_1341 1930 Buick Marquette Phaeton 41599.24 S24_1628 1966 Shelby Cobra 427 S/C 42015.54 S72_1253 Boeing X-32A JSF 42692.53 AVG Function AVG is used to calculate average value of an expression. It ignores NULL values. AVG(expression) AVG function is used to calculate the average price of all products by executing the following query: SELECT AVG(buyPrice) average_buy_price FROM Products average_buy_price ----------------54.395181818182 MAX and MIN Function MAX and MIN function returns the maximum and minimum values of a set of values in expression. MAX(expression) For example, we can use MIN and MAX functions to retrieve the highest and lowest-price products as follows: SELECT MAX(buyPrice) highest_price, MIN(buyPrice) lowest_price FROM Products highest_price lowest_price ------------- -----------103.42 15.91 COUNT Function

The COUNT function returns the number of the items in expression. You can use the COUNT function to get the number of products in the products table as follows: SELECT COUNT(*) AS Total FROM products Total -----110 Ordering: order table using JDBC application ORDER BY Clause : There may be times when a specific order is required in a SQL query which cannot be done using either ASC or DESC or using a special sort field. MySQL has a ORDER BY FIELD function which can be used to do this. Using the FIELD( ) function in the ORDER BY clause we can achieve this. It works by specifying the column to sort by and then the values to sort in order. For example: SELECT * FROM fruit ORDER BY FIELD(name, 'Banana', 'Apple', 'Pear', 'Orange'), variety; The resulting data from the example table looks like this: +----------+--------+---------------------+ | fruit_id | name | variety | +----------+--------+---------------------+ | 11 | Banana | Burro | | 12 | Banana | Cavendish | | 10 | Banana | Plantain | | 6 | Apple | Cox's Orange Pippin | | 7 | Apple | Granny Smith | | 1 | Apple | Red Delicious | | 8 | Pear | Anjou |

Sort the table record either in ascending order or in descending order according to any field by using ORDER BY Clause. It manages your table records in sorted order of specified column. When You write only 'ORDER BY column_name' , by default it returns records sorted in ascending order. You can also use "asc" for ascending order. For descending order use 'desc' as 'ORDER BY column_name desc' Example : In this example we are arranging student records in descending order of roll_no . package jdbc; import java.sql.Connection; import java.sql.DriverManager;

import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; class SortingRecords{ public static void main(String[] args){ System.out.println("Sorting rocords of table in JDBC..."); Connection con = null; Statement statement = null; ResultSet rs = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "students"; String driverName = "com.mysql.jdbc.Driver"; String userName = "root"; String password = "root"; try { Class.forName(driverName); // Connecting to the database con = DriverManager.getConnection(url + dbName, userName, password); try { statement = con.createStatement(); // Using ORDER BY Clause String sql = "SELECT * FROM student ORDER BY roll_no desc"; rs = statement.executeQuery(sql); System.out.println("RollNo\tName\tCourse"); System.out.println("----------------------"); while (rs.next()) { int roll = rs.getInt("roll_no"); String name = rs.getString("name"); String course = rs.getString("course"); System.out.println(roll + "\t" + name + "\t" + course); }

} catch (SQLException e) { System.out.println(e); } con.close(); } catch (Exception e) { e.printStackTrace(); } } } Output : Sorting rocords of table in JDBC... RollNo Name Course ---------------------4 Andru MCA 3 Rose MCA 2 Mandy BCA 1 Ron MCA Mysql Group By Mysql Group By statement is conjecture term used with the aggregate functions to group the result-set by specified one or more columns. The MySQL GROUP BY clause is used with the SELECT statement to group rows into subgroups by the one or more values of columns or expressions. The MySQL GROUP BY clause is an optional part of the SELECT statement. It must appear after the FROM or WHERE clause. The MySQL GROUP BY clause consists of the GROUP BY keyword followed by a list of comma-separated columns or expressions. The following illustrates the MySQL GROUP BY clause syntax: SELECT c1,c2,... cn, aggregate_function(expression) FROM table WHERE where_conditions GROUP BY c1, c2, ... cn MySQL GROUP BY Examples Lets take a look at the orders table in the sample database. Suppose we want to group values of the order status into subgroups, we can use the following query: SELECT status FROM orders

GROUP BY status

We can see that the GROUP BY clause returns unique occurrences of status values. It is similar the SELECT DISTINCT query as follows: SELECT DISTINCT status FROM orders MySQL GROUP BY with aggregate functions The aggregate functions allow you to perform calculation of a set of records and return a single value. The most common aggregate functions are SUM, AVG, MAX, MIN and COUNT. The aggregate functions are used with MySQL GROUP BY clause to perform calculation on each subgroup and return a single value for each subgroup. Suppose you want to know how many orders in each status, you can use the COUNT function as follows: SELECT status, count(*) FROM orders GROUP BY status

MySQL GROUP BY vs. ANSI SQL GROUP BY MySQL follows ANSI SQL. However, MySQL give you more flexibility when using GROUP BY clause: In ANSI SQL, you must list all columns that you use in the SELECT clause in the GROUP BY clause. MySQL does not have this restriction. MySQL allows you to have additional columns in the SELECT clause that are not in the GROUP BY clause. MySQL also allows you to sort the group order in which the results are returned. The default order is ascending.

If you want to see the status and count of orders in the example above in the descending order, you can use the following query: SELECT status, count(*) FROM orders GROUP BY status DESC;

DESC in the GROUP BY clause to sort the status in descending order. MySQL Select Statement In this lesson you will be learn how to use SELECT statement in MySQL and you can also learn how to use SELECT statement with WHERE clause. The SELECT statement is used to retrieve the records from the table. There are some keywords uses in SELECT statement that are described in the following table Keywords SELECT FROM WHERE GROUP BY HAVING ORDER BY LIMIT Description SELECT statement is used to retrieve fields from one or more tables. Tables containing to the fields. The WHERE clause is used to describe the criteria to restrict the records retrieved. The GROUP BY clause is used to determine how the records should be grouped. HAVING clause used with GROUP BY to define the criteria for grouped records The ORDER BY clause is used to described the criteria for ordering the record. The LIMIT clause is used to restrict the limit of number of records retrieved.

The simple SELECT statement is used to retrieve the all records from table. By the following example you can retrieve the full list of Emp table. mysql> SELECT * FROM Emp;

If you want to retrieve only some fields from a table, then you have to provide a comma separated list of column names. By the following example you select Name, City and Age fields from the Emp table. mysql> SELECT Name, City, Age from EMP; The WHERE clause is used to limit the number of records. The comparison operators are used with WHERE clause to limit the number of records. Comparison operator?s list are given below: Operator = <> or != < <= > >= Like Between IN NOT IN Description Equal to Not equal to Less then Less then or equal to Greater then Greater then or equal to Used for comparing string Used for checking value between a range. Used to check values in a list Used to check the value is not in the list.

% Character - If you are working with Strings, then % character can be used as a wildcard. By the following example you can retrieve the all fields from Emp table where the Designation field contain the text, 'Manager'. mysql> SELECT * FROM Emp WHERE Designation LIKE '%Manager%'; _ character - The underscore character can be used as a placeholder. By the following example you can selects the all records from the table Emp, where the Name starts with ?R? followed by four characters. For this we have to use four underscores.

mysql> SELECT * FROM Emp WHERE Name LIKE 'R____'; BETWEEN Clause - The BETWEEN clause can be used with numbers, dates and text. The following example is used to retrieve all fields Emp table where the Salary is between 10000 AND 20000. mysql> SELECT * FROM Emp WHERE Salary BETWEEN 10000 AND 20000; OR Clause - The OR clause is used to check the values against the range of values that have been specified. The following example retrieves the list of all records where the Designation is either Manager or Assistant in the Emp table. mysql> SELECT * FROM Emp WHERE Designation ='Manager' OR 'Assistant'; IN Clause - The IN clause is used to check the values against to many values that have been specified in IN clause. The following example retrieves the list of all records where the Designation is either Manager or Assistant in the Emp table. mysql> SELECT * FROM Emp WHERE Designation IN ('Manager', 'Assistant'); NOT IN Clause - You can use the NOT modifier with IN clause for checking the values,. Which are not within the list. The following example retrieves the list of all records where the Designation is not equal to Manager or Assistant in the Emp table. mysql> SELECT * FROM Emp WHERE Designation NOT IN ('Manager', 'Assistant'); The following list shows you a Aggregate Function that available in MySQL.

AVG( ); The AVG( ) function returns the average value in a group of records. Example of the AVG( ) function:SELECT AVG(Profit) FROM Income GROUP BY EmpId; COUNT( ); The COUNT( ) function returns the number of records in a group of records. Example of the COUNT( ) function:SELECT COUNT(Profit) FROM Income GROUP BY EmpId;

MAX( ); The MAX( ) function return the maximum value in a group of records. Example of the MAX( ) function:SELECT MAX(Profit) FROM Income GROUP BY EmpId; MIN( ); The MIN( ) function returns minimum value in a group of records. Example of the MIN( ) function:SELECT MIN(Profit) FROM Income GROUP BY EmpId; SUM( ); The SUM( ) function return the sum of the field. Example of the SUM() function : SELECT SUM(Profit) FROM Income GROUP BY EmpId ;

The HAVING Clause As you know the WHERE clause is used to restrict the records in a query. But if you want to restrict the records by using the Aggregate function then you have to use the HAVING clause. The HAVING clause restricts the records after they have been grouped. The following example shows the list of all Employees who did profit over 10000 on average. mysql> SELECT AVG(Profit) FROM Income GROUP BY EmpId HAVING AVG(Profit) > 10000; The ORDER BY Clause The ORDER BY clause can be used to set the order of the retrieved records. The following example shows the list of all employees in the Emp table in alphabetical order. In this clause we can use the ASC or DESC modifiers to set the order of records in ascending or descending order. If any modifier is not provided then the records are listed in ascending order. mysql> SELECT Name FROM Emp ORDER BY Name; The LIMIT Clause The LIMIT clause can be used to limit the number of records that have been returned by the SELECT statement. You can specify the start row, and number of records retrieved. mysql> SELECT * FROM Emp LIMIT 0,10;

GROUP BY clause The MySQL GROUP BY clause is used with the SELECT statement to group rows into subgroups by the one or more values of columns or expressions. The MySQL GROUP BY clause is an optional part of the SELECT statement. It must appear after the FROM or WHERE clause. The MySQL GROUP BY clause consists of the GROUP BY keyword followed by a list of comma-separated columns or expressions. The following illustrates the MySQL GROUP BY clause syntax: SELECT c1,c2,... cn, aggregate_function(expression) FROM table WHERE where_conditions GROUP BY c1, c2, ... cn Views in MySQL A view is a specific look on data from one or more tables. It can arrange data in some specific order, highlight or hide some data. A view consists of a stored query accessible as a virtual table composed of the result set of a query. Unlike ordinary tables a view does not form part of the physical schema. It is a dynamic, virtual table computed or collated from data in the database. A view is a pseudo table. It is a stored query which looks like a table. And it can be referenced like a table. Views can restrict users to specific rows or columns and thus enhance security. They can be used to joing columns from multiple tables, so that they look like a single table. They can be used to provide aggregate information. There are several restrictions that apply to views. Here are some of them: The SELECT statement cannot contain a subquery The SELECT statement cannot refer to system or user variables Any table or view referred to in the definition must exist A temporary VIEW cannot be created A VIEW cannot be associated with a trigger Creating, modifying and dropping a View CREATE VIEW syntax to create a view. mysql> SELECT * FROM Cars; +----+------------+--------+ | Id | Name | Cost | +----+------------+--------+ | 1 | Audi | 52642 | | 2 | Mercedes | 57127 | | 3 | Skoda | 9000 | | 4 | Volvo | 29000 | | 5 | Bentley | 350000 | | 6 | Citroen | 21000 | | 7 | Hummer | 41400 | | 8 | Volkswagen | 21600 | +----+------------+--------+

This is our data, upon which we create the view. mysql> CREATE VIEW CheapCars AS -> SELECT Name FROM Cars WHERE Cost<25000; We create a view CheapCars. These are cars which cost under 25000. mysql> SELECT * FROM CheapCars; +------------+ | Name | +------------+ | Skoda | | Citroen | | Volkswagen | +------------+ A view is a database object than can be queried. There are three cars which are considered to be cheap. mysql> ALTER VIEW CheapCars AS SELECT Name FROM Cars -> WHERE Cost<30000; mysql> SELECT * FROM CheapCars; +------------+ | Name | +------------+ | Skoda | | Volvo | | Citroen | | Volkswagen | +------------+ We can redefine a view. Say we now consider a car to be cheap, if it costs under 30000. We use the ALTER VIEW statement to modify our view. What happens to a view if we delete a table, from which the data is selected? mysql> DROP TABLE Cars; mysql> SELECT * FROM CheapCars; ERROR 1356 (HY000): View 'mydb.CheapCars' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them Querying the view we receive the above error. mysql> SOURCE cars.sql mysql> SELECT * FROM CheapCars; +------------+ | Name | +------------+

| Skoda | | Citroen | | Volkswagen | +------------+ When we recreate the table the view works again. mysql> DROP VIEW CheapCars; Finally, a view is deleted with the DROP VIEW syntax. Finding views We will mention several ways how to find views in MySQL database. mysql> SHOW FULL TABLES; +----------------+------------+ | Tables_in_mydb | Table_type | +----------------+------------+ | AA | BASE TABLE | ... | Chars | BASE TABLE | | CheapCars | VIEW | | Customers | BASE TABLE | | Dates | BASE TABLE | | Decimals | BASE TABLE | | FavoriteCars | VIEW | ... We can list all tables in a database with a SHOW FULL TABLES statement. In the Table_type column we can see, whether it is a table or a view. mysql> SELECT TABLE_NAME, TABLE_TYPE FROM information_schema.TABLES; +---------------------------------------+-------------+ | TABLE_NAME | TABLE_TYPE | +---------------------------------------+-------------+ | CHARACTER_SETS | SYSTEM VIEW | | COLLATIONS | SYSTEM VIEW | | COLLATION_CHARACTER_SET_APPLICABILITY | SYSTEM VIEW | | COLUMNS | SYSTEM VIEW | | COLUMN_PRIVILEGES | SYSTEM VIEW | | ENGINES | SYSTEM VIEW | ... | Chars | BASE TABLE | | CheapCars | VIEW | | Customers | BASE TABLE | | Dates | BASE TABLE | | Decimals | BASE TABLE | | FavoriteCars | VIEW | ...

In the information_schema database there is a TABLES table. The TABLE_NAME and TABLE_TYPE columns give us information about table names and their types. mysql> SELECT TABLE_NAME FROM information_schema.VIEWS; +--------------+ | TABLE_NAME | +--------------+ | CheapCars | | FavoriteCars | +--------------+ This is the most straightforward way to find views. We query the VIEWS table of the information_schema database. Creating a view with a UNION The UNION operator is used to combine result-sets of two or more SELECT statements. Each select must have the same number of columns. mysql> CREATE VIEW FavoriteCars AS -> SELECT * FROM Cars WHERE Id=7 -> UNION SELECT * FROM Cars WHERE Id=4 -> UNION SELECT * FROM Cars WHERE Id=5; We create a view called FavoriteCars. In this view, we have three rows which are considered to be favourite. There are three SELECT statements combined with a UNION operator. mysql> SELECT * FROM FavoriteCars; +----+---------+--------+ | Id | Name | Cost | +----+---------+--------+ | 7 | Hummer | 41400 | | 4 | Volvo | 29000 | | 5 | Bentley | 350000 | +----+---------+--------+ This is a SELECT from the view. JOIN in MySQL An SQL join clause combines records from two or more tables in a database. It creates a set that can be saved as a table or used as it is. A JOIN is a means for combining fields from two tables by using values common to each. ANSI standard SQL specifies four types of JOIN: INNER, OUTER, LEFT, and RIGHT. As a special case, a table (base table, view, or joined table) canJOIN to itself in a self-join. A programmer writes a JOIN predicate to identify the records for joining. If the evaluated predicate is true, the combined record is then produced in the expected format, a record set or a temporary table. Consider the following tables:

Employee table

LastName

DepartmentID

Rafferty

31

Jones

33

Steinberg

33

Robinson

34

Smith

34

John

NULL

Department table

DepartmentID DepartmentName

31

Sales

33

Engineering

34

Clerical

35

Marketing

Note: In the Employee table above, the employee "John" has not been assigned to any department yet. Also, note that no employees are assigned to the "Marketing" department.

Cross join

CROSS JOIN returns the Cartesian product of rows from tables in the join. In other words, it will produce rows which combine each row from the first table with each row from the second table.[1] Example of an explicit cross join: SELECT * FROM employee CROSS JOIN department; Example of an implicit cross join: SELECT * FROM employee, department; Employee.LastN Employee.Departme Department.Department Department.Departm ame ntID Name entID

Rafferty

31

Sales

31

Jones

33

Sales

31

Steinberg

33

Sales

31

Smith

34

Sales

31

Robinson

34

Sales

31

John

NULL

Sales

31

Rafferty

31

Engineering

33

Jones

33

Engineering

33

Steinberg

33

Engineering

33

Smith

34

Engineering

33

Robinson

34

Engineering

33

John

NULL

Engineering

33

Rafferty

31

Clerical

34

Jones

33

Clerical

34

Steinberg

33

Clerical

34

Smith

34

Clerical

34

Robinson

34

Clerical

34

John

NULL

Clerical

34

Rafferty

31

Marketing

35

Jones

33

Marketing

35

Steinberg

33

Marketing

35

Smith

34

Marketing

35

Robinson

34

Marketing

35

John

NULL

Marketing

35

The cross join does not apply any predicate to filter records from the joined table. Programmers can further filter the results of a cross join by using a WHERE clause.

Inner join An inner join is the most common join operation used in applications and can be regarded as the default join-type. Inner join creates a new result table by combining column values of two

tables (A and B) based upon the join-predicate. The query compares each row of A with each row of B to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, column values for each matched pair of rows of A and B are combined into a result row. The result of the join can be defined as the outcome of first taking the Cartesian product (or Cross join) of all records in the tables (combining every record in table A with every record in table B)then return all records which satisfy the join predicate. Actual SQL implementations normally use other approaches like a hash join or a sort-merge join where possible, since computing the Cartesian product is very inefficient. SQL specifies two different syntactical ways to express joins: "explicit join notation" and "implicit join notation". The "explicit join notation" uses the JOIN keyword to specify the table to join, and the ON keyword to specify the predicates for the join, as in the following example: SELECT * FROM employee INNER JOIN department ON employee.DepartmentID = department.DepartmentID; The "implicit join notation" simply lists the tables for joining, in the FROM clause of the SELECT statement, using commas to separate them. Thus it specifies a cross join, and the WHERE clause may apply additional filter-predicates (which function comparably to the join-predicates in the explicit notation). The following example is equivalent to the previous one, but this time using implicit join notation: SELECT * FROM employee, department WHERE employee.DepartmentID = department.DepartmentID; The queries given in the examples above will join the Employee and Department tables using the DepartmentID column of both tables. Where the DepartmentID of these tables match (i.e. the join-predicate is satisfied), the query will combine the LastName, DepartmentID and DepartmentName columns from the two tables into a result row. Where the DepartmentID does not match, no result row is generated. Thus the result of the execution of either of the two queries above will be: Employee.LastN Employee.Departme Department.Department Department.Departm ame ntID Name entID

Robinson

34

Clerical

34

Jones

33

Engineering

33

Smith

34

Clerical

34

Steinberg

33

Engineering

33

Rafferty

31

Sales

31

Note: Programmers should take special care when joining tables on columns that can contain NULL values, since NULL will never match any other value (not even NULL itself), unless the join condition explicitly uses the IS NULL or IS NOT NULL predicates. Notice that the employee "John" and the department "Marketing" do not appear in the query execution results. Neither of these has any matching records in the other respective table: "John" has no associated department, and no employee has the department ID 35 ("Marketing"). Depending on the desired results, this behavior may be a subtle bug, which can be avoided with an outer join. One can further classify inner joins as equi-joins, as natural joins, or as cross-joins. Equi-join An equi-join is a specific type of comparator-based join, that uses only equality comparisons in the join-predicate. Using other comparison operators (such as <) disqualifies a join as an equi-join. The query shown above has already provided an example of an equi-join: SELECT * FROM employee JOIN department ON employee.DepartmentID = department.DepartmentID; We can write equi-join as below, SELECT * FROM employee, department WHERE employee.DepartmentID = department.DepartmentID; If columns in an equi-join have the same name, SQL-92 provides an optional shorthand notation for expressing equi-joins, by way of the USING construct: SELECT * FROM employee INNER JOIN department USING (DepartmentID); The USING construct is more than mere syntactic sugar, however, since the result set differs from the result set of the version with the explicit predicate. Specifically, any columns mentioned in the USING list will appear only once, with an unqualified name, rather than once for each table in the join. In the above case, there will be a single DepartmentID column and noemployee.DepartmentID or department.DepartmentID. The USING clause is not supported by SQL Server and Sybase. Natural join A natural join is a type of equi-join where the join predicate arises implicitly by comparing all columns in both tables that have the same column-names in the joined tables. The resulting joined table contains only one column for each pair of equally named columns. Most experts agree that NATURAL JOINs are dangerous and therefore strongly discourage their use. The danger comes from inadvertently adding a new column, named the same as

another column in the other table. An existing natural join might then "naturally" use the new column for comparisons, making comparisons/matches using different criteria (from different columns) than before. Thus an existing query could produce different results, even though the data in the tables have not been changed, but only augmented. The above sample query for inner joins can be expressed as a natural join in the following way: SELECT * FROM employee NATURAL JOIN department; As with the explicit USING clause, only one DepartmentID column occurs in the joined table, with no qualifier: DepartmentID Employee.LastName Department.DepartmentName

34

Smith

Clerical

33

Jones

Engineering

34

Robinson

Clerical

33

Steinberg

Engineering

31

Rafferty

Sales

PostgreSQL, MySQL and Oracle support natural joins, but not Microsoft T-SQL or IBM DB2. The columns used in the join are implicit so the join code does not show which columns are expected, and a change in column names may change the results. An INNER JOIN performed on 2 tables having the same field name has the same effect. Outer joins An outer join does not require each record in the two joined tables to have a matching record. The joined table retains each recordeven if no other matching record exists. Outer joins subdivide further into left outer joins, right outer joins, and full outer joins, depending on which table's rows are retained (left, right, or both). (In this case left and right refer to the two sides of the JOIN keyword.) No implicit join-notation for outer joins exists in standard SQL. Left outer join The result of a left outer join (or simply left join) for table A and B always contains all records of the "left" table (A), even if the join-condition does not find any matching record in the "right" table (B). This means that if the ON clause matches 0 (zero) records in B (for a

given record in A), the join will still return a row in the result (for that record)but with NULL in each column from B. Aleft outer join returns all the values from an inner join plus all values in the left table that do not match to the right table. From Oracle 9i onwards the LEFT OUTER JOIN statement can be used as well as Oracle's older (+) syntax. For example, this allows us to find an employee's department, but still shows the employee(s) even when they have not been assigned to a department (contrary to the inner-join example above, where unassigned employees were excluded from the result). Example of a left outer join, with the additional result row (compared with the inner join) italicized: SELECT * FROM employee LEFT OUTER JOIN department ON employee.DepartmentID = department.DepartmentID; Employee.LastN Employee.Departme Department.Department Department.Departm ame ntID Name entID

Jones

33

Engineering

33

Rafferty

31

Sales

31

Robinson

34

Clerical

34

Smith

34

Clerical

34

John

NULL

NULL

NULL

Steinberg

33

Engineering

33

Oracle supports the alternate syntax: SELECT * FROM employee, department WHERE employee.DepartmentID = department.DepartmentID(+) Sybase supports the alternate syntax: SELECT * FROM employee, department WHERE employee.DepartmentID *= department.DepartmentID Right outer join

A right outer join (or right join) closely resembles a left outer join, except with the treatment of the tables reversed. Every row from the "right" table (B) will appear in the joined table at least once. If no matching row from the "left" table (A) exists, NULL will appear in columns from A for those records that have no match in B. A right outer join returns all the values from the right table and matched values from the left table (NULL in case of no matching join predicate). For example, this allows us to find each employee and his or her department, but still show departments that have no employees. Below is an example of a right outer join, with the additional result row italicized: SELECT * FROM employee RIGHT OUTER JOIN department ON employee.DepartmentID = department.DepartmentID; Employee.LastN Employee.Departme Department.Department Department.Departm ame ntID Name entID

Smith

34

Clerical

34

Jones

33

Engineering

33

Robinson

34

Clerical

34

Steinberg

33

Engineering

33

Rafferty

31

Sales

31

NULL

NULL

Marketing

35

Oracle supports the alternate syntax: SELECT * FROM employee, department WHERE employee.DepartmentID(+) = department.DepartmentID Right and left outer joins are functionally equivalent. Neither provides any functionality that the other does not, so right and left outer joins may replace each other as long as the table order is switched. Full outer join Conceptually, a full outer join combines the effect of applying both left and right outer joins. Where records in the FULL OUTER JOINed tables do not match, the result set will have

NULL values for every column of the table that lacks a matching row. For those records that do match, a single row will be produced in the result set (containing fields populated from both tables). For example, this allows us to see each employee who is in a department and each department that has an employee, but also see each employee who is not part of a department and each department which doesn't have an employee. Example full outer join: SELECT * FROM employee FULL OUTER JOIN department ON employee.DepartmentID = department.DepartmentID; Employee.LastN Employee.Departme Department.Department Department.Departm ame ntID Name entID

Smith

34

Clerical

34

Jones

33

Engineering

33

Robinson

34

Clerical

34

John

NULL

NULL

NULL

Steinberg

33

Engineering

33

Rafferty

31

Sales

31

NULL

NULL

Marketing

35

Some database systems do not support the full outer join functionality directly, but they can emulate it through the use of an inner join and UNION ALL selects of the "single table rows" from left and right tables respectively. The same example can appear as follows: SELECT employee.LastName, employee.DepartmentID, department.DepartmentName, department.DepartmentID FROM employee INNER JOIN department ON employee.DepartmentID = department.DepartmentID UNION ALL

SELECT employee.LastName, employee.DepartmentID, CAST(NULL AS VARCHAR(20)), CAST(NULL AS INTEGER) FROM employee WHERE NOT EXISTS ( SELECT * FROM department WHERE employee.DepartmentID = department.DepartmentID) UNION ALL SELECT CAST(NULL AS VARCHAR(20)), CAST(NULL AS INTEGER), department.DepartmentName, department.DepartmentID FROM department WHERE NOT EXISTS ( SELECT * FROM employee WHERE employee.DepartmentID = department.DepartmentID) Self-join A self-join is joining a table to itself. Example A query to find all pairings of two employees in the same country is desired. If there were two separate tables for employees and a query which requested employees in the first table having the same country as employees in the second table, a normal join operation could be used to find the answer table. However, all the employee information is contained within a single large table.[7] Consider a modified Employee table such as the following: Employee Table

EmployeeID LastName

Country

DepartmentID

123

Rafferty

Australia

31

124

Jones

Australia

33

145

Steinberg

Australia

33

201

Robinson United States

34

305

Smith

Germany

34

306

John

Germany

NULL

An example solution query could be as follows: SELECT F.EmployeeID, F.LastName, S.EmployeeID, S.LastName, F.Country FROM Employee F INNER JOIN Employee S ON F.Country = S.Country WHERE F.EmployeeID < S.EmployeeID ORDER BY F.EmployeeID, S.EmployeeID; Which results in the following table being generated. Employee Table after Self-join by Country

EmployeeID LastName EmployeeID LastName Country

123

Rafferty

124

Jones

Australia

123

Rafferty

145

Steinberg Australia

124

Jones

145

Steinberg Australia

305

Smith

306

John

Germany

For this example: F and S are aliases for the first and second copies of the employee table. The condition F.Country = S.Country excludes pairings between employees in different countries. The example question only wanted pairs of employees in the same country. The condition F.EmployeeID < S.EmployeeID excludes pairings where the EmployeeID of the first employee is greater than or equal to the EmployeeID of the second employee. In other words, the effect of this condition is to exclude duplicate pairings and self-pairings. Without it, the following less useful table would be generated (the table below displays only the "Germany" portion of the result): EmployeeID LastName EmployeeID LastName Country

305

Smith

305

Smith

Germany

305

Smith

306

John

Germany

306

John

305

Smith

Germany

306

John

306

John

Germany

Only one of the two middle pairings is needed to satisfy the original question, and the topmost and bottommost are of no interest at all in this example.

ResultSet Object in MYSQL java.sql Interface ResultSet A table of data representing a database result set, which is usually generated by executing a statement that queries the database. A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set. A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable. The following code fragment, in which con is a valid Connection object, illustrates how to make a result set that is scrollable and insensitive to updates by others, and that is updatable. See ResultSet fields for other options.

Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2"); // rs will be scrollable, will not show changes made by others, // and will be updatable

The ResultSet interface provides getter methods (getBoolean, getLong, and so on) for retrieving column values from the current row. Values can be retrieved using either the index number of the column or the name of the column. In general, using the column index will be more efficient. Columns are numbered from 1. For maximum portability, result set columns within each row should be read in left-to-right order, and each column should be read only once. For the getter methods, a JDBC driver attempts to convert the underlying data to the Java type specified in the getter method and returns a suitable Java value. The JDBC specification

has a table showing the allowable mappings from SQL types to Java types that can be used by the ResultSet getter methods. Column names used as input to getter methods are case insensitive. When a getter method is called with a column name and several columns have the same name, the value of the first matching column will be returned. The column name option is designed to be used when column names are used in the SQL query that generated the result set. For columns that are NOT explicitly named in the query, it is best to use column numbers. If column names are used, there is no way for the programmer to guarantee that they actually refer to the intended columns. A set of updater methods were added to this interface in the JDBC 2.0 API (JavaTM 2 SDK, Standard Edition, version 1.2). The comments regarding parameters to the getter methods also apply to parameters to the updater methods. The updater methods may be used in two ways: 1. to update a column value in the current row. In a scrollable ResultSet object, the cursor can be moved backwards and forwards, to an absolute position, or to a position relative to the current row. The following code fragment updates the NAME column in the fifth row of the ResultSet object rs and then uses the method updateRow to update the data source table from which rs was derived. rs.absolute(5); // moves the cursor to the fifth row of rs rs.updateString("NAME", "AINSWORTH"); // updates the // NAME column of row 5 to be AINSWORTH rs.updateRow(); // updates the row in the data source 2. to insert column values into the insert row. An updatable ResultSet object has a special row associated with it that serves as a staging area for building a row to be inserted. The following code fragment moves the cursor to the insert row, builds a three-column row, and inserts it into rs and into the data source table using the method insertRow.

rs.moveToInsertRow(); // moves cursor to the insert row rs.updateString(1, "AINSWORTH"); // updates the // first column of the insert row to be AINSWORTH rs.updateInt(2,35); // updates the second column to be 35 rs.updateBoolean(3, true); // updates the third column to true rs.insertRow(); rs.moveToCurrentRow(); A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results. The number, types and properties of a ResultSet object's columns are provided by the ResulSetMetaData object returned by the ResultSet.getMetaData method.

Properties object to connect to database: Using a database URL and a Properties object: A third form of the DriverManager.getConnection( ) method requires a database URL and a Properties object: DriverManager.getConnection(String url, Properties info); A Properties object holds a set of keyword-value pairs. It's used to pass driver properties to the driver during a call to the getConnection() method. To make the same connection made by the previous examples, use the following code: import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class DBConnect2 { public static void main(String[] args) { String databaseURL = "jdbc:mysql://localhost:3306/test"; Connection conn = null; try { Properties props = new Properties(); props.put("user", "root"); props.put("password", "root123"); conn = DriverManager.getConnection(databaseURL, props); if (conn != null) { System.out.println("Connected to the database"); } } catch (SQLException ex) { System.out.println("An error occurred. Maybe user/password is invalid"); ex.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } } } MYSQL commands: CREATE TABLE Syntax CREATE TABLE creates a table with the given name. A) FOR GENERAL TABLE CREATION

Create Table TableName(fieldname datatype,fieldname1 datatype,) Example: CREATE TABLE Student (StudentId int(6) not null default 0,Student varchar(25) not null default , PrimaryKey(StudentId)); B) FOR CREATING TABLE USING AN EXISTING TABLE(ALONG WITH DATA) Create Table TableName AS Select * from ExistingTableName Example: CREATE TABLE StudentEmail AS SELECT * FROM PersonEmail; C) FOR CREATING TABLE USING AN EXISTING TABLE(WITHOUT DATA) Create Table TableName like ExistingTableName Example: CREATE TABLE StudentEmail like PersonEmail; D) FOR CREATING TABLE USING MYSQLDUMP mysqldump p u username databasename tablename > tablename.sql mysql -u p username databasename < tablename.sql Example: mysqldump -p -u sans sanskrit Pustak > pustak.sql Example: mysql -p -u sans sans sanskrit < pustak.sql 2. ALTER TABLE Syntax ALTER TABLE enables you to change the structure of an existing table. For example, you can add or delete columns, change the type of existing columns, or rename columns or the table itself. A) TO ADD A NEW COLUMN a) To add the column as the first column of the table. Alter Table TableName add NewColumnName datatype FIRST Example: Alter table Student add School varchar(30) not null default FIRST b) To add the column after a particular column of the table. Alter Table TableName add NewColumnName datatype AFTER ExistingColumnName Example: Alter table Student Add School varchar(30) not null default AFTER Student B) TO DELETE A COLUMN Alter Table TableName DROP ColumnName Example: Alter table Student DROP School C) TO RENAME A COLUMN Alter Table TableName CHANGE OldColumnName NewColumnName datatype Example: Alter table Student change School SchoolName varchar(30) not null default ; D) TO MODIFY A COLUMN DATA-TYPE/SIZE Alter Table TableName modify ColumnName datatype Example: Alter table Student modify School varchar(50) not null default ; E) TO MAKE A COLUMN UNIQUE a) To make a single column unique. Alter Table TableName add UNIQUE(fieldname) Example: Alter table Student add UNIQUE(School); b) To make multiple columns unique. Alter Table TableName add UNIQUE(fieldname1, fieldname2, fieldname3) Example: Alter table Ashtadhyayee add UNIQUE(Bhav, Paad, Sootra); 3. RENAME TABLE Syntax This statement renames one or more tables. Rename OldTableName to NewTableName; Example: Rename Student to StudentDetail 4. DROP TABLE Syntax This statement will allow deleting a table from the database

DROP table TableName; Example: DROP table StudentDetail 5. TO SEE ALL THE TABLES IN THE DATABASE SHOW tables; 6. TO SEE DATABASE'S FIELD FORMATS. Desc tablename; 7. INSERT Syntax INSERT inserts new rows into an existing table A) To Insert data in all columns of a table. INSERT INTO TableName values () Example: Insert into StudentDetail values(1,Ravi,WoodBine),; B) To Insert data in a column(s) of the table. INSERT INTO TableName (ColName1, ColName2,..) values(val1,val2,..) Example: Insert into StudentDetail (StudentId, StudentName) values(2,Shyaam),; C) To Insert data into a table from another table. INSERT INTO TableName (ColName1,ColName2) select ColName1,ColName2 From TableName2. Example: Insert into StudentName (StudentName) select Name from NameLog; 8. SELECT Syntax SELECT is used to retrieve rows selected from one or more tables D) To Select all data from the table SELECT * FROM TABLENAME; Example: Select * from StudentDetail; E) To Select data of a particular Column from the table SELECT ColumnName FROM TABLENAME; Example: Select StudentName from StudentDetail; F) To Select data based on a condition SELECT * FROM TABLENAME where Condition; Example: Select StudentName from StudentDetail where StudentId=2; G) To Select limited number of Records at a time SELECT * FROM TABLENAME LIMIT no.of records Example: Select StudentName from StudentDetail LIMIT 10 9. UPDATE Syntax UPDATE statement updates columns of existing rows in TableName with new values. The SET clause indicates which columns to modify and the values they should be given. The WHERE clause, if given, specifies the conditions that identify which rows to update. With no WHERE clause, all rows are updated. A) To Update data based on a condition UPDATE TableName SET ColumnName=value where condition; Example: UPDATE StudentDetail SET StudentName=Rohan where StudentId=1; B) To Update all records simultaneously UPDATE TableName SET ColumnName=value where condition Example: UPDATE StudentDetail SET School=Wendy High School;

10. DELETE Syntax DELETE statement deletes rows from TableName and returns a count of the number of deleted rows. The WHERE clause, if given, specifies the conditions that identify which rows to delete. With no WHERE clause, all rows are deleted. C) To Delete data based on a condition Delete fieldname from TableName where condition; Example: Delete StudentName where StudentId=1; D) To Delete all records simultaneously Delete from TableName Example: Delete * from StudentDetail

Program models: In the design of Java Web applications, there are two commonly used design models, referred to as Model 1 and Model 2. Model 1

A simplified diagram of a Model 1 implementation. In Model 1, a request is made to a JSP or servlet and then that JSP or servlet handles all responsibilities for the request, including processing the request, validating data, handling the business logic, and generating a response. The Model 1 architecture is commonly used in smaller, simple task applications due to its ease of development. Although conceptually simple, this architecture is not conducive to large-scale application development because, inevitably, a great deal of functionality is duplicated in each JSP. Also, the Model 1 architecture unnecessarily ties together the business logic and presentation logic of the application. Combining business logic with presentation logic makes it hard to introduce a new 'view' or access point in an application. For example, in addition to an HTML interface, you might want to include a Wireless Markup Language (WML) interface for wireless access. In this case, using Model 1 will unnecessarily require the duplication of the business logic with each instance of the presentation code. Advantages: Easy and quick to develop web application Disadvantages:

Navigation control is decentralized. Time consuming: spend more time to develop custom tags in JSP. So that there is no need to use scirptlet tags. Hard to extend: better for small applications but not for large applications. Model 2

A simplified diagram of the Model 2 pattern. Model 2 is a complex design pattern used in the design of Java Web applications which separates the display of content from the logic used to obtain and manipulate the content. Since Model 2 drives a separation between logic and display, it is usually associated with the Model-View-Controller (MVC) paradigm. While the exact form of the MVC "Model" was never specified by the Model 2 design, a number of publications recommend a formalized layer to contain MVC Model code. The Java BluePrints, for example, originally recommended using EJBs to encapsulate the MVC Model. In a Model 2 application, requests from the client browser are passed to the controller. The controller performs any logic necessary to obtain the correct content for display. It then places the content in the request (commonly in the form of a JavaBean or POJO) and decides which view it will pass the request to. The view then renders the content passed by the controller. Model 2 is recommended for medium- and large-sized applications. Advantages: Navigation control is centralized Easy to maintain Easy to extend Easy to test Better separation of concerns Disadvantages: Controller code self is to be written. If the controller code is changed, class has to be recompiled and redeploy the application.

Indexing in MYSQL:

Indexing, is the process of creating Indexes. Indexes are structures which allow SQL (or more generally a DBMS or Search Engine) to locate, in a very efficient fashion, records based on the value of one (or several) of the fields they contain. For example, a database may include at table containing student records, with their Student ID, their Name, Date of Birth, Phone Number ... By creating a index on the Phone Number, we can then search Student based on a phone number. In the absence of an index, the system would have found the same records, but this operation would have been carried by looking every single record and comparing with the desired phone number. Types of INDEXES:

KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any restraints on your data so they are used only for making sure certain queries can run quickly. UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to speed up queries, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow this distinct values rule to be broken when inserting or updating data. Your database system may allow a UNIQUE index to be applied to columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (the rationale here is that NULL is considered not equal to itself). Depending on your application, however, youmay find this undesirable: if you wish to prevent this, you should disallow NULL values in the relevant columns. PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a primary means to uniquely identify any row in the table, so unlike UNIQUE it should not be used on any columns which allow NULL values. Your PRIMARY index should be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead. Some database systems (such as MySQL's InnoDB) will store a table's records on disk in the order in which they appear in the PRIMARY index. FULLTEXT indexes are different from all of the above, and their behaviour differs significantly between database systems. FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause, unlike the above three - which are typically implemented internally using b-trees (allowing for selecting, sorting or ranges starting from left most column) or hash tables (allowing for selection starting from left most column). Where the other index types are general-purpose, a FULLTEXT index is specialised, in that it serves a narrow purpose: it's only used for a "full text search" feature.

Similarities All of these indexes may have more than one column in them. With the exception of FULLTEXT, the column order is significant: for the index to be useful in a query, the query must use columns from the index starting from the left - it

can't use just the second, third or fourth part of an index, unless it is also using the previous columns in the index to match static values. (For a FULLTEXT index to be useful to a query, the query must use all columns of the index.) CREATE INDEX Syntax Unique indexing: CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name [index_type] ON tbl_name (index_col_name) [index_type] index_col_name: col_name [(length)] [ASC | DESC] index_type: USING {BTREE | HASH} Temporary indexing: CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name (create_definition,...) [table_options] Or: CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)] [table_options] select_statement Two columns indexing: CREATE INDEX index_name [index_type] ON tbl_name (col_name1,colname2) [index_type] Multiple columns indexing: CREATE INDEX index_name [index_type] ON tbl_name (col_name1,colname2,colname3) [index_type]

You might also like