0% found this document useful (0 votes)
15 views29 pages

Dblab 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views29 pages

Dblab 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

LAB 3 # manual introduction to MySQL

Contents
1. Introduction to Mysql , SQL , data types (String, numeric , date time )
2. Create , Use , Select commands
3. Order by clause
4. Aggregate functions (count , sum , avg , min , max, group_concat, first , last)

Introduction
 Structured data tables , rows , columns (text)
 Structure query language
 Sql vs mysql

Data types

String :
Numeric:

Date and time:


Commands:
Create

Create command creates a database if its not exists before

Example,

Select:

Capabilities of SQL SELECT Statements

A SELECT statement retrieves information from the database. With a SELECT statement, you can
use the following capabilities:

• Projection: Select the columns in a table that are returned by a query. Select as few or as many
of the columns as required.

• Selection: Select the rows in a table that are returned by a query. Various criteria can be used
to restrict the rows that are retrieved.

• Joining: Bring together data that is stored in different tables by specifying the link between
them. SQL joins are covered in more detail in the lesson titled ―Displaying Data from Multiple
Tables.‖
Basic SELECT Statement

Syntax:
In its simplest form, a SELECT statement must include the following:
• A SELECT clause, which specifies the columns to be displayed
• A FROM clause, which identifies the table containing the columns that are listed in
the SELECT clause
In the syntax:
SELECT is a list of one or more columns
* selects all columns
DISTINCT suppresses duplicates
column|expression selects the named column or the expression
alias gives the selected columns different headings
FROM table specifies the table containing the columns

Note: Throughout this course, the words keyword, clause, and statement are used as follows:
• A keyword refers to an individual SQL element. For example, SELECT and FROM
are keywords.
• A clause is a part of a SQL statement. For example, SELECT employee_id,
last_name, and so on is a clause.
• A statement is a combination of two or more clauses. For example, SELECT * FROM
employees is a SQL statement.
Selecting All Columns
You can display all columns of data in a table by following the SELECT keyword with an
asterisk (*). The department table contains four columns: DEPARTMENT_ID,
DEPARTMENT_NAME, MANAGER_ID, and LOCATION_ID. The table contains eight
rows, one for each department.
Example:
SELECT *
FROM departments;

Output:
You can also display all columns in the table by listing all the columns after the SELECT
keyword. For example, the following SQL statement (like the example in the slide) displays all
columns and all rows of the DEPARTMENTS table:
SELECT department_id, department_name, manager_id, location_id
FROM departments;

Selecting Specific Columns


You can use the SELECT statement to display specific columns of the table by specifying the
column names, separated by commas. Above example displays all the department numbers and
location numbers from the DEPARTMENTS table.
In the SELECT clause, specify the columns that you want in the order in which you want them
to appear in the output. For example, to display location before department number (from left
to right), you use the following statement:
Example:
SELECT location_id, department_id
FROM departments;

Writing SQL Statements


By using the following simple rules and guidelines, you can construct valid statements that
are both easy to read and edit:
• SQL statements are not case-sensitive (unless indicated).
• SQL statements can be entered on one or many lines.
• Keywords cannot be split across lines or abbreviated.
• Clauses are usually placed on separate lines for readability and ease of editing.
• Indents should be used to make code more readable.
• Keywords typically are entered in uppercase; all other words, such as table names and
columns names are entered in lowercase.
Arithmetic Expressions

You may need to modify the way in which data is displayed, or you may want to perform calculations,
or look at what-if scenarios. All these are possible using arithmetic expressions. An arithmetic
expression can contain column names, constant numeric values, and the arithmetic operators.

Arithmetic Operators

Operator Description

+ Add

- Subtract

* Multiply

/ Divide

Using Arithmetic Operators


Example:
SELECT last_name, salary, salary + 300
FROM employees;
This example uses the addition operator to calculate a salary increase of $300 for all
employees. The slide also displays a SALARY+300 column in the output.
Note that the resultant calculated column, SALARY+300, is not a new column in the
EMPLOYEES table; it is for display only. By default, the name of a new column comes from
the calculation that generated it—in this case, salary+300.
Note: The Oracle server ignores blank spaces before and after the arithmetic operator.
Output:

Operator Precedence
If an arithmetic expression contains more than one operator, multiplication and division are
evaluated first. If operators in an expression are of the same priority, then evaluation is done
from left to right.
You can use parentheses to force the expression that is enclosed by the parentheses to be
evaluated first.
Rules of Precedence:
• Multiplication and division occur before addition and subtraction.
• Operators of the same priority are evaluated from left to right.
• Parentheses are used to override the default precedence or to clarify the statement.

Example 1:
SELECT last_name, salary, 12*salary+100
FROM employees;
Output:
Example2 :

SELECT last_name, salary, 12*(salary+100)


FROM employees;

Output:

The first example in the slide displays the last name, salary, and annual compensation of employees. It
calculates the annual compensation by multiplying the monthly salary with 12, plus a one-time bonus
of $100. Note that multiplication is performed before addition.

Note: Use parentheses to reinforce the standard order of precedence and to improve clarity. For example,
the expression in the slide can be written as (12*salary)+100 with no change in the result.

Using Parentheses

You can override the rules of precedence by using parentheses to specify the desired order in which the
operators are to be executed.

The second example in the slide displays the last name, salary, and annual compensation of employees.
It calculates the annual compensation as follows: adding a monthly bonus of $100 to the monthly salary,
and then multiplying that subtotal with 12. Because of the parentheses, addition takes priority over
multiplication.

Defining a Null Value

If a row lacks a data value for a particular column, that value is said to be null or to contain a null.

Null is a value that is unavailable, unassigned, unknown, or inapplicable. Null is not the same as zero or
a blank space. Zero is a number and blank space is a character.

Columns of any data type can contain nulls. However, some constraints (NOT NULL and
PRIMARY KEY) prevent nulls from being used in the column.

In the COMMISSION_PCT column in the EMPLOYEES table, notice that only a sales manager or sales
representative can earn a commission. Other employees are not entitled to earn commissions. A null
represents that fact.
Example:

SELECT last_name, job_id, salary, commission_pct

FROM employees;

Output:

Null Values in Arithmetic Expressions

If any column value in an arithmetic expression is null, the result is null. For example, if you attempt to
perform division by zero, you get an error. However, if you divide a number by null, the result is a null
or unknown.

Example:

SELECT last_name, 12*salary*commission_pct

FROM employees;
Output:

In the example, employee King does not get any commission. Because the
COMMISSION_PCT column in the arithmetic expression is null, the result is null.

Column Alias

When displaying the result of a query, SQL Developer normally uses the name of the selected column
as the column heading. This heading may not be descriptive and, therefore, may be difficult to
understand. You can change a column heading by using a column alias.

Specify the alias after the column in the SELECT list using blank space as a separator. By default, alias
headings appear in uppercase. If the alias contains spaces or special characters (such as # or $), or if it
is case-sensitive, enclose the alias in double quotation marks (― ‖).

Example 1:

SELECT last_name AS name, commission_pct comm

FROM employees;

Output:
Example 2:

SELECT last_name "Name”, salary*12 "Annual Salary"

FROM employees;

Output:

Concatenation Operator:

You can link columns to other columns, arithmetic expressions, or constant values to create a character
expression by using the concatenation operator (||). Columns on either side of the operator are combined
to make a single output column.

Example:

SELECT last_name||job_id AS "Employees"


FROM employees;

Output:
In the example, LAST_NAME and JOB_ID are concatenated, and given the alias Employees. Note that
the last name of the employee and the job code are combined to make a single output column.

The AS keyword before the alias name makes the SELECT clause easier to read. Null
Values with the Concatenation Operator

If you concatenate a null value with a character string, the result is a character string. LAST_NAME
|| NULL results in LAST_NAME.

Note: You can also concatenate date expressions with other expressions or columns.

Literal Character Strings

A literal is a character, a number, or a date that is included in the SELECT list. It is not a column name
or a column alias. It is printed for each row returned. Literal strings of free- format text can be included
in the query result and are treated the same as a column in the SELECT list.

Date and character literals must be enclosed within single quotation marks (' '); number literals need not
be enclosed in a similar manner.

Example:

SELECT last_name ||' is a '||job_id AS "Employee Details"


FROM employees;

Output:
The above example displays the last names and job codes of all employees. The column has the heading
Employee Details. Note the spaces between the single quotation marks in the SELECT statement. The
spaces improve the readability of the output.

Alternative Quote (q) Operator

Many SQL statements use character literals in expressions or conditions. If the literal itself contains a
single quotation mark, you can use the quote (q) operator and select your own quotation mark delimiter.

You can choose any convenient delimiter, single-byte or multibyte, or any of the following character
pairs: [ ], { }, ( ), or < >.

Example:

SELECT department_name || q'[ Department's Manager Id: ]'

|| manager_id

AS "Department and Manager"


FROM departments;

Output:
In the example, the string contains a single quotation mark, which is normally interpreted as a delimiter
of a character string. By using the q operator, however, brackets [] are used as the quotation mark
delimiters. The string between the brackets delimiters is interpreted as a literal character string.

Duplicate Rows

The default display of queries is all rows, including duplicate rows.

Example:

SELECT department_id

FROM employees;

Output:

In the above example, the EMPLOYEES table actually contains 20 rows, but there are only seven
unique department numbers in the table.

You can specify multiple columns after the DISTINCT qualifier. The DISTINCT qualifier affects
all the selected columns, and the result is every distinct combination of the columns.

SELECT DISTINCT department_id, job_id

FROM
employees;
Sorting rows using the ORDER BY clause

The order of rows that are returned in a query result is undefined. The ORDER BY clause can be used
to sort the rows. However, if you use the ORDER BY clause, it must be the last clause of the SQL
statement. Further, you can specify an expression, an alias, or a column position as the sort condition.

Syntax

SELECT expr

FROM table

[WHERE condition(s)]

[ORDER BY {column, expr, numeric_position} [ASC|DESC]];

In the syntax:

ORDER BY specifies the order in which the retrieved rows are displayed ASC
orders the rows in ascending order (this is the default order) DESC orders the rows in
descending order

If the ORDER BY clause is not used, the sort order is undefined, and the Oracle server may not fetch
rows in the same order for the same query twice. Use the ORDER BY clause to display the rows in a
specific order.

Note: Use the keywords NULLS FIRST or NULLS LAST to specify whether returned rows
containing null values should appear first or last in the ordering sequence.

Example:

SELECT last_name, job_id, department_id, hire_date

FROM employees

ORDER BY hire_date ;
Output:

Sorting in descending order:


Example:

SELECT last_name, job_id, department_id, hire_date

FROM employees

ORDER BY hire_date DESC ;

To reverse the order in which the rows are displayed, specify the DESC keyword after the column name
in the ORDER BY clause. The slide example sorts the result by the most recently hired employee.
Aggregate functions:
Aggregate functions are widely utilized in databases, spreadsheets, and various data management
software. They are especially useful in the business world as different levels of management require
different types of information. For example, top-level executives are interested in overall figures rather
than specific details. The functions condense data from the database and provide summarized
information. As a result, they are frequently used in economics and finance to show the financial
wellbeing of a company or the performance of stocks and industries.

Count():
The MySQL count() function calculates the number of values in a given expression. The function can
return all rows or only those that meet a specific condition, and its output type is BIGINT. If no matching
rows are found, the function returns zero. It can be used with both numeric and non-numeric data
types.
For instance, if we want to determine the total number of employees in an "employee" table, we can
use the count() function as demonstrated in the following query
Sum():
The MySQL sum() function computes the sum of all non-NULL values in an expression. If the result set
contains no rows, the function returns NULL. This function is designed to work only with numeric data
types.
For instance, to calculate the total number of working hours for all employees in a table, we can use the
sum() function as demonstrated in the following query:

Avg():
The MySQL AVG() function calculates the average value of a specified column. Like the SUM() function,
it is also limited to working with numeric data types only.

For example, to determine the average working hours for all employees in a table, we can use the
AVG() function as demonstrated in the following query:

Min() :
The MySQL MIN() function returns the minimum or lowest value in a specified column. Like the other functions,
it operates only with numeric data types.

For example, to find the minimum working hours for an employee in a table, we can use the MIN() function as
demonstrated in the following query:
Max():
The MySQL MAX() function returns the maximum or highest value in a specified column. Like the other
functions, it is restricted to working with numeric data types.
For example, to find the maximum working hours for an employee in a table, we can use the MAX()
function as demonstrated in the following query:

First():
The FIRST() function returns the first value in a specified column. It is only available in MS Access and
requires the use of the LIMIT clause to retrieve the first value.
For example, to find the first working date for an employee in a table, the following query can be used:

Last():
The LAST() function returns the last value in a specified column. Like the FIRST() function, it is only
available in MS Access and requires the use of both the ORDER BY and LIMIT clauses to retrieve the last
value.
For example, to find the last working hour for an employee in a table, the following query can be used:
Group_concat():
The GROUP_CONCAT() function combines the values of multiple rows into a single string. If the group
contains at least one non-NULL value, the function will return a string value. If all values are NULL, the
function returns NULL.
For example, consider the following employee table:

You might also like