SQL Query Tutorial
SQL Query Tutorial
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.
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
ADD COLUMN contact char(20)
AFTER contact_last_name;
QUERIES
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.
If character or dates are used in the range or list, they may enclosed in single quotation.
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’
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;
EMPLOYEE CUSTOMER
Name 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 700
Bayo
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.
Results:
EMPLOYEE CUSTOMER
Name ID Sales_Rep_ID Customer_Name
Ela 100 100 Bench
Dom 200 200 GAP
Dom 200 200 LEE
Drex 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.
Results:
EMPLOYEE CUSTOMER
Name ID Sales_Rep_ID Customer_Name
Ela 100 100 Bench
Dom 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.
Results:
EMPLOYEE CUSTOMER
Name ID Sales_Rep_ID Customer_Name
Ela 100 100 Bench
Dom 200 200 GAP
Dom 200 200 LEE
Drex 400 400 POLO
Jeck 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:
EMPLOYEE CUSTOMER
Name 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 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
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 .
For Example:
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. The
supported aggregate functions and their syntax are listed in Table 4-1.
The AVG function computes the average of values in a column or an expression. SUM computes the sum. Both
functions 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:
This query returns the sum of year-to-date sales for each type of book:
COUNT
The COUNT function has three variations. COUNT(*) counts all the rows in the target table whether they
include nulls or not. COUNT(expression) computes the number of rows with non-NULL values in a specific
column or expression. COUNT(DISTINCT expression) computes the number of distinct non-NULL values in a
column or expression.
Examples
The following query finds the number of different countries where publishers are located:
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:
Aggregate functions are used often in the HAVING clause of queries with GROUP BY. The following query
selects all categories (types) of books that have an average price for all books in the category higher than
$15.00:
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 first
three 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 standard
declares only those listed in Table 4-3.
Function Usage
CURRENT_DATE Identifies the current date.
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.
Example
The following queries retrieve the values from built-in functions. Notice that the various vendors return dates in
their native formats:
/* On MySQL */
SELECT CURRENT_TIMESTAMP;
-> '2009-12-15 23:50:26'
/* On Microsoft SQL Server */
SELECT CURRENT_TIMESTAMP
GO
-> '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 string
functions are dyadic, indicating that they operate on two strings at once. SQL99 supports the string functions
listed in Table 4-6.
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 plus
sign (+) concatenation operator.
MySQL Syntax
If any of the concatenation values are null, the entire returned string is null. Also, if a numeric value is
concatenated, 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
The functions LOWER and UPPER allow the case of a string to be altered quickly and easily, so that all the
characters are lower- or uppercase, respectively. These functions are supported in all the database
implementations covered in this book.
Example
The various database vendors also support a variety of other text formatting functions that are specific to their
implementation.
SUBSTRING
MySQL's implementation assumes that the characters are to be extracted from the starting position continuing
to the end of the character string.
Examples:
/* On MySQL */
SELECT SUBSTRING('Be vewy, vewy quiet',5);
-> 'wy, vewy quiet''
TRIM
The TRIM function removes leading spaces, trailing characters, or both from a specified character string. This
function also removes other types of characters from a specified character string. The default function is to trim
the specified character from both sides of the character string. If no removal string is specified, TRIM removes
spaces by default.
Examples
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or
more columns.
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.
Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate
functions.
Now we want to find if any of the customers have a total order of less than 2000.
Customer SUM(OrderPrice)
Nilsen 1700
Now we want to find if the customers "Hansen" or "Jensen" have a total order of more than 1500.
Customer SUM(OrderPrice)
Hansen 2000
Jensen 2000