Upload
poisonedheart
View
225
Download
0
Embed Size (px)
Citation preview
8/8/2019 SQL Query Tutorial
http://slidepdf.com/reader/full/sql-query-tutorial 1/12
Data Definition Language
- Create (database or table)
- Alter ( Table)
- Drop ( Database or Table)
- Rename (Table)
DROP – DDL command that allows us to remove entire database objects from the RDMS. This also allows
to remove the entire table structure from the database.
Syntax: DROP TABLE tablename
DROP DATABASE database name
Note : Use this command with care!!!!
ALTER = command allows you to make changes to the structure of a table without deleteing and creating
it.
ALTER TABLE Clauses
Clause Usage Meaning Example
ADD COLUMN ALTER TABLE tablenameADD COLUMN column namedatatype()
Add new columnto the end of thetable
ALTER TABLEEmployeeADD COLUMNSalary int(10)
CHANGE COLUMN ALTER TABLE tablenameCHANGE COLUMN columnname1 column name2datatype
Allows you tochange the datatype and columnname
ALTER TABLEEmployeeCHANGECOLUMN SalarySALDecimal(10.2)
DROP COLUMN ALTER TABLE tablenameDROP COLUMN column name
Removes columnfrom a table
including of itsdata
ALTER TABLEEmployee
DROP COLUMNContact
ADD INDEX ALTER TABLE tablenameADD INDEX index name(column name)
Add new index oncolumn name
ALTER TABLEEmployeeADD INDEXSal_Index (SAL))
DROP INDEX ALTER TABLE tablenameDROP INDEX index name
Removes existingindex
ALTER TABLEEmployeeDROP INDEXSal_Index
RENAME AS ALTER TABLE tablenameRENAME AS new tablename
Change the nameof the table
ALTER TABLEEmployee
RENAME ASEmp;
NOTE:
- ALTER command could have serious repercussions on a table you should always back-up the table
before execution.
- The word “column” in most ALTER statement is optional
- When adding a new column to a table, you can use the “AFTER” command to indicate where in the
table the new column should be placed.
o ALTER TABLE clients
8/8/2019 SQL Query Tutorial
http://slidepdf.com/reader/full/sql-query-tutorial 2/12
ADD COLUMN contact char(20)
AFTER contact_last_name;
QUERIES
Logical Operators = reduce to either TRUE (1) or FALSE (0)
OPERATOR SYNTAX DESCRIPTION EXAMPLE
AND , && C1 AND C2
C1 && C2
Only true if both
conditions are true
Select 1 and 0; Results is
0OR, || C1 OR C2
C1 || C2True if either C1 or C2 istrue
Select 1 OR 0; Result is1
NOT, ! !C1 , NOT C2 True if C1 is False, Falseif C1 is true
Select Not (1 and 0);Result is 1Select NOT(1 OR 0);Result is 0
Arithmetic Operators are used to perform basic mathematical operations.
OPERATOR SYNTAX DESCRIPTION EXAMPLE+ a + b Adding 2 or more
elements and return thesum
Select 4 + 8 ; = 12
- a - b Select 4 – 2; = 2* a * b Subtracting 2 or more
elements and return thedifference
Select % * 3 ; = 15
/ a / b Divide 2 or moreelements and return thequotient
Select 4/2 ; = 2
% a % b A modulus, returning the
remainder after division
Select 5 % 3 = 2
Select ‘abc’ = ‘ABC’ ; result is 1 or true
Select ‘4200’ = 4200.0 ; result is 1 or true
Note: In MYSSQL , if you are comparing strings or numerics or floating point numbers and integer, it will
compare than as if they were the same type.
Between Operator = is used to display recordsor rows based on a range of values. The range contains a
lower range and an upper range.
Example :
SELECT 3 between 2 and 4; Result is 1
SELECT 5 between 6 and 4; Result is 0 because the first range is the lower range.
SELECT first_name, last_name, start_data
FROM Emp
WHERE start_date between ’09-May-08’ and ’09-May-09’;
If character or dates are used in the range or list, they may enclosed in single quotation.
8/8/2019 SQL Query Tutorial
http://slidepdf.com/reader/full/sql-query-tutorial 3/12
LIKE Operator – used to match a character, pattern to select rows or records. The character pattern matching
operation is referred to as “wild card” search.
Wild Card Character
% = represent any sequence of zero or more characters
Example:
SELECT last_name
FROM emp
WHERE last_name LIKE ‘M%’
This example will show records that has last_name start in ‘M’
_ (Under Score) – it represents any single character.
Example:
SELECT last_name
FROM emp
WHERE last_name LIKE ‘__ng’
This example will show records that has last_name that ends in ‘ng’ and have only 4 character.
What is Join?
Join = is used to query data from more than one table. Rows are joined using common values, typically
primary and foreign key values.
For Example :
SELECT e.emp_name, d.dept_name
FROM Employee as e, department as d
WHERE e.dept_id = d.dept_id;
Cartesian Product = this is formed when:
- A join is omitted
- A Join condition is invalid
- All rows in the first table are joined to all rows in the second table.
Example: SELECT name, dept_id From employee, department;
This will show all the rows of the second table even if are not related or no link.
Table for Reference:
EMPLOYEE CUSTOMERName ID Sales_Rep_ID Customer_Name
Ela 100 100 Bench
Dom 200 200 GAP
Von 300 200 LEE
Drex 400 400 POLO
Jeck 500 500 JAG
Vernice 600 Dickes
Airen 700Bayo
8/8/2019 SQL Query Tutorial
http://slidepdf.com/reader/full/sql-query-tutorial 4/12
Equi-Join = relationship between two tables where both table has equal values in a field or column (primary
and foreign key). This may also be called inner join.
SELECT Name, Sales_Rep_ID, Customer_Name
FROM employee, customer
Where ID = Sales_Rep_ID;
Results:
EMPLOYEE CUSTOMER
Name ID Sales_Rep_ID Customer_Name
Ela 100 100 Bench
Dom 200 200 GAP
Dom 200 200 LEEDrex 400 400 POLO
Jeck 500 500 JAG
Left Outer Join = this is used to display all the rows of the left table that have null values that did not match to
the right table in the SELECT statement.
SELECT Name, Sales_Rep_ID, Customer_Name
FROM employee LEFT JOIN customer
ON ID = Sales_Rep_ID;
Results:
EMPLOYEE CUSTOMER
Name ID Sales_Rep_ID Customer_Name
Ela 100 100 BenchDom 200 200 GAP
Dom 200 200 LEE
Drex 400 400 POLO
Jeck 500 500 JAG
null null Dickes
null null Bayo
Right Outer Join = this is used to display all the rows of the right table that have null values that did not match
to the left table in the SELECT statement.
SELECT Name, Sales_Rep_ID, Customer_Name
FROM employee RIGHT JOIN customer
ON ID = Sales_Rep_ID;
Results:
EMPLOYEE CUSTOMER
Name ID Sales_Rep_ID Customer_Name
Ela 100 100 BenchDom 200 200 GAP
8/8/2019 SQL Query Tutorial
http://slidepdf.com/reader/full/sql-query-tutorial 5/12
Dom 200 200 LEE
Drex 400 400 POLOJeck 500 500 JAG
Vernice 600 null Null
Airen 700 null null
REMEMBER: Remember that a Right Join reads all records from the right table including rows, while Left Join
reads all records from the left table including null values.
Full Outer Join = These are joins where record from the first table, including those with no match in the
second table is returned along with each record in the second table, including those with no match in the first
table.
Example:
SELECT Name, Sales_Rep_ID, Customer_Name
FROM employee FULL OUTER JOIN customer
ON ID = Sales_Rep_ID;
EMPLOYEE CUSTOMER
Name ID Sales_Rep_ID Customer_NameEla 100 100 Bench
Dom 200 200 GAP
Von 300 200 LEE
Drex 400 400 POLO
Jeck 500 500 JAG
Vernice 600 null null
Airen 700 null null
null null Null Dickes
null null null Bayo
UNION = this statement combines the result of different SELECT statement into one
Limiting Query Results:
Another SQL term you can add to your SELECT statement is LIMIT. This states how many records
to return.
For Example:
SELECT * from EMP LIMIT 10; - this will show records from EMP table from 1 - 10 or initially 10
records.
SELECT * from EMP LIMIT 10, 20 ; - this will show records from EMP table from 10 - 20 .
You can use LIMIT with Where and/or ORDER BY Clause.
8/8/2019 SQL Query Tutorial
http://slidepdf.com/reader/full/sql-query-tutorial 6/12
For Example:
SELECT * FROM EMP
WHERE DEPT_ID < 400
ORDER BY DEPT_ID ASC LIMIT 1; This will show only 1 record which is the least number of
DEPT_ID.
Aggregate Functions
Aggregate functions return a single value based upon a set of other values. If used among many other expressions in the item list of a SELECT statement, the SELECT must have a GROUP BY clause. No GROUP
BY clause is required if the aggregate function is the only value retrieved by the SELECT statement. Thesupported aggregate functions and their syntax are listed in Table 4-1.
Table 4-1: SQL Aggregate Functions
Function Usage
AVG(expression) Computes the average value of a column by the expression
COUNT(expression) Counts the rows defined by the expression
COUNT(*) Counts all rows in the specified table or view
MIN(expression) Finds the minimum value in a column by the expression
MAX(expression) Finds the maximum value in a column by the expression
SUM(expression) Computes the sum of column values by the expression
AVG and SUM
The AVG function computes the average of values in a column or an expression. SUM computes the sum. Bothfunctions work with numeric values and ignore NULL values. They also can be used to compute the average or sum of all distinct values of a column or expression.
AVG and SUM are supported by Microsoft SQL Server, MySQL, Oracle, and PostgreSQL.
Example
The following query computes average year-to-date sales for each type of book:
SELECT type, AVG( ytd_sales ) AS "average_ytd_sales"
FROM titlesGROUP BY type;
This query returns the sum of year-to-date sales for each type of book:
SELECT type, SUM( ytd_sales )FROM titlesGROUP BY type;
COUNT
8/8/2019 SQL Query Tutorial
http://slidepdf.com/reader/full/sql-query-tutorial 7/12
The COUNT function has three variations. COUNT(*) counts all the rows in the target table whether theyinclude nulls or not. COUNT(expression) computes the number of rows with non-NULL values in a specificcolumn or expression. COUNT(DISTINCT expression) computes the number of distinct non-NULL values in acolumn or expression.
Examples
This query counts all rows in a table:
SELECT COUNT(*) FROM publishers;
The following query finds the number of different countries where publishers are located:
SELECT COUNT(DISTINCT country) "Count of Countries"FROM publishers
MIN and MAX
MIN(expression) and MAX(expression) find the minimum and maximum value (string, datetime, or numeric) in
a set of rows. DISTINCT or ALL may be used with these functions, but they do not affect the result.
MIN and MAX are supported by Microsoft SQL Server, MySQL, Oracle, and PostgreSQL.
MySQL also supports the functions LEAST( ) and GREATEST( ), providing the same capabilities.
Examples
The following query finds the best and worst sales for any title on record:
SELECT 'MIN' = MIN(ytd_sales), 'MAX' = MAX(ytd_sales)FROM titles;
Aggregate functions are used often in the HAVING clause of queries with GROUP BY . The following queryselects all categories (types) of books that have an average price for all books in the category higher than$15.00:
SELECT type 'Category', AVG( price ) 'Average Price'FROM titlesGROUP BY typeHAVING AVG(price) > 15
Built-in Scalar Functions
Built-in scalar functions identify the current user session, and also characteristics of the current user session,such as the current session privileges. Built-in scalar functions are almost always nondeterministic. The firstthree functions listed in Table 4-3 are built-in functions that fall into the date-and-time category of functions.Although the four vendors provide many additional functions beyond these SQL built-ins, the SQL standarddeclares only those listed in Table 4-3.
Table 4-3: SQL99 Built-in Scalar Functions
8/8/2019 SQL Query Tutorial
http://slidepdf.com/reader/full/sql-query-tutorial 8/12
Function Usage
CURRENT_DATE Identifies the current date.
CURRENT_TIME Identifies the current time.
CURRENT_TIMESTAMP Identifies the current date and time.
CURRENT_USER Identifies the currently active user within the database server.
SESSION_USER Identifies the currently active Authorization ID, if it differs from the user.
SYSTEM_USER Identifies the currently active user within the host operating system.
Microsoft SQL Server supports all the built-in scalar functions.
Example
The following queries retrieve the values from built-in functions. Notice that the various vendors return dates intheir native formats:
/* On MySQL */SELECT CURRENT_TIMESTAMP;-> '2009-12-15 23:50:26' /* On Microsoft SQL Server */SELECT CURRENT_TIMESTAMPGO-> 'Dec 15,2009 23:50:26' /* On Oracle */SELECT USER FROM dual;-> dylan
String Functions
Basic string functions offer a number of capabilities and return a string value as a result set. Some stringfunctions are dyadic, indicating that they operate on two strings at once. SQL99 supports the string functionslisted in Table 4-6.
Table 4-6: SQL String Functions
Function Usage
CONCATENATE
(expression ||expression)
Appends two or more literal expressions, column values, or variables together into one
string.
CONVERT Converts a string to a different representation within the same character set.
LOWER Converts a string to all lowercase characters.
SUBSTRING Extracts a portion of a string.
TRANSLATE Converts a string from one character set to another.
TRIM Removes leading characters, trailing characters, or both from a character string.
UPPER Converts a string to all uppercase characters.
8/8/2019 SQL Query Tutorial
http://slidepdf.com/reader/full/sql-query-tutorial 9/12
CONCATENATE
The CONCATENATE function appends two or more strings together, producing a single output string.PostgreSQL and Oracle support the double-pipe concatenation operator. Microsoft SQL Server uses the plussign (+) concatenation operator.
MySQL Syntax
CONCAT(str1, str2, [,...n])
If any of the concatenation values are null, the entire returned string is null. Also, if a numeric value isconcatenated, it is implicitly converted to a character string:
SELECT CONCAT('My ', 'bologna ', 'has ', 'a ', 'first ', 'name...');-> 'My bologna has a first name...'SELECT CONCAT('My ', NULL, 'has ', 'first ', 'name...');-> NULL
LOWER and UPPER
The functions LOWER and UPPER allow the case of a string to be altered quickly and easily, so that all thecharacters are lower- or uppercase, respectively. These functions are supported in all the databaseimplementations covered in this book.
Example
SELECT LOWER('You Talkin To ME?'), UPPER('you talking to me?!');-> you talking to me?, YOU TALKIN TO ME?!
The various database vendors also support a variety of other text formatting functions that are specific to their implementation.
SUBSTRING
MySQL Syntax and Variations
SUBSTRING(extraction_string FROM starting_position)
MySQL's implementation assumes that the characters are to be extracted from the starting position continuingto the end of the character string.
Microsoft SQL Server Syntax and Variations
SUBSTRING(extraction_string [FROM starting_position] [FOR length])
Examples:
/* On MySQL */SELECT SUBSTRING('Be vewy, vewy quiet',5);-> 'wy, vewy quiet''
8/8/2019 SQL Query Tutorial
http://slidepdf.com/reader/full/sql-query-tutorial 10/12
TRIM
The TRIM function removes leading spaces, trailing characters, or both from a specified character string. Thisfunction also removes other types of characters from a specified character string. The default function is to trimthe specified character from both sides of the character string. If no removal string is specified, TRIM removesspaces by default.
Examples
SELECT TRIM(' wamalamadingdong ');-> 'wamalamadingdong'
The GROUP BY Statement
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.
SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
SQL GROUP BY Example
We have the following "Orders" table:
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
Now we want to find the total sum (total order) of each customer.
We will have to use the GROUP BY statement to group the customers.
We use the following SQL statement:
SELECT Customer,SUM(OrderPrice) FROM Orders
8/8/2019 SQL Query Tutorial
http://slidepdf.com/reader/full/sql-query-tutorial 11/12
GROUP BY Customer
The result-set will look like this:
Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000
The HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregatefunctions.
SQL HAVING Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
SQL HAVING Example
We have the following "Orders" table:
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
Now we want to find if any of the customers have a total order of less than 2000.
We use the following SQL statement:
8/8/2019 SQL Query Tutorial
http://slidepdf.com/reader/full/sql-query-tutorial 12/12
SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000
The result-set will look like this:
Customer SUM(OrderPrice)
Nilsen 1700
Now we want to find if the customers "Hansen" or "Jensen" have a total order of more than 1500.
We add an ordinary WHERE clause to the SQL statement:
SELECT Customer,SUM(OrderPrice) FROM Orders
WHERE Customer='Hansen' OR Customer='Jensen'
GROUP BY Customer
HAVING SUM(OrderPrice)>1500
The result-set will look like this:
Customer SUM(OrderPrice)
Hansen 2000
Jensen 2000