SQL
SQL
Data: o Basic/raw facts about something which is not organized, for example details of some students which is not organized. Data Item: o Each piece of information about an entity, such as name of a person or address, age or name of a product or the price is a Data Item. Database: o A well organised collection of data that ensures safety, security and integrity of data. DataBase Management System(DBMS) : o Comprehensive software that provides the essential services to create, manage and maintain the databases. In short a DBMS provides the means to store the data in the database, to edit or delete the data stored, to search and analyze the data in the database. They also provide various safety and security mechanisms that ensures that in any case stored data will be safe and accessible.
Database Systems: o Systems comprising of Databases and Database Management Systems are simply referred as database systems. Advantages of Database Systems: o They reduce data redundancy (duplication of data). o They control data inconsistency. o They facilitate sharing of data. o They enforce standards. o They ensure data security & integrity o They facilitate efficiency in handling the data. Relational DataBase Management System(RDBMS) : o A Database Management System that conforms at-least half of the 12 rules defined by Dr. E.F. Codd (1970) in his research document. In a relational data model, the data is organized into tables (i.e. Rows and Columns). These tables are called Relations. A row in a table represents a relationship among a set of values. Since table is a collection of relationships it is generally referred to using the mathematical term Relation.
Relational data model: In this model data is organised into tabular structures called relations. A database may contain many relations providing a better classification of data based on its nature and use. Multiple relations are then linked/associated together on some common key data values (foreign key). Basics of Relational Model Relation : A tabular structure containing data. To be a relation is must satisfy following four conditions: Atomicity : At every row-column intersectioni (Cell) there must be an atomic value i.e. a value that can not be further subdivided.
No duplicity: No two rows of relation will be identicali i.e. in any two rows value in at least one column must be different. Ordering of rows is immaterial.i Ordering of columns isi immaterial. Tuple : A row in a relation is called a tuple. Attribute : A column in a relation is called an attribute. Domain : Domain of an attribute refers to the set of all the possible values for that attribute. Degree : Number of attributes in a relation is the degree of that relation. Cardinality : Number of tuples in a relation is the cardinality of that relation.
Candidate Key: o A set of one or more minimal attributes used to uniquely identify a tuple in the relation and which can act as Primary Key. A relation can have multiple candidate keys. Primary Key: o A candidate key that is primarily chosen for unique identification of tuples in a Relation. Any subset of Primary key should not be Primary key. For example: Admission Number in the Student Table, Accession Number of a Book in the Book table, Employee Id of an employee in the Employee Table, Item Number of an item in the Stock table, Flight Number of a flight in the Flight Master Table, etc. A table may have more than one candidate keys but definitely has one and only one primary key.
Alternate Key: o Candidate keys that not chosen as primary key are the alternate keys. Foreign Key: o When the primary key of one relation appears in another relation, it is called foreign key. Foreign key refers to a tuple in its original table. Referential Integrity: o When a table contain foreign key, referring to a tuple/record in another table, the referenced record must be exist. The record in first table may be termed as parent record while a record in foreign key table is called the child record. Referential integrity ensures that a child record will exist only if its parent record exists. Child record can not be created if parent record does not exist and parent record can not be deleted if a child record exists.
Introduction to MySQL
MySQL is a fast, easy-to-use RDBMS used for small and big business applications. MySQL is developed, marketed, and supported by a Swedish Company MySQL AB. MySQL is released under an opensource license so it is customizable. It requires no payment for its usage. MySQL is a very powerful software to handle RDBMS. o MySQL uses a standard form of the well-known ANSI-SQL standards. o MySQL is a platform independent application which works on many operating systems like Windows, UNIX, LINUX etc. And has compatibility with many languages including JAVA , C++, PHP, PERL, etc. o MySQL is a easy to install RDBMS and capable of handling large data sets.
SQL Commands: SQL commands are instructions used to communicate with the database to perform specific task that work with data. SQL commands can be used not only for searching the database but also to perform various other functions like, for example, you can create tables, add data to tables, or modify data, drop the table, set permissions for users. SQL commands are grouped into four major categories depending on their functionality: Data Definition Language (DDL) - These SQL commands are used for creating, modifying, and dropping the structure of database objects. The commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE. Data Manipulation Language (DML) - These SQL commands are used for storing, retrieving, modifying, and deleting data. These commands are SELECT, INSERT, UPDATE, and DELETE. Transaction Control Language (TCL) - These SQL commands are used for managing changes affecting the data. These commands are COMMIT, ROLLBACK, and SAVEPOINT. Data Control Language (DCL) - These SQL commands are used for providing security to database objects. These commands are GRANT and REVOKE.
Text
CHAR(size) A fixed-length string between 1 and 255 characters in length right-padded with spaces to the specified length when stored. Values must be enclosed in single quotes or double quotes. CHAR(size) VARCHAR(size) A variable-length string between 1 and 255 characters in length; for example VARCHAR(25). Values must be enclosed in single quotes or double quotes. VARCHAR (size)
NUMERIC
DECIMAL(p,s) It can represent number with or without the fractional part. The size argument has two parts : precision and scale. Precision (p) indicates the number of significant digits and scale (s)maximum number of digits to the right of the decimal point.
INT It is used for storing integer values INT (3) DATE It represents the date including day, month and year between 1000-01-01 and 9999-12-31 YYYY-MM-DD 2009-07-02
Creating a Table
mysql> SHOW TABLES;
Displays the current list of tables
mysql> CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20), -> species VARCHAR(20), sex CHAR(1), birth DATE, death DATE); mysql> SHOW TABLES;
Will display the table with the table name pet Verification of the table can be done with DESCRIBE command mysql> DESCRIBE pet;
+---------------| Field +---------------| name | owner | species | sex | birth | death +---------------- +---------------| Type | Null +---------------- +---------------| varchar(20) | YES | varchar(20) | YES | varchar(20) | YES | char(1) | YES | date | YES | date | YES +---------------| Key +---------------| | | | | | +---------------| Default +--------| NULL | NULL | NULL | NULL | NULL | NULL +---------------| Extra +---------------| | | | | | + | + | | | | | |
SQL CREATE TABLE Statement The CREATE TABLE Statement is used to create tables to store data. Integrity Constraints like primary key, unique key, foreign key can be defined for the columns while creating the table. The integrity constraints can be defined at column level or table level. The implementation and the syntax of the CREATE Statements differs for different RDBMS. The Syntax for the CREATE TABLE Statement is: CREATE TABLE table_name (column_name1 datatype, column_name2 datatype, ... column_nameN datatype ); table_name - is the name of the table. column_name1, column_name2.... - is the name of the columns datatype - is the datatype for the column like char, date, number etc. For Example: If you want to create the employee table, the statement would be like, CREATE TABLE employee ( id number(5), name char(20), dept char(10), age number(2), salary number(10), location char(10) );
Table name
Tables in SQL
Product
Attribute names
For Example: If you want to insert a row to the employee table, the query would be like, INSERT INTO employee (id, name, dept, age, salary location) VALUES (105, 'Srinath', 'Aeronautics', 27, 33000); NOTE:When adding a row, only the characters or date values should be enclosed with single quotes. If you are inserting data to all the columns, the column names can be omitted. The above insert statement can also be written as, INSERT INTO employee VALUES (105, 'Srinath', 'Aeronautics', 27, 33000);
Syntax for SQL INSERT is: INSERT INTO table_name [(column1, column2, ... columnN)] SELECT column1, column2, ...columnN FROM table_name [WHERE condition]; For Example: To insert a row into the employee table from a temporary table, the sql insert query would be like, INSERT INTO employee (id, name, dept, age, salary location) SELECT emp_id, emp_name, dept, age, salary, location FROM temp_employee; If you are inserting data to all the columns, the above insert statement can also be written as, INSERT INTO employee SELECT * FROM temp_employee; NOTE:We have assumed the temp_employee table has columns emp_id, emp_name, dept, age, salary, location in the above given order and the same datatype. IMPORTANT NOTE: 1) When adding a new row, you should ensure the datatype of the value and the column matches 2) You follow the integrity constraints, if any, defined for the table.
selection
DISTINCT Eliminating duplicate query results with distinct If you use the keyword distinct after the keyword SELECT, you will only get unique rows. Example: SELECT rate, FROM loan; (above will display all rate values might be repeated) SELECT distinct rate FROM loan; (above will display only unique rate values, no repetition)
SQL SELECT Statement The most commonly used SQL command is SELECT statement. The SQL SELECT statement is used to query or retrieve data from a table in the database. A query may retrieve information from specified columns or from all of the columns in the table. To create a simple SQL SELECT Statement, you must specify the column(s) name and the table name. The whole query is called SQL SELECT Statement. Syntax of SQL SELECT Statement: SELECT column_list FROM table-name [WHERE Clause] [GROUP BY clause] [HAVING clause] [ORDER BY clause]; table-name is the name of the table from which the information is retrieved. column_list includes one or more columns from which data is retrieved. The code within the brackets is optional
NOTE: In a SQL SELECT statement only SELECT and FROM statements are mandatory. Other clauses like WHERE, ORDER BY, GROUP BY, HAVING are optional.
For Example: To find the name of a student with id 100, the query would be like: SELECT first_name, last_name FROM student_details WHERE id = 100; Comparison Operators and Logical Operators are used in WHERE Clause. These operators are discussed in the next chapter. NOTE: Aliases defined for the columns in the SELECT statement cannot be used in the WHERE clause to set conditions. Only aliases created for tables can be used to reference the columns in the table. How to use expressions in the WHERE Clause? Expressions can also be used in the WHERE clause of the SELECT statement. For example: Lets consider the employee table. If you want to display employee name, current salary, and a 20% increase in the salary for only those products where the percentage increase in salary is greater than 30000, the SELECT statement can be written as shown below SELECT name, salary, salary*1.2 AS new_salary FROM employee WHERE salary*1.2 > 30000; Output: name salary Hrithik 35000 Harsha 35000 Priya 30000 new_salary 37000 37000 360000
SQL Operators
There are two type of Operators, namely Comparison Operators and Logical Operators. These operators are used mainly in the WHERE clause, HAVING clause to filter the data to be selected. Comparison Operators: Comparison operators are used to compare the column data with specific values in a condition. Comparison Operators are also used along with the SELECT statement to filter data based on specific conditions. The below table describes each comparison operator. Comparison Operators Description = equal to <>, != is not equal to < less than > greater than >= greater than or equal to <= less than or equal to Logical Operators: There are three Logical Operators namely AND, OR and NOT. Logical operators are discussed in detail in the next section
SQL Logical Operators There are three Logical Operators namely, AND, OR, and NOT. These operators compare two conditions at a time to determine whether a row can be selected for the output. When retrieving data using a SELECT statement, you can use logical operators in the WHERE clause, which allows you to combine more than one condition.
Logical Operators Description OR For the row to be selected at least one of the conditions must be true. AND For a row to be selected all the specified conditions must be true. NOT For a row to be selected the specified condition must be false. "OR" Logical Operator: If you want to select rows that satisfy at least one of the given conditions, you can use the logical operator, OR. For example: if you want to find the names of students who are studying either Maths or Science, the query would be like, SELECT first_name, last_name, subject FROM student_details WHERE subject = 'Maths' OR subject = 'Science' The output would be something like, first_name last_name subject ------------- ------------- ---------Anajali Bhagwat Maths Shekar Gowda Maths Rahul Sharma Science Stephen Fleming Science
AND" Logical Operator: If you want to select rows that must satisfy all the given conditions, you can use the logical operator, AND. For Example: To find the names of the students between the age 10 to 15 years, the query would be like: SELECT first_name, last_name, age FROM student_details WHERE age >= 10 AND age <= 15; The output would be something like, first_name last_name age ------------- ------------- -----Rahul Sharma 10 Anajali Bhagwat 12 Shekar Gowda 15
"NOT" Logical Operator: If you want to find rows that do not satisfy a condition, you can use the logical operator, NOT. NOT results in the reverse of a condition. That is, if a condition is satisfied, then the row is not returned. For example: If you want to find out the names of the students who do not play football, the query would be like: SELECT first_name, last_name, games FROM student_details WHERE NOT games = 'Football' The output would be something like, first_name last_name games ---------------- ---------------- ----------Rahul Sharma Cricket Stephen Fleming Cricket Shekar Gowda Badminton Priya Chandra Chess You can use multiple logical operators in an SQL statement. When you combine the logical operators in a SELECT statement, the order in which the statement is processed is 1) NOT 2) AND 3) OR
For example: If you want to select the names of the students who age is between 10 and 15 years, or those who do not play football, the SELECT statement would be SELECT first_name, last_name, age, games FROM student_details WHERE age >= 10 AND age <= 15 OR NOT games = 'Football' The output would be something like, first_name last_name age games ------------- ------------- -------- -----------Rahul Sharma 10 Cricket Priya Chandra 15 Chess
In this case, the filter works as follows: Condition 1: All the students WHO do not play football are selected. Condition 2: All the students whose are aged between 10 and 15 are selected. Condition 3: Finally the result is, the rows which satisfy atleast one of the above conditions is returned. NOTE:The order in which you phrase the condition is important, if the order changes you are likely to get a different result.
The output would be similar to: first_name last_name ------------- ------------- Rahul Sharma NOTE:Each underscore act as a placeholder for only one character. So you can use more than one underscore. Eg: ' __i% '-this has two underscores towards the left, 'S__j%' - this has two underscores between character 'S' and 'i'. SQL BETWEEN ... AND Operator The operator BETWEEN and AND, are used to compare data for a range of values. For Example: to find the names of the students between age 10 to 15 years, the query would be like, SELECT first_name, last_name, age FROM student_details WHERE age BETWEEN 10 AND 15; The output would be similar to: first_name last_name age ------------- ------------- ------ Rahul Sharma 10 Anajali Bhagwat 12 Shekar Gowda 15
SQL IN Operator: The IN operator is used when you want to compare a column with more than one value. It is similar to an OR condition. For example: If you want to find the names of students who are studying either Maths or Science, the query would be like, SELECT first_name, last_name, subject FROM student_details WHERE subject IN ('Maths', 'Science'); The output would be similar to: first_name last_name subject ------------- ------------- ---------- Anajali Bhagwat Maths Shekar Gowda Maths Rahul Sharma Science Stephen Fleming Science You can include more subjects in the list like ('maths','science','history') NOTE:The data used to compare is case sensitive. SQL IS NULL Operator A column value is NULL if it does not exist. The IS NULL operator is used to display all the rows for columns that do not have a value. For Example: If you want to find the names of students who do not participate in any games, the query would be as given below SELECT first_name, last_name FROM student_details WHERE games IS NULL There would be no output as we have every student participate in a game in the table student_details, else the names of the students who do not participate in any games would be displayed.
SQL ORDER BY The ORDER BY clause is used in a SELECT statement to sort results either in ascending or descending order. Oracle sorts query results in ascending order by default. Syntax for using SQL ORDER BY clause to sort data is: SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1 [, column2, .. columnN] [DESC]]; database table "employee"; id name dept age salary location 100 Ramesh Electrical 24 25000 Bangalore 101 Hrithik Electronics 28 35000 Bangalore 102 Harsha Aeronautics 28 35000 Mysore 103 Soumya Electronics 22 20000 Bangalore 104 Priya InfoTech 25 30000 Mangalore For Example: If you want to sort the employee table by salary of the employee, the sql query would be. SELECT name, salary FROM employee ORDER BY salary; The output would be like name salary ---------- ---------- Soumya 20000 Ramesh 25000 Priya 30000 Hrithik 35000 Harsha 35000
ORDER BY
The query first sorts the result according to name and then displays it. You can also use more than one column in the ORDER BY clause. If you want to sort the employee table by the name and salary, the query would be like, SELECT name, salary FROM employee ORDER BY name, salary; The output would be like: name salary ------------- ------------Soumya 20000 Ramesh 25000 Priya 30000 Harsha 35000 Hrithik 35000 NOTE:The columns specified in ORDER BY clause should be one of the columns selected in the SELECT column list. You can represent the columns in the ORDER BY clause by specifying the position of a column in the SELECT list, instead of writing the column name. The above query can also be written as given below, SELECT name, salary FROM employee ORDER BY 1, 2;
By default, the ORDER BY Clause sorts data in ascending order. If you want to sort the data in descending order, you must explicitly specify it as shown below. SELECT name, salary FROM employee ORDER BY name, salary DESC; The above query sorts only the column 'salary' in descending order and the column 'name' by ascending order. If you want to select both name and salary in descending order, the query would be as given below. SELECT name, salary FROM employee ORDER BY name DESC, salary DESC; How to use expressions in the ORDER BY Clause? Expressions in the ORDER BY clause of a SELECT statement. For example: If you want to display employee name, current salary, and a 20% increase in the salary for only those employees for whom the percentage increase in salary is greater than 30000 and in descending order of the increased price, the SELECT statement can be written as shown below SELECT name, salary, salary*1.2 AS new_salary FROM employee WHERE salary*1.2 > 30000 ORDER BY new_salary DESC; The output for the above query is as follows. name salary new_salary ---------- ---------- ------------- Hrithik 35000 37000 Harsha 35000 37000 Priya 30000 36000 NOTE:Aliases defined in the SELECT Statement can be used in ORDER BY Clause.
SQL MAX(): This function is used to get the maximum value from a column. To get the maximum salary drawn by an employee, the query would be: SELECT MAX (salary) FROM employee; SQL MIN(): This function is used to get the minimum value from a column. To get the minimum salary drawn by an employee, he query would be: SELECT MIN (salary) FROM employee; SQL AVG(): This function is used to get the average value of a numeric column. To get the average salary, the query would be SELECT AVG (salary) FROM employee; SQL SUM(): This function is used to get the sum of a numeric column To get the total salary given out to the employees, SELECT SUM (salary) FROM employee;
SELECT location, dept, SUM (salary) FROM employee GROUP BY location, dept; The output would be like: location dept salary ------------- --------------- ----------Bangalore Electrical 25000 Bangalore Electronics 55000 Mysore Aeronautics 35000 Mangalore InfoTech 30000
When WHERE, GROUP BY and HAVING clauses are used together in a SELECT statement, the WHERE clause is processed first, then the rows that are returned after the WHERE clause is executed are grouped based on the GROUP BY clause. Finally, any conditions on the group functions in the HAVING clause are applied to the grouped rows before the final output is displayed.
Populated Database:
Query 10: Find the maximum salary, the minimum salary, and the average salary among all employees. Q10: SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY) FROM EMPLOYEE
Query 11: Find the maximum salary, the minimum salary, and the average salary among employees who work for the 'Research' department. Q11: SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY) FROM EMPLOYEE, DEPARTMENT WHERE DNO=DNUMBER AND DNAME='Research'
Group by
SQL has a GROUP BY-clause for specifying the grouping attributes, which must also appear in the SELECT-clause Query 12: For each department, retrieve the department number, the number of employees in the department, and their average salary. Q12: SELECT DNO, COUNT (*), AVG (SALARY) FROM EMPLOYEE GROUP BY DNO Query 13: For each project, retrieve the project number, project name, and the number of employees who work on that project. Q13: SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME
Query 14: For each project on which more than two employees work, retrieve the project number, project name, and the number of employees who work on that project. Q14: SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME HAVING COUNT (*) > 2
SQL TRUNCATE Statement The SQL TRUNCATE command is used to delete all the rows from the table and free the space containing the table. Syntax to TRUNCATE a table: TRUNCATE TABLE table_name; For Example: To delete all the rows from employee table, the query would be like, TRUNCATE TABLE employee; Difference between DELETE and TRUNCATE Statements: DELETE Statement: This command deletes only the rows from the table based on the condition given in the where clause or deletes all the rows from the table if no condition is specified. But it does not free the space containing the table. TRUNCATE statement: This command is used to delete all the rows from the table and free the space containing the table.
Syntax to add a column ALTER TABLE table_name ADD column_name datatype; For Example: To add a column "experience" to the employee table, the query would be like ALTER TABLE employee ADD experience number(3); Syntax to drop a column ALTER TABLE table_name DROP column_name; For Example: To drop the column "location" from the employee table, the query would be like ALTER TABLE employee DROP location; Syntax to modify a column ALTER TABLE table_name MODIFY column_name datatype; For Example: To modify the column salary in the employee table, the query would be like ALTER TABLE employee MODIFY salary number(15,2); SQL RENAME Command The SQL RENAME command is used to change the name of the table or a database object. If you change the object's name any reference to the old name will be affected. You have to manually change the old name to the new name in every reference. Syntax to rename a table RENAME old_table_name To new_table_name; For Example: To change the name of the table employee to my_employee, the query would be like RENAME employee TO my_emloyee;
For Example: To create an employee table with Primary Key constraint, the query would be like. Primary Key at table level: CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), salary number(10), location char(10) );
or CREATE TABLE employee ( id number(5) CONSTRAINT emp_id_pk PRIMARY KEY, name char(20), dept char(10), age number(2), salary number(10), location char(10) ); Primary Key at table level: CREATE TABLE employee ( id number(5), name char(20), dept char(10), age number(2), salary number(10), location char(10), CONSTRAINT emp_id_pk PRIMARY KEY (id) );
For Example: 1) Lets use the "product" table and "order_items". Foreign Key at column level: CREATE TABLE product ( product_id number(5) CONSTRAINT pd_id_pk PRIMARY KEY, product_name char(20), supplier_name char(20), unit_price number(10) ); CREATE TABLE order_items ( order_id number(5) CONSTRAINT od_id_pk PRIMARY KEY, product_id number(5) CONSTRAINT pd_id_fk REFERENCES, product(product_id), product_name char(20), supplier_name char(20), unit_price number(10) );
Foreign Key at table level: CREATE TABLE order_items ( order_id number(5) , product_id number(5), product_name char(20), supplier_name char(20), unit_price number(10) CONSTRAINT od_id_pk PRIMARY KEY(order_id), CONSTRAINT pd_id_fk FOREIGN KEY(product_id) REFERENCES product(product_id) ); 2) If the employee table has a 'mgr_id' i.e, manager id as a foreign key which references primary key 'id' within the same table, the query would be like, CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), mgr_id number(5) REFERENCES employee(id), salary number(10), location char(10) );
Unique Key at column level: CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), salary number(10), location char(10) UNIQUE ); or CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), salary number(10), location char(10) CONSTRAINT loc_un UNIQUE ); Unique Key at table level: CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), salary number(10), location char(10), CONSTRAINT loc_un UNIQUE(location) );
DEFAULT CONSTRAINT
DEFAULT to define the columns default value. CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), salary number(10) DEFAULT 0, location char(10) UNIQUE ); Not Null and Default constraints can be applied only at column level rest all constraints can be applied on both column level and table levels.
EXAMPLE : Let's try with 2 tables below: Table 1: GameScores PlayerName DepartmentId Scores Jason 1 3000 Irene 1 1500 Jane 2 1000 David 2 2500 Paul 3 2000 James 3 2000 Table 2: Departments DepartmentId DepartmentName 1 IT 2 Marketing 3 HR
If a sql join condition is omitted or if it is invalid the join operation will result in a Cartesian product. The Cartesian product returns a number of rows equal to the product of all rows in all the tables being joined. For example, if the first table has 20 rows and the second table has 10 rows, the result will be 20 * 10, or 200 rows. This query takes a long time to execute.
SQL Joins
SQL Joins are used to relate information in different tables. A Join condition is a part of the sql query that retrieves rows from two or more tables. A SQL Join condition is used in the SQL WHERE Clause of select, update, delete statements. The Syntax for joining two tables is: SELECT col1, col2, col3... FROM table_name1, table_name2 WHERE table_name1.col2 = table_name2.col1; Lets use the below two tables to explain the sql join conditions. database table "product"; product_id product_name supplier_name unit_price 100 Camera Nikon 300 101 Television Onida 100 102 Refrigerator Vediocon 150 103 Ipod Apple 75 104 Mobile Nokia 50 database table "order_items"; order_id product_id total_units customer 100 104 30 Infosys 5 101 102 5 Satyam 5 102 103 25 Wipro 5 103 101 10 TCS
Here we can easily understand that when multiple tables are joined they must have some column common in them and in select clause we can put an equality check to filter only a meaningful combination of records. SQL Joins can be classified into Equi join and Non Equi join. 1) SQL Equi joins It is a simple sql join condition which uses the equal sign as the comparison operator. Two types of equi joins are SQL Outer join and SQL Inner join. For example: You can get the information about a customer who purchased a product and the quantity of product. 2) SQL Non equi joins It is a sql join condition which makes use of some comparison operator other than the equal sign like >, <, >=, <=
SQL Subquery
Subquery or Inner query or Nested query is a query in a query. A subquery is usually added in the WHERE Clause of the sql statement. Most of the time, a subquery is used when you know how to search for a value using a SELECT statement, but do not know the exact value. Subqueries are an alternate way of returning data from multiple tables. Subqueries can be used with the following sql statements along with the comparision operators like =, <, >, >=, <= etc. SELECT INSERT UPDATE DELETE For Example: 1) Usually, a subquery should return only one record, but sometimes it can also return multiple records when used with operators like IN, NOT IN in the where clause. The query would be like, SELECT first_name, last_name, subject FROM student_details WHERE games NOT IN ('Cricket', 'Football'); The output would be similar to: first_name last_name subject ------------- ------------- ---------- Shekar Gowda Badminton Priya Chandra Chess
2) Lets consider the student_details table which we have used earlier. If you know the name of the students who are studying science subject, you can get their id's by using this query below, SELECT id, first_name FROM student_details WHERE first_name IN ('Rahul', 'Stephen'); but, if you do not know their names, then to get their id's you need to write the query in this manner, SELECT id, first_name FROM student_details WHERE first_name IN (SELECT first_name FROM student_details WHERE subject= 'Science'); Output: id first_name -------- ------------- 100 Rahul 102 Stephen In the above sql statement, first the inner query is processed first and then the outer query is processed.
3) Subquery can be used with INSERT statement to add rows of data from one or more tables to another table. Lets try to group all the students who study Maths in a table 'maths_group'. INSERT INTO maths_group(id, name) SELECT id, first_name || ' ' || last_name FROM student_details WHERE subject= 'Maths' 4) A subquery can be used in the SELECT statement as follows. Lets use the product and order_items table defined in the sql_joins section. select p.product_name, p.supplier_name, (select order_id from order_items where product_id = 101) as order_id from product p where p.product_id = 101 product_name supplier_name order_id ------------------ ------------------ ---------- Television Onida 5103 Correlated Subquery A query is called correlated subquery when both the inner query and the outer query are interdependent. For every row processed by the inner query, the outer query is processed as well. The inner query depends on the outer query before it can be processed. SELECT p.product_name FROM product p WHERE p.product_id = (SELECT o.product_id FROM order_items o WHERE o.product_id = p.product_id); NOTE: 1) You can nest as many queries you want but it is recommended not to nest more than 16 subqueries in oracle. 2) If a subquery is not dependent on the outer query it is called a non-correlated subquery.
MySQL Functions
A function is a special type of predefined command set that performs some operation and may return a single value. MySQL supports functions that can be used to manipulate data. Such functions can be used to manipulate data. 1) Single-row functions return a single result row for every row of a queried table. They are categorized into: Numeric functions, String functions, and Date and Time functions. 2) Group Functions: These functions group the rows of data based on the values returned by the query. This is discussed in SQL GROUP Functions. The group functions are used to calculate aggregate values like total or average, which return just one total or one average value after processing a group of rows.
There are four types of single row functions. They are: 1) Numeric Functions: These are functions that accept numeric input and return numeric values. 2) Character or Text Functions: These are functions that accept character input and can return both character and number values. 3) Date Functions: These are functions that take values that are of datatype DATE as input and return values of datatype DATE, except for the MONTHS_BETWEEN function, which returns a number. You can combine more than one function together in an expression. This is known as nesting of functions.
What is a DUAL Table in Oracle? This is a single row and single column dummy table provided by oracle. This is used to perform mathematical calculations without using a table. Select * from DUAL Output: DUMMY ------X Select 777 * 888 from Dual Output: 777 * 888 --------689976
1) Numeric Functions: Numeric functions are used to perform operations on numbers. They accept numeric values as input and return numeric values as output. Few of the Numeric functions are: The following examples explains the usage of the above numeric functions
Return Value Absolute value of the number 'x' Integer value that is Greater than or equal to the number 'x' Integer value that is Less than or equal to the number 'x' Truncates value of number 'x' up to 'y' decimal places Rounded off value of the number 'x' up to the number 'y' decimal places Returns the argument raised to the specified power. POW () works the same way.
FLOOR (x)
TRUNC (x, y)
ROUND (x, y)
POWER() :
Examples ABS (1) ABS (-1) CEIL (2.83) CEIL (2.49) CEIL (-1.6) FLOOR (2.83) FLOOR (2.49) FLOOR (-1.6) ROUND (125.456, 1) ROUND (125.456, 0) ROUND (124.456, -1) TRUNC (140.234, 2) TRUNC (-54, 1) TRUNC (5.7) TRUNC (142, -1)
CEIL (x)
FLOOR (x)
TRUNC (x, y)
ROUND (x, y)
POW(x,y)
For Example: Let's consider the product table used in sql joins. We can use ROUND to round off the unit_price to the nearest integer, if any product has prices in fraction. SELECT ROUND (unit_price) FROM product;
Character or Text Functions: Character or text functions are used to manipulate text strings. They accept strings or characters as input and can return both character and number values as output. Few of the character or text functions are as given below:
Function Name LOWER (string_value) UPPER (string_value) INITCAP (string_value) LTRIM (string_value, trim_text) RTRIM (string_value, trim_text)
Return Value All the letters in 'string_value' is converted to lowercase. All the letters in 'string_value' is converted to uppercase. All the letters in 'string_value' is converted to mixed case. All occurrences of 'trim_text' is removed from the left of 'string_value'. All occurrences of 'trim_text' is removed from the right of 'string_value' . All occurrences of 'trim_text' from the left and right of 'string_value' , 'trim_text' can also be only one character long . Returns 'n' number of characters from 'string_value' starting from the 'm' position.
SUBSTR (string_value, m, n)
LENGTH (string_value)
Returns 'string_value' left-padded with 'pad_value' . The length of the whole string will be of 'n' characters. Returns 'string_value' right-padded with 'pad_value' . The length of the whole string will be of 'n' characters. Returns concatenated string i.e. it adds strings. Returns the index of the first occurrence of substring. Returns the given number of characters by extracting them from the left side of the given string. Returns the given number of characters by extracting them from the right side of the given string. Returns a substring starting from the specified position in a given string.
CONCAT(): INSTR():
LEFT() :
RIGHT():
MID()/SUBSTR() :
Function Name LOWER(string_value) UPPER(string_value) INITCAP(string_value) LTRIM(string_value, trim_text) RTRIM (string_value, trim_text) TRIM (trim_text FROM string_value) SUBSTR (string_value, m, n) LENGTH (string_value)
Examples LOWER('Good Morning') UPPER('Good Morning') INITCAP('GOOD MORNING') LTRIM ('Good Morning', 'Good) RTRIM ('Good Morning', ' Morning') TRIM ('o' FROM 'Good Morning') SUBSTR ('Good Morning', 6, 7) LENGTH ('Good Morning')
Morning
Good
Gd Mrning
Morning 12
CONCAT( Informatics , , Practices ) INSTR( Informatics , mat ); : LEFT( INFORMATICS PRACTICES , 3); : RIGHT( INFORMATICS PRACTICES ,3); MID( INFORMATICS PRACTICES ,3,4);
3) Date Functions: These are functions that take values that are of datatype DATE as input and return values of datatypes DATE, except for the MONTHS_BETWEEN function, which returns a number as output. Few date functions are as given below.
NOW() : time
Result : '2010-07-
SYSDATE() : Return the time at which the function executes DATE() : Extracts the date part of a date or datetime expression MONTH() Returns the month from the date passed YEAR() : Returns the year CURDATE() : Returns the current date
Result: '2010-
Example: DATE('2003-12-31 01:02:03'); Result:: '2003-12-31' Example: MONTH('2010-0721'); Result : 7 YEAR('2010-07-21'); Result : 2010 Result: '2010-
Result :
DAYOFMONTH() : Returns the day of the month (0-31) DAYOFWEEK() : Returns the weekday index of the argument DAYOFYEAR() : year(1-366) Return the day of the
Example: DAYOFMONTH('2010-0721'); Result: 21 Example: DAYOFWEEK('2010-07-21'); Result: 4 (Sunday is counted as 1) Example: DAYOFYEAR('2010-0721'); Result: 202
EXAMPLES
teacher
NUMBER NAME AGE DEPARTMENT DATEOFJOIN SALARY SEX
JUGAL
34
COMPUTER
10/01/97
12000
PRATIGYA
31
HISTORY
24/03/98
20000
SANDEEP
32
MATHS
12/12/96
30000
SANGEETA
35
HISTORY
01/07/99
40000
SHYAM
50
MATHS
05/09/97
25000
SATTI
42
HISTORY
27/06/98
30000
SHIV OM
44
COMPUTER
25/02/97
40000
SHALKHA
33
MATHS
31/07/97
20000
Write SQL commands for the following: i.To show all the information about the teacher of History department. ii.To list the names of female teachers who are in Hindi department. iii.To list the names of the teachers with their date of joining in ascending order. iv.To list the details of all the teachers who s salary is between 20000 to 35000. V.Write command to list structure of above table. vi. To list the details of all the teachers having their name with first alphabet as S, 3rd character as I and ending with m . vii.Add new record with details as(9, Mohan ,55, Computer ,11970505,20000, M ); viii. Increase the salary of each teacher by 10%. ix. Add new column commission with datatype integer(5). x. List all the teachers having salary > 20000 and department as computer or maths.
schoolbus
Rtno Area_Covered Capacity Noofstudents Distance Transporter Charges
Vasant Kunj
100
120
10
Amit
1000
Hauz Khas
80
80
Rahul
850
Pitampura
80
70
30
Manoj
3000
Rohini
70
70
40
Mansukh
4000
Yamuna Vihar
70
65
45
Ramit
4200
Krishna Nagar
80
80
40
Neeraj
4100
Munirka
60
60
Lovely
850
Lajpat Nagar
70
70
10
Suri
1000
Saket
100
90
15
Raman
1200
10
South Ex
80
76
Govind
700
a) To show all information of students where capacity is more than the no of student in order of Rtno. Select * from SchoolBus where capacity > noofstuents (b) To show area_covered for buses covering more than 20 km., but charges less then 80000. Select Area_covered from SchoolBus where distance>20 and Charges<8000 (c) To show transporter wise total no. of students traveling. Select sum(Noofstudens), Transporter from SchoolBus group by Transporter (d) Add a new record with following data: (11, Moti bagh ,35,32,10, kisan tours , 35000) Insert into SchoolBus values(11, Moti bagh ,35,32,10, kisan tours , 35000) (e) Give the output considering the original relation as given: (i) Select sum (distance) from schoolbus where transporter= Yadav travels ; (ii) Select min (noofstudents) from schoolbus; (iii) Select avg(charges) from schoolbus where transporter= Anand travels ; (iv) Select distinct transporter from schoolbus;
GRADUATE
sno Name stipend subject average Division
Amit
1000
COMPUTER
35
III
2 3
Rahul Manoj
800 800
PHYSICS MATHS
68 70
I I
Mansukh
700
CHEMISTRY
50
II
Ramit
700
MATHS
75
6 7
Neeraj
800 600
CHEMISTRY COMPUTER
80 90
I I
Lovely
Suri
700
MATHS
78
Raman
1000
COMPUTER
75
10
Govind
800
PHYSICS
55
II
(a) List the names of those students who have obtained I DIV sorted by NAME. (b) Display a report, listing NAME, STIPEND, SUBJECT and amount of stipend received in a year assuming that the STIPEND is paid every month. (c) To count the number of students who are either PHYSICS or COMPUTER SC graduates. (d) To insert a new row in the GRADUATE table: 11, KAJOL , 300, computer sc , 75, 1 (e) Give the output of following sql statement based on table GRADUATE: (i) Select MIN(AVERAGE) from GRADUATE where SUBJECT= PHYSICS ; (ii) Select SUM(STIPEND) from GRADUATE WHERE div=2; (iii) Select AVG(STIPEND) from GRADUATE where AVERAGE>=65; (iv) Select COUNT(distinct SUBDJECT) from GRADUATE; (f) Assume that there is one more table GUIDE in the database as shown below:
Employee
empid 101 202 301 FirstName Amit Rahul Manoj LastName Rastogi Mishra Chadha Address 50 A,Vasant Kunj R-129,Hauz Khas M78,streetno90Pita mpura Rohini 60.GH,Yamuna Vihar 112,Krishna Nagar A-90,Munirka 3-A,Lajpat Nagar IV 1-B,Saket B-6,South ExII City N Delhi N Delhi N Delhi
Empsalary
empid 101 202 301 104 500 611 117 808 923 106 salary 10000 8000 8000 7000 7000 8000 60000 7000 100000 8000 Benefits 4000 600 800 700 900 900 9000 700 10000 800 Designation Manager Salesman Salesman Manager Clerk Clerk Director clerk Director Clerk
Write the SQL commands for the following : (i) To show firstname,lastname,address and city of all employees living in paris (ii) To display the content of Employees table in descending order of Firstname. (iii) To display the firstname,lastname and total salary of all managers from the tables Employee and empsalary , where total salary is calculated as salary+benefits. (iv) To display the maximum salary among managers and clerks from the table Empsalary. Give the Output of following SQL commands: (i) Select firstname,salary from employees ,empsalary where designation = Salesman and Employees.empid=Empsalary.empid; (ii) Select count(distinct designation) from empsalary; (iii) Select designation, sum(salary) from empsalary group by designation having count(*) >2; (iv) Select sum(benefits) from empsalary where designation = Clerk ;
Product
Pcode P001 P002 P003 P004 P005 Pname TV TV PC PC Handycam Company BPL Sony LenvQ Comapq Sony Price 10000 12000 29000 35000 20000 Stock 200 150 234 100 135 Manufacture 12-jan-2008 23-mar-2007 09-apr-2009 20-jun-2009 23-mar-2007 Warranty 3 4 2 2 3
Write MySQL commands for following Statements i. To show details of all the PC with stock more than 110. [1] ii. To list the company which gives warranty for more than 2 years. [1] iii. To find stock value of the BPL company where stock value is sum of the products of price and stock. [1] iv. To show number of products from each company. [1] v. To count the number of PRODUCTS which are manufactured in 2009. [1] vi. To show the PRODUCT name which are within warranty as on date. [1] (c) Give the output of following MySQL statement. [4] (i) Select COUNT (distinct company) from PRODUCT; (ii) Select MAX (price) from PRODUCT where WARRANTY<=3; (iii) select AVG (price) from PRODUCT where Company= SONY ; (iv) Select MIN (price) from PRODUCT where stock<200;
SELECT * FROM PRODUCT WHERE PNAME = PC AND STOCK > 110; viii. SELECT COMPANY FROM PRODUCT WHERE WARRANTY > 2; ix. SELECT PRICE * STOCK STOCK VALUE FROM PRODUCT WHERE COMPANY = BPL ; x. SELECT COMPANY, COUNT(DISTINCT PNAME) PRODUCTS FROM PRODUCT GROUP BY COMPANY; xi. SELECT COUNT (*) FROM PRODUCT WHERE YEAR(MANUFACTURE ) = 2009; xii. SELECT PNAME FROM PRODUCT WHERE YEAR(CURDATE()- MANUFACTURE) <= WARRANTY; (c) Give the output of following MySQL statement. [4] i. 4 ii. 39000 iii. 15000 iv. 12000
staff
empid 101 202 301 104 500 611 117 808 923 106 FirstName Amita Rahul Manoj Mansukh Ramita Neeraj Lovely Surinder Raman Govind Dept Sales Finance Research Sales Research Finance Sales Finance Research Sales SEX F M M M F M F F M M Experience 10 12 6 5 3 6 7 8 3 2
salary
empid 101 202 301 104 500 611 117 808 923 106 salary 10000 8000 8000 7000 7000 8000 60000 7000 100000 8000 Allowance 4000 600 800 700 900 900 9000 700 10000 800 Commission 500 600 800 700 3000 600 600 3000 1000 500
(i) Display NAME of all the staff who is in SALES having more than 10 year experience from the table staff. [1] (ii) Display the average Basic Salary of all staff working in Finance department using the table staff and salary. [1] (iii) Display the minimum ALLOWANCE of female staff. [1] (iv) Display the highest commission among all male staff [1] (v) Select count(*) from STAFF where sex= F ; [1] (vi) SELECT NAME,DEPT,BASIC FROM STAFF,SALARY WHERE DEPT= SALES AND STAFF.ID=SALARY.ID;
. SELECT NAME FROM STAFF WHERE DEPT = Sales AND EXPERIENCE > 10; II. SELECT AVG(Basic) FROM STAFF, SALARY WHERE STAFF.ID = SALARY.ID AND DEPT = Finance ; III. SELECT MIN(Allowance) FROM STAFF, SALARY WHERE STAFF.ID = SALARY.ID AND SEX = F ; IV. SELECT MAX(Commission) FROM STAFF, SALARY WHERE STAFF.ID = SALARY.ID AND SEX = M ; V. 4 VI. Name DEPT Basic Siddharat Sales 15000 Nupur Sales 20000 James Sales 18000 Samuel Sales 18000