Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
167 views

Assignment 1 SQL

This document provides instructions for the first assignment on Structured Query Language (SQL). The assignment aims to teach students about SQL, the MySQL relational database management system, and basic Data Definition Language (DDL) and Data Manipulation Language (DML) commands. Students will complete tasks to create tables in a database using SQL commands like CREATE TABLE and add constraints like PRIMARY KEY and FOREIGN KEY. The tasks are designed to take approximately 2 hours to complete and require submitting code and output for specific tasks.

Uploaded by

itsfake
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
167 views

Assignment 1 SQL

This document provides instructions for the first assignment on Structured Query Language (SQL). The assignment aims to teach students about SQL, the MySQL relational database management system, and basic Data Definition Language (DDL) and Data Manipulation Language (DML) commands. Students will complete tasks to create tables in a database using SQL commands like CREATE TABLE and add constraints like PRIMARY KEY and FOREIGN KEY. The tasks are designed to take approximately 2 hours to complete and require submitting code and output for specific tasks.

Uploaded by

itsfake
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 18

High Performance Computational Infrastructures

ASSIGNMENT - 1
STRUCTURED QUERY LANGUAGE (SQL)

Aims and Objectives

This is the first assignment on Structured Query Language (SQL). In this assignment, you will learn
the introduction of SQL, MySQL relational database management system and basic Data Definition
Language (DDL) and Data Manipulation Language (DML) commands.

Time Required

2 hours.

Please note that the above number is only indicative and should be regarded as an average amount
of time for all students. You may require significantly more or less time depending on personal
circumstances, e.g. knowledge and understanding to the relevant subject topics, experience of the
software used, and level of programming skills. Please do prepare to use more time outside the
officially arranged sessions.

Report Requirement

Complete all the tasks, and report your code and results for Tasks 1.3-1.7 and 1.9-1.12.

Note that you should copy and paste the code and results in the text format as much as possible.
Screenshots as the output results are only acceptable for the exceptional cases.
Structured Query Language (SQL)
SQL (sometimes pronounced sequel for historical reasons) is an abbreviation for Structured Query
Language. It is a comprehensive language for controlling and interacting with a relational database
management system. SQL commands are used for organizing, managing and retrieving data stored
in a relational database. There are very few SQL commands, which make the language very easy to
learn. SQL is called a fourth generation language (4GL) due to its power, conciseness, English like,
free format and low level procedures.
The standard set of SQL commands falls into four categories:
 Data Definition Language (DDL) commands for creating and altering the structure of a
database.
 Data Manipulation Language (DML) commands for adding and modifying data.
 Data control commands for controlling access to the database.
 Query commands for extracting information from the database.

MySQL
MySQL is a relational database management system (RDBMS) developed and distributed by MySQL
AB: http://www.mysql.com/ It provides the latest information about MySQL software and MySQL
AB. MySQL uses an extension of the standard SQL. During our lab sessions we are going to use
MySQL on the DISC local net.
With SQL you can:
 Create new database tables.
 Store information in these tables.
 Select exactly any information you need from tables.
 Make changes in tables, updating or deleting them as required.
 Design and print reports.
 Combine data from various tables.

phpMyAdmin
phpMyAdmin is an open source web application, written in PHP for managing MySQL databases.
Currently it can create and drop databases, create/drop/alter tables, delete/edit/add fields,
execute any SQL statement, manage keys on fields, manage privileges, export data into various
formats and is available in 50 languages.

Task 1.1 Logging in to phpMyAdmin


We will set up a database server running MySQL server. Use phpMyAdmin to manage your MySQL
database directly.
How to login to phpMyAdmin?
1. Go to the URL: http://localhost/phpMyAdmin
2. Login by using the username and the password.
3. After logging in, you will see the default welcome screen for phpMyAdmin:

Task 1.2 Designing the Database and Tables


Before you create any database and table(s), please do your planning:
 Name of the database.
 Names of all the tables.
 All the attributes for each table
 The domain constraint(s) for each attribute
 The primary key for each table
 The referential constraints (Foreign keys)
Conventions:
Try to use a consistent convention for all names that you will assign. For example:
All table names: First letter capitalized with no underscores: e.g. Employee, WorksOn,…
All attribute names: lower case with underscores: name, ssn, birth_date, …
All constraint names: lower case, underscored; for example, a foreign key constraints from
Employee to Department table ->fk_employee_department.
What Data Type to Use?
For all integer values, use Type = INT
For all real numbers, use Type = FLOAT
For all text fields, use Type = VARCHAR, and Length = 50 (or some other reasonable number)
For Dates (e.g. Birth Date), use Type = DATE

Database: Create the database University Information System name UIS.


Table Name Departments
Description This table provides the information of departments in the University.
Column Data Type Description
DepartmentID (PK) Int The unique identifier of Department
Title String The title of Department
Description String The description of Department
The datetime the Department was uploaded to the PC
DateAddedtoPC DateTime
platform
The datetime the Department was modified to the PC
DateModified DateTime
platform
Table Name Students
Description This table provides the information of Students in the University.
Column Data Type Description
StudentID (PK) Int The unique identifier of the Student
StudentName String The name of the Student
DepartmentID (FK) Int The department of the Student
The datetime the Student was uploaded to the PC
DateAddedtoPC DateTime
platform
The datetime the Student was modified to the PC
DateModified DateTime
platform

Table Name Courses


Description This table provides the information of courses in the University.
Column Data Type Description
CourseID (PK) Int The unique identifier of Course
Title String The title of Course
Description String The description of Course
The datetime the Course was uploaded to the PC
DateAddedtoPC DateTime
platform
The datetime the Course was modified to the PC
DateModified DateTime
platform

Table Name StudentCourses


Description This table provides the information of courses in the University.
Column Data Type Description
StudentID (FK) Int The unique identifier of Student
CourseID (FK) Int The unique identifier of Course
Term String The term of Course registration
Status String The status of the course
The datetime the Student Course was uploaded to the PC
DateAddedtoPC DateTime
platform
The datetime the Student Course was modified to the PC
DateModified DateTime
platform

Task 1.3 Creating the Database


How to use SQL command to create your database?
SQL Command: CREATE DATABASE database_name;
1. Click “SQL” in the middle
2. Type your SQL query in the box
CREATE DATABASE UIS
3. Click “Go” to execute the SQL query
Task 1.4 Using the Database
How to use SQL command to select the database to perform the further SQL commands on your
database?
SQL Command: USE database_name;
1. Click “SQL” in the middle
2. Type your SQL query in the box
USE UIS
3. Click “Go” to execute the SQL query

Task 1.5 SQL CREATE TABLE + CONSTRAINT Statement


SQL Constraints
In SQL, we have the following constraints:
 NOT NULL - Indicates that a column cannot store NULL value
 UNIQUE - Ensures that each row for a column must have a unique value
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or
combination of two or more columns) have an unique identity which helps to find a
particular record in a table more easily and quickly
 FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in
another table
 CHECK - Ensures that the value in a column meets a specific condition
 DEFAULT - Specifies a default value when specified none for this column

SQL Command:
CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);
1. Click “SQL” in the middle
2. Type your SQL query in the box
CREATE TABLE Departments (
DepartmentID INT NOT NULL PRIMARY KEY ,
Title VARCHAR( 50 ) NOT NULL ,
Description VARCHAR( 255 ),
DateAddedtoPC DATETIME NOT NULL ,
DateModified DATETIME)
3. Click “Go” to execute the SQL query

4. After execute the SQL query and see the structure of created table

Task 1.6 SQL FOREIGN KEY Constraint


A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
1. Click “SQL” in the middle
2. Type your SQL query in the box
CREATE TABLE Students (
StudentID INT NOT NULL,
Name VARCHAR( 50 ) NOT NULL ,
DepartmentID INT NOT NULL,
DateAddedtoPC DATETIME NOT NULL ,
DateModified DATETIME NULL,
PRIMARY KEY (StudentID),
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
)
3. Click “Go” to execute the SQL query

Similar to the above example, please create the other tables as outlined in Task 1.2, i.e. Courses and
StudentCourses.
Task 1.7 SQL ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
SQL Command:
 To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype
 To delete a column in a table, use the following syntax (notice that some database systems
don't allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name
 To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
MODIFY COLUMN column_name datatype

Now execute the following statements on your database:


To add a column named "DateOfBirth" in the "Students" table, use the following SQL statement:
ALTER TABLE Students
ADD DateOfBirth DATE
To change the data type of the column named "Name" in the "Students" table, use the following SQL
statement:
ALTER TABLE Students
MODIFY COLUMN Name VARCHAR(100)
To delete the column named "DateOfBirth" in the " Students" table,. use the following SQL
statement:
ALTER TABLE Students
DROP COLUMN DateOfBirth

Task 1.8 SQL DROP TABLE and DROP DATABASE Statement


Tables and databases can easily be deleted/removed with the DROP statement.
SQL Command:
 The DROP TABLE Statement
DROP TABLE table_name
Example: DROP TABLE AnotherTable
 The DROP DATABASE Statement
DROP DATABASE database_name
Example: DROP DATABASE AnotherDatabase

Please do NOT delete the tables or database you created unless you wish to create them again.
Create your separate tables or databases when you are practicing these statements.

Task 1.9 SQL INSERT INTO Statement


The INSERT INTO statement is used to insert new records in a table. It is possible to write the
INSERT INTO statement in two forms.
 The first form does not specify the column names where the data will be inserted, only their
values:
INSERT INTO table_name
VALUES (value1,value2,value3,...)
 The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...)
Now execute the following statements on table "Departments":
 Insert Data without column names
INSERT INTO Departments
VALUES (1, 'Computer Science', 'Offers degrees in Computer Science', '1/10/2014', NULL)
 Insert Data with column names
INSERT INTO Departments (DepartmentID, Title, Description, DateAddedtoPC, DateModified)
VALUES (2, ‘Mathematics', 'Offers degrees in Mathematics', '1/10/2014', NULL)
 Insert Data only in specified columns
INSERT INTO Departments (DepartmentID, Title, DateAddedtoPC)
VALUES (3, ‘Information Systems', '1/10/2014')

Task 1.10 SQL UPDATE Statement


The UPDATE statement is used to update existing records in a table.
SQL Command:
UPDATE table_name
SET column1=value1,column2=value2,...

Now perform the following task:


To update the Students Department information with a new DepartmentID, use the following SQL
statement:
UPDATE Students
SET DepartmentID=2

Task 1.11 SQL DELETE Statement


The DELETE statement is used to delete rows in a table.
SQL Command:
DELETE FROM table_name

Now perform the following task:


To delete the data from "Students" table, use the following SQL statement:
DELETE FROM Students

Task 1.12 load data from tab delimited text file into table
After logging in, navigate to the phpMyAdmin import screen by doing this:
1. Look in the left-hand column and click on the name of the table into which you want to load
the data.
2. Click the Import tab that appears at the top of the page.
3. Change the "Format of imported file" to CSV. (Do not choose "CSV using LOAD DATA"; it will
not work.)
4. You willl then see a screen that allows you to choose the import options:
5. Next to "Location of the text file", choose the file from your hard disk that you want to
import.
6. Change the Fields terminated by option to be a tab instead of the default semicolon.
7. Leave the other options unchanged unless you know what you're doing.
8. Press Go.
You should see something like Inserted rows: 50 (Query took 0.00 sec) at the top of the screen.
Click the Browse tab to review the imported data.

Task 1.13 SQL SELECT Statement


The SELECT statement is used to select data from a database. The result is stored in a result table,
called the result-set.
SQL Command:
SELECT column_name, column_name
FROM table_name
Another way is:
SELECT * FROM table_name

SELECT Column Example


The following SQL statement selects the "Title" and "Description" columns from the "Departments"
table:
SELECT Title, Description FROM Departments

SELECT * Example
The following SQL statement selects all the columns from the "Departments" table:
SELECT * FROM Departments

After executing the above command, the following screen will be show:

Task 1.14 SQL SELECT DISTINCT Statement


In a table, a column may contain many duplicate values; and sometimes you only want to list the
different (distinct) values. The DISTINCT keyword can be used to return only distinct (different)
values.

SQL Command:
SELECT DISTINCT column_name, column_name
FROM table_name
SELECT DISTINCT Example
The following SQL statement selects only the distinct values from the "DepartmentID" column from
the "Students" table:
SELECT DISTINCT DepartmentID FROM Students

Task 1.15 SQL WHERE Clause


The WHERE clause is used to extract only those records that fulfill a specified criterion.
SQL Command:
SELECT column_name, column_name
FROM table_name
WHERE column_name operator value
Operators in The WHERE Clause
The following operators can be used in the WHERE clause:
Operator Description

= Equal

<> Not equal. Note: In some versions of SQL


this operator may be written as !=

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

BETWEEN Between an inclusive range

LIKE Search for a pattern

IN To specify multiple possible values for a


column

WHERE Clause Example


The following SQL statement selects all the Students from the DepartmentID "1", in the "Students"
table:
SELECT * FROM Students
WHERE DepartmentID=1

Task 1.16 SQL AND & OR Operators


The AND & OR operators are used to filter records based on more than one condition.
The AND operator displays a record if both the first condition AND the second condition are true.
The OR operator displays a record if either the first condition OR the second condition is true.

AND Operator Example


The following SQL statement selects all students from the DepartmentID "1" AND the
DateAddedtoPC "1/10/2014", in the "Students" table:
SELECT * FROM Students
WHERE DepartmentID=1
AND DateAddedtoPC ='2014-10-01';
OR Operator Example
The following SQL statement selects all Students from the DepartmentID "1" OR "3", in the
"Students" table: 
SELECT * FROM Students
WHERE DepartmentID =1
OR DepartmentID =3

Combining AND & OR


You can also combine AND and OR (use parenthesis to form complex expressions).
The following SQL statement selects all Students from the DateAddedtoPC "1/10/2014" AND the
DepartmentID must be equal to "1" OR "3", in the "Students" table:
SELECT * FROM Students
WHERE DateAddedtoPC ='2014-10-01'
AND (DepartmentID =1 OR DepartmentID =3);

Task 1.17 SQL ORDER BY Keyword


The ORDER BY keyword is used to sort the result-set by one or more columns.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a
descending order, you can use the DESC keyword.

SQL Command:
SELECT column_name, column_name
FROM table_name
ORDER BY column_name, column_name ASC|DESC;

ORDER BY Example
The following SQL statement selects all students from the "Students" table, sorted by the
"DepartmentID" column:
SELECT * FROM Students
ORDER BY DepartmentID

ORDER BY DESC Example


The following SQL statement selects all students from the "Students" table, sorted DESCENDING by
the "DepartmentID " column:
SELECT * FROM Students
ORDER BY DepartmentID DESC

ORDER BY Several Columns Example


The following SQL statement selects all students from the " Students " table, sorted by the
"DepartmentID " and the "Name" column:
SELECT * FROM Students
ORDER BY DepartmentID, Name

Task 1.18 SQL LIKE Operator


The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

SQL Command:
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern

SQL Wildcard Characters


In SQL, wildcard characters are used with the SQL LIKE operator. SQL wildcards are used to search
for data within a table. With SQL, the wildcards are:
Wildcard Description
% A substitute for zero or more characters

_ A substitute for a single character

[charlist] Sets and ranges of characters to match

[^charlist] Matches only a character NOT specified within


or the brackets
[!charlist]

SQL LIKE Operator and Wildcard Examples


Using the SQL % Wildcard
The following SQL statement selects all students with a Name starting with "ber":
SELECT * FROM Students
WHERE Name LIKE 'ber%'
The following SQL statement selects all students with a Name ending with the letter "s":
SELECT * FROM Students
WHERE Name LIKE '%s'
The following SQL statement selects all students with a Name containing the pattern "land":
SELECT * FROM Students
WHERE Name LIKE '%land%'
Using the NOT keyword allows you to select records that does NOT match the pattern. The
following SQL statement selects all students with a Name NOT containing the pattern "land":
SELECT * FROM Students
WHERE Name NOT LIKE '%land%'

Using the SQL _ Wildcard


The following SQL statement selects all students with a Name starting with any character, followed
by "erlin":
SELECT * FROM Students
WHERE Name LIKE '_erlin'
The following SQL statement selects all students with a Name starting with "L", followed by any
character, followed by "n", followed by any character, followed by "on":
SELECT * FROM Students
WHERE Name LIKE 'L_n_on'

Using the SQL [charlist] Wildcard


The following SQL statement selects all students with a Name starting with "b", "s", or "p":
SELECT * FROM Students
WHERE Name LIKE '[bsp]%'
The following SQL statement selects all students with a Name starting with "a", "b", or "c":
SELECT * FROM Students
WHERE Name LIKE '[a-c]%'
The following SQL statement selects all students with a Name NOT starting with "b", "s", or "p":
SELECT * FROM Students
WHERE Name LIKE '[!bsp]%'

or

SELECT * FROM Students


WHERE Name NOT LIKE '[bsp]%'

Task 1.19 SQL IN Operator


The IN operator allows you to specify multiple values in a WHERE clause.
SQL Command:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
IN Operator Example
The following SQL statement selects all students with a DepartmentID of "1" or "3":
SELECT * FROM Students
WHERE DepartmentID IN (1, 3)
NOT IN Operator Example
To display the students outside the range of the previous example, use NOT IN:
SELECT * FROM Students
WHERE DepartmentID NOT IN (1, 3)

Task 1.20 SQL BETWEEN Operator


The BETWEEN operator selects values within a range. The values can be numbers, text, or dates.
SQL Command:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2
BETWEEN Operator Example
The following SQL statement selects all students with a DepartmentID BETWEEN 1 and 10:
SELECT * FROM Students
WHERE DepartmentID BETWEEN 1 AND 10
NOT BETWEEN Operator Example
To display the students outside the range of the previous example, use NOT BETWEEN:
SELECT * FROM Students
WHERE DepartmentID NOT BETWEEN 1 AND 10

SQL Aliases
SQL aliases are used to give a database table, or a column in a table, a temporary name. Basically
aliases are created to make column names more readable. Aliases can be useful when:
 There are more than one table involved in a query
 Functions are used in the query
 Column names are big or not very readable
 Two or more columns are combined together

SQL Alias Syntax for Columns


SELECT column_name AS alias_name
FROM table_name
SQL Alias Syntax for Tables
SELECT column_name(s)
FROM table_name AS alias_name

Task 1.21 SQL JOIN


An SQL JOIN clause is used to combine rows from two or more tables, based on a common field
between them.
Different SQL JOINs
Before we continue with examples, we will list the types the different SQL JOINs you can use:
 INNER JOIN: Returns all rows when there is at least one match in BOTH tables
 LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
 RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
 FULL JOIN: Return all rows when there is a match in ONE of the tables
The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN return all
rows from multiple tables where the join condition is met.
Example Database in Task 1.2, let's look at a selection from the "Departments" table then, have a
look at a selection from the "Students" table. Notice that the "DepartmentID" column in the
"Departments" table refers to the Student in the "Students" table. The relationship between the two
tables above is the " DepartmentID " column.
SQL INNER JOIN Keyword
The INNER JOIN keyword selects all rows from both tables as long as there is a match between the
columns in both tables.
SQL INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name

or:

SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name
Note: INNER JOIN is the same as JOIN.

SQL INNER JOIN Example


The following SQL statement will return all Students with Departments:
SELECT a.StudentID, a. Name, b.Title
FROM Students as a
INNER JOIN Departments as b
ON a.DepartmentID=b. DepartmentID
ORDER BY b.Title
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns. If there are rows in the "Students" table that do not have matches in
"Departments", these students will NOT be listed.

SQL LEFT JOIN Keyword


The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the
right table (table2). The result is NULL in the right side when there is no match.
SQL LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
or:
or:

SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;
Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.

SQL LEFT JOIN Example


The following SQL statement will return all Students, and any Courses they might have registered:
SELECT a.StudentID, a.Name, b.CourseID
FROM Students as a
LEFT OUTER JOIN StudentCourses as b
ON a. StudentID =b. StudentID
ORDER BY a. StudentID
Note: The LEFT JOIN keyword returns all the rows from the left table (Students), even if there are
no matches in the right table (Departments).
SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in
the left table (table1). The result is NULL in the left side when there is no match.
SQL RIGHT JOIN Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name

or:

SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;
Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.
SQL RIGHT JOIN Example
The following SQL statement will return all courses, and any students they have registered:
SELECT a.CourseID, b.Title, a.StudentID
FROM StudentCourses as a
RIGHT OUTER JOIN Courses as b
ON a. CourseID=b. CourseID
ORDER BY a.courseID
Note: The RIGHT JOIN keyword returns all the rows from the right table (Departments), even if
there are no matches in the left table (Students).
SQL FULL OUTER JOIN Keyword
The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right
table (table2).
The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.
SQL FULL OUTER JOIN Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;

SQL FULL OUTER JOIN Example


The following SQL statement selects all students, and all courses:
SELECT a.StudentID, a.Name, b.CourseID, c.Title
FROM Students as a
FULL OUTER JOIN StudentCourses as b
ON a. StudentID =b. StudentID
FULL OUTER JOIN Courses as c
ON b.courseID=c.CourseID
ORDER BY a. StudentID
Note: The FULL OUTER JOIN keyword returns all the rows from the left table (Students), and all the
rows from the right table (Departments). If there are rows in "Students" that do not have matches
in "Departments", or if there are rows in "Departments" that do not have matches in "Students",
those rows will be listed as well.

SQL Functions
SQL has many built-in functions for performing calculations on data.
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate
functions:
 AVG() - Returns the average value
 COUNT() - Returns the number of rows
 MAX() - Returns the largest value
 MIN() - Returns the smallest value
 SUM() - Returns the sum
SQL Scalar functions
SQL scalar functions return a single value, based on the input value. Useful scalar functions:
 UCASE() - Converts a field to upper case
 LCASE() - Converts a field to lower case
 MID() - Extract characters from a text field
 LEN() - Returns the length of a text field
 ROUND() - Rounds a numeric field to the number of decimals specified
 NOW() - Returns the current system date and time
 FORMAT() - Formats how a field is to be displayed

Task 1.22 SQL Aggregate and Scalar Functions


SQL COUNT() Function
The COUNT() function returns the number of rows that matches a specified criteria.
SQL COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values (NULL values will not be
counted) of the specified column:
SELECT COUNT(column_name) FROM table_name
SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table:
SELECT COUNT(*) FROM table_name
SQL COUNT(DISTINCT column_name) Syntax
The COUNT(DISTINCT column_name) function returns the number of distinct values of the
specified column:
SELECT COUNT(DISTINCT column_name) FROM table_name

The AVG() Function


The AVG() function returns the average value of a numeric column.
SELECT AVG(column_name) FROM table_name

The MAX() Function


The MAX() function returns the largest value of the selected column.
SELECT MAX(column_name) FROM table_name

The MIN() Function


The MIN() function returns the smallest value of the selected column.
SELECT MIN(column_name) FROM table_name

The SUM() Function


The SUM() function returns the total sum of a numeric column.
SELECT SUM(column_name) FROM table_name
Task 1.23 SQL 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 Command:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name

SQL GROUP BY Example


To find the number of students in each department, use the following SQL statement to count by
students and group by department:
SELECT DepartmentID, COUNT(StudentID) AS NumberOfStudents FROM Students
GROUP BY DepartmentID
Or:
SELECT b.Title, COUNT(a.StudentID) AS NumberOfStudents FROM Students as a
LEFT OUTER JOIN Departments as b
ON a.DepartmentID=b.DepartmentID
GROUP BY b.Title
ORDER BY b.Title
GROUP BY More Than One Column
We can also use the GROUP BY statement on more than one column, like this:
SELECT a.DepartmentID, b.Title, COUNT(a.StudentID) AS NumberOfStudents FROM Students as a
LEFT OUTER JOIN Departments as b
ON a.DepartmentID=b.DepartmentID
GROUP BY a.DepartmentID, b.Title
ORDER BY b.Title

Task 1.24 SQL HAVING Clause


The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.
SQL Command:
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
Want to find if any of the department has total students less than 10. Use the following SQL
statement:
SELECT b.Title, COUNT(a.StudentID) AS NumberOfStudents FROM Students as a
LEFT OUTER JOIN Departments as b
ON a.DepartmentID=b.DepartmentID
GROUP BY b.Title
HAVING COUNT(a.StudentID) < 10;
ORDER BY b.Title

You might also like