This document discusses how to aggregate data using group functions in SQL. It describes the available group functions like AVG, COUNT, MAX, MIN, SUM, and how to use them. It explains how to group data using the GROUP BY clause and include or exclude grouped rows using the HAVING clause. Examples are provided to illustrate grouping data by one or more columns and restricting groups with the HAVING clause.
Group functions operate on sets of rows to give one result per group. Common group functions include COUNT, SUM, AVG, MIN, and MAX. The GROUP BY clause is used to divide rows into groups and the HAVING clause excludes groups based on a condition. Nesting group functions allows analyzing groups of groups, like finding the maximum of several averages.
Subqueries allow queries to be nested within other queries. They can return either single rows or multiple rows. Single-row subqueries use comparison operators like = or >, while multiple-row subqueries use operators like IN, ANY, or ALL. Subqueries execute first before the outer or main query uses the results. This allows the main query to filter or compare based on unknown values from the subquery.
Group functions operate on sets of rows to give one result per group. Some key points covered in the document include:
1. Group functions like AVG, COUNT, MAX, MIN, SUM allow aggregating data across rows grouped by columns like department.
2. The GROUP BY clause is used to divide rows into groups and column(s) in the SELECT that are not aggregate functions must be in the GROUP BY.
3. The HAVING clause is used to filter groups based on conditions with aggregate functions and comes after GROUP BY.
This document discusses views in Oracle databases. It defines a view as a virtual table derived from one or more underlying base tables or other views. The document covers how to create simple and complex views, modify view definitions, perform DML operations on views, and remove views. Key points include that views allow restricting access, simplifying queries, and presenting different perspectives of the same data without affecting the base tables.
This document discusses how to restrict and sort data retrieved by SQL queries. It covers limiting rows using the WHERE clause and comparison operators, and sorting rows using the ORDER BY clause. Examples are provided for each clause and operator to filter rows by conditions and sort the output in ascending or descending order on one or multiple columns. Parentheses can be used to override the default order of operation precedence.
This document discusses techniques for joining data from multiple database tables. It covers equijoins to retrieve matching records between tables, non-equijoins to retrieve records with non-equal conditions, outer joins to include non-matching records, and self joins to join a table to itself. Examples are provided to demonstrate how to write SQL statements to perform each type of join and include additional conditions.
The document provides an overview of basic SQL statements and capabilities. It discusses using SELECT statements to project columns, select rows, and join tables. It also covers arithmetic expressions, column aliases, concatenation, and eliminating duplicate rows. SQL statements are executed through the SQL*Plus environment, which allows editing, saving, and running SQL code and commands.
Single-row functions can manipulate data items, accept arguments and return one value, and act on each row returned. There are various types of single-row functions including character, number, date, and conversion functions. Character functions manipulate character strings, number functions perform calculations, and date functions modify date formats. Functions allow data to be formatted, calculated, and converted as needed for different queries and outputs.
Group functions operate on sets of rows to give one result per group. Common group functions include COUNT, SUM, AVG, MIN, and MAX. The GROUP BY clause is used to divide rows into groups and the HAVING clause excludes groups based on a condition. Nesting group functions allows analyzing groups of groups, like finding the maximum of several averages.
Subqueries allow queries to be nested within other queries. They can return either single rows or multiple rows. Single-row subqueries use comparison operators like = or >, while multiple-row subqueries use operators like IN, ANY, or ALL. Subqueries execute first before the outer or main query uses the results. This allows the main query to filter or compare based on unknown values from the subquery.
Group functions operate on sets of rows to give one result per group. Some key points covered in the document include:
1. Group functions like AVG, COUNT, MAX, MIN, SUM allow aggregating data across rows grouped by columns like department.
2. The GROUP BY clause is used to divide rows into groups and column(s) in the SELECT that are not aggregate functions must be in the GROUP BY.
3. The HAVING clause is used to filter groups based on conditions with aggregate functions and comes after GROUP BY.
This document discusses views in Oracle databases. It defines a view as a virtual table derived from one or more underlying base tables or other views. The document covers how to create simple and complex views, modify view definitions, perform DML operations on views, and remove views. Key points include that views allow restricting access, simplifying queries, and presenting different perspectives of the same data without affecting the base tables.
This document discusses how to restrict and sort data retrieved by SQL queries. It covers limiting rows using the WHERE clause and comparison operators, and sorting rows using the ORDER BY clause. Examples are provided for each clause and operator to filter rows by conditions and sort the output in ascending or descending order on one or multiple columns. Parentheses can be used to override the default order of operation precedence.
This document discusses techniques for joining data from multiple database tables. It covers equijoins to retrieve matching records between tables, non-equijoins to retrieve records with non-equal conditions, outer joins to include non-matching records, and self joins to join a table to itself. Examples are provided to demonstrate how to write SQL statements to perform each type of join and include additional conditions.
The document provides an overview of basic SQL statements and capabilities. It discusses using SELECT statements to project columns, select rows, and join tables. It also covers arithmetic expressions, column aliases, concatenation, and eliminating duplicate rows. SQL statements are executed through the SQL*Plus environment, which allows editing, saving, and running SQL code and commands.
Single-row functions can manipulate data items, accept arguments and return one value, and act on each row returned. There are various types of single-row functions including character, number, date, and conversion functions. Character functions manipulate character strings, number functions perform calculations, and date functions modify date formats. Functions allow data to be formatted, calculated, and converted as needed for different queries and outputs.
This document discusses restricting and sorting data in SQL queries. It describes how to limit rows returned using a WHERE clause and comparison operators. It also explains how to sort rows using an ORDER BY clause, including sorting in ascending and descending order and by multiple columns. Logical operators, precedence rules, and NULL handling are also covered.
This document discusses how to limit and sort data retrieved from a database table using SQL queries. It covers using the WHERE clause to restrict rows by conditions, comparison operators like = and BETWEEN, logical operators like AND and OR, and the ORDER BY clause to sort rows in ascending or descending order based on one or more columns. Examples are provided for each technique.
This document discusses restricting and sorting data in SQL queries. It covers limiting rows using the WHERE clause with various operators like comparison, logical, BETWEEN, IN, LIKE and IS NULL. It also covers sorting result rows using the ORDER BY clause, including sorting in ascending and descending order and by multiple columns. The overall goal is to select specific data rows and control the order of rows displayed in the results.
This document describes views in an Oracle database. It defines what a view is, explains why they are used to restrict access, simplify queries, and provide different perspectives on the same data. It covers how to create simple and complex views, retrieve data from views, modify data through views depending on their definition, and remove views. The key points are that views allow logical abstraction of data without changing the physical storage and have benefits for access control, query optimization, and data independence.
This document describes various single-row functions in SQL that can manipulate or modify data. It discusses character, number, date, and conversion functions and provides examples of how to use functions like TO_CHAR, TO_NUMBER, ROUND, TRUNC, and DECODE in SELECT statements. Common uses of functions include performing calculations, formatting output, converting data types, and conditional processing of data. Nesting functions allows multiple operations to be applied sequentially.
This document provides an overview of basic SQL statements and SQL*Plus commands. It covers capabilities of SELECT statements, executing a basic SELECT statement, writing SQL statements, selecting specific columns, using arithmetic expressions and operators, defining aliases and literals, eliminating duplicate rows, and interacting with SQL*Plus through commands like editing, saving, and running SQL statements.
This document discusses data manipulation in Oracle databases. It describes how to insert, update, and delete rows from tables using DML statements like INSERT, UPDATE, and DELETE. It also covers transaction management using COMMIT, ROLLBACK, and SAVEPOINT statements to control when changes are committed to the database or rolled back. Key aspects covered include inserting new rows, updating and deleting specific rows or all rows, and handling integrity constraints and transactions.
This document provides an overview of basic SQL statements and SQL*Plus commands. It describes how to select data from tables using the SELECT statement, perform calculations, and give columns aliases. It also summarizes how to describe table structures, edit SQL statements, and execute saved SQL files using SQL*Plus commands. The key capabilities of the SELECT statement are selection, projection, and joining data from multiple tables.
حل اسئلة الكتاب السعودى فى شرح قواعد البيانات اوراكلMohamed Moustafa
The document contains examples of SQL queries on Oracle database tables. It shows how to retrieve data from the DEPT and EMP tables, including selecting columns, filtering rows, sorting results, and performing calculations. Various SQL functions are demonstrated like INITCAP, LENGTH, SUBSTR, and date formatting. The last section aggregates data from the EMP table using MAX, MIN, SUM, and AVG.
This document discusses how to limit and sort data retrieved by SQL queries. It covers using the WHERE clause to restrict rows selected based on conditions, comparison operators like = and BETWEEN, logical operators like AND and OR, and the ORDER BY clause to sort rows in ascending or descending order. Examples are provided for each concept to demonstrate proper SQL syntax. The overall goal is to teach how to selectively retrieve only the relevant data needed from a database table.
The document describes three types of user-defined functions in SQL Server: 1) Scalar functions that return a single value, 2) Inline table valued functions that return a table object, and 3) Multi-statement table valued functions that explicitly define the structure of the table to return. Examples are provided for each type of function, including how to create, modify, and execute the functions. Triggers are also discussed, with an example provided of an AFTER UPDATE trigger that inserts old records from the updated table into a second table.
The ALTER command in MySQL is used to modify the structure of existing tables. It allows you to add, drop, or modify columns, change the data type of columns, rename tables, and change the table type. Some key things the ALTER command allows you to do include:
1. Add or drop columns from a table.
2. Modify column definitions by changing the data type, default value, nullability, or length of a column.
3. Change the name of a table or rename columns.
4. Change the table type, such as converting between InnoDB and MyISAM.
The ALTER table command in SQL is used to modify the structure of an existing table. It can be used to add new columns, delete columns, change column sizes or data types, and add integrity constraints. Some key uses of ALTER table include adding a new column using the ADD command, modifying column properties like data type or default value using the MODIFY command, and changing the structure of a table.
1. The document discusses various SQL commands for creating, manipulating, and querying database tables. It covers commands like CREATE TABLE, INSERT, SELECT, UPDATE, DELETE, ALTER TABLE, COMMENT, and more.
2. Mathematical functions like COUNT, MAX, MIN, ROUND, TRUNC are described along with logical and comparison operators.
3. The document provides examples of using operators, functions, joins and grouping with detailed explanations.
This document provides an overview of basic SQL statements including:
- Executing a basic SELECT statement to retrieve data from tables
- Using functions like SELECT, FROM, and DISTINCT to retrieve specific columns and eliminate duplicates
- Performing calculations on columns using arithmetic operators
- Renaming columns with aliases and concatenating columns
- Describing the structure of tables using the DESCRIBE command
The goal is to learn fundamental SQL skills like selecting, calculating, aliasing columns, and viewing table definitions.
The document discusses subqueries in SQL, including: defining subqueries and their types (single-row, multiple-row); guidelines for using subqueries; and operators used in single-row versus multiple-row subqueries like =, >, IN, ANY, ALL. Examples are provided to illustrate how to write single-row and multiple-row subqueries and use them to solve problems like finding employees whose salary is greater than a particular employee's salary.
This document provides an overview of Oracle SQL functions. It discusses single-row functions that operate on each row returned, including conversion, character, number, and date functions. Character functions covered include LOWER, UPPER, INITCAP, CONCAT, SUBSTR, LENGTH, and INSTR, which can be used for case conversion and character manipulation.
This document discusses various ways to customize SQL*Plus and produce more readable output, including:
1) Using substitution variables to prompt for input and dynamically alter queries, reports, and file names.
2) Defining variables with DEFINE and ACCEPT and passing values between SQL statements.
3) Customizing the SQL*Plus environment with SET commands and verifying settings with SHOW.
Slides from the ILOUG 2019 conference. At every conference, you’ll see plenty about the latest and greatest release of Oracle. You’ll sigh as you think that it will be 10 years before you get to these versions at your workplace. This presentation is for you – we’ll look at the cool underused SQL features available going all the way back to Oracle 8.
The document discusses different ways to avoid mutating table errors when using triggers in Oracle:
1. Use a compound trigger instead of a row-level trigger to avoid the error. A compound trigger allows initializing variables before and after statements to prevent mutating errors.
2. An example is given of a compound trigger that enforces a business rule limiting salary increases to 10% of the department average without causing a mutating error.
3. The mutating error occurs when a trigger references the table that owns the trigger, preventing the trigger from seeing changes made by its own statement.
This document discusses multiple-column subqueries in SQL. It describes how multiple-column subqueries can return multiple columns that can then be compared pairwise or nonpairwise to columns in the outer query. Examples are provided of multiple-column subqueries used to return order items that match the product number and quantity from another order. The document also discusses how subqueries can be used in the FROM clause and how null values are handled in subqueries.
This document discusses restricting and sorting data in SQL queries. It describes how to limit rows returned using a WHERE clause and comparison operators. It also explains how to sort rows using an ORDER BY clause, including sorting in ascending and descending order and by multiple columns. Logical operators, precedence rules, and NULL handling are also covered.
This document discusses how to limit and sort data retrieved from a database table using SQL queries. It covers using the WHERE clause to restrict rows by conditions, comparison operators like = and BETWEEN, logical operators like AND and OR, and the ORDER BY clause to sort rows in ascending or descending order based on one or more columns. Examples are provided for each technique.
This document discusses restricting and sorting data in SQL queries. It covers limiting rows using the WHERE clause with various operators like comparison, logical, BETWEEN, IN, LIKE and IS NULL. It also covers sorting result rows using the ORDER BY clause, including sorting in ascending and descending order and by multiple columns. The overall goal is to select specific data rows and control the order of rows displayed in the results.
This document describes views in an Oracle database. It defines what a view is, explains why they are used to restrict access, simplify queries, and provide different perspectives on the same data. It covers how to create simple and complex views, retrieve data from views, modify data through views depending on their definition, and remove views. The key points are that views allow logical abstraction of data without changing the physical storage and have benefits for access control, query optimization, and data independence.
This document describes various single-row functions in SQL that can manipulate or modify data. It discusses character, number, date, and conversion functions and provides examples of how to use functions like TO_CHAR, TO_NUMBER, ROUND, TRUNC, and DECODE in SELECT statements. Common uses of functions include performing calculations, formatting output, converting data types, and conditional processing of data. Nesting functions allows multiple operations to be applied sequentially.
This document provides an overview of basic SQL statements and SQL*Plus commands. It covers capabilities of SELECT statements, executing a basic SELECT statement, writing SQL statements, selecting specific columns, using arithmetic expressions and operators, defining aliases and literals, eliminating duplicate rows, and interacting with SQL*Plus through commands like editing, saving, and running SQL statements.
This document discusses data manipulation in Oracle databases. It describes how to insert, update, and delete rows from tables using DML statements like INSERT, UPDATE, and DELETE. It also covers transaction management using COMMIT, ROLLBACK, and SAVEPOINT statements to control when changes are committed to the database or rolled back. Key aspects covered include inserting new rows, updating and deleting specific rows or all rows, and handling integrity constraints and transactions.
This document provides an overview of basic SQL statements and SQL*Plus commands. It describes how to select data from tables using the SELECT statement, perform calculations, and give columns aliases. It also summarizes how to describe table structures, edit SQL statements, and execute saved SQL files using SQL*Plus commands. The key capabilities of the SELECT statement are selection, projection, and joining data from multiple tables.
حل اسئلة الكتاب السعودى فى شرح قواعد البيانات اوراكلMohamed Moustafa
The document contains examples of SQL queries on Oracle database tables. It shows how to retrieve data from the DEPT and EMP tables, including selecting columns, filtering rows, sorting results, and performing calculations. Various SQL functions are demonstrated like INITCAP, LENGTH, SUBSTR, and date formatting. The last section aggregates data from the EMP table using MAX, MIN, SUM, and AVG.
This document discusses how to limit and sort data retrieved by SQL queries. It covers using the WHERE clause to restrict rows selected based on conditions, comparison operators like = and BETWEEN, logical operators like AND and OR, and the ORDER BY clause to sort rows in ascending or descending order. Examples are provided for each concept to demonstrate proper SQL syntax. The overall goal is to teach how to selectively retrieve only the relevant data needed from a database table.
The document describes three types of user-defined functions in SQL Server: 1) Scalar functions that return a single value, 2) Inline table valued functions that return a table object, and 3) Multi-statement table valued functions that explicitly define the structure of the table to return. Examples are provided for each type of function, including how to create, modify, and execute the functions. Triggers are also discussed, with an example provided of an AFTER UPDATE trigger that inserts old records from the updated table into a second table.
The ALTER command in MySQL is used to modify the structure of existing tables. It allows you to add, drop, or modify columns, change the data type of columns, rename tables, and change the table type. Some key things the ALTER command allows you to do include:
1. Add or drop columns from a table.
2. Modify column definitions by changing the data type, default value, nullability, or length of a column.
3. Change the name of a table or rename columns.
4. Change the table type, such as converting between InnoDB and MyISAM.
The ALTER table command in SQL is used to modify the structure of an existing table. It can be used to add new columns, delete columns, change column sizes or data types, and add integrity constraints. Some key uses of ALTER table include adding a new column using the ADD command, modifying column properties like data type or default value using the MODIFY command, and changing the structure of a table.
1. The document discusses various SQL commands for creating, manipulating, and querying database tables. It covers commands like CREATE TABLE, INSERT, SELECT, UPDATE, DELETE, ALTER TABLE, COMMENT, and more.
2. Mathematical functions like COUNT, MAX, MIN, ROUND, TRUNC are described along with logical and comparison operators.
3. The document provides examples of using operators, functions, joins and grouping with detailed explanations.
This document provides an overview of basic SQL statements including:
- Executing a basic SELECT statement to retrieve data from tables
- Using functions like SELECT, FROM, and DISTINCT to retrieve specific columns and eliminate duplicates
- Performing calculations on columns using arithmetic operators
- Renaming columns with aliases and concatenating columns
- Describing the structure of tables using the DESCRIBE command
The goal is to learn fundamental SQL skills like selecting, calculating, aliasing columns, and viewing table definitions.
The document discusses subqueries in SQL, including: defining subqueries and their types (single-row, multiple-row); guidelines for using subqueries; and operators used in single-row versus multiple-row subqueries like =, >, IN, ANY, ALL. Examples are provided to illustrate how to write single-row and multiple-row subqueries and use them to solve problems like finding employees whose salary is greater than a particular employee's salary.
This document provides an overview of Oracle SQL functions. It discusses single-row functions that operate on each row returned, including conversion, character, number, and date functions. Character functions covered include LOWER, UPPER, INITCAP, CONCAT, SUBSTR, LENGTH, and INSTR, which can be used for case conversion and character manipulation.
This document discusses various ways to customize SQL*Plus and produce more readable output, including:
1) Using substitution variables to prompt for input and dynamically alter queries, reports, and file names.
2) Defining variables with DEFINE and ACCEPT and passing values between SQL statements.
3) Customizing the SQL*Plus environment with SET commands and verifying settings with SHOW.
Slides from the ILOUG 2019 conference. At every conference, you’ll see plenty about the latest and greatest release of Oracle. You’ll sigh as you think that it will be 10 years before you get to these versions at your workplace. This presentation is for you – we’ll look at the cool underused SQL features available going all the way back to Oracle 8.
The document discusses different ways to avoid mutating table errors when using triggers in Oracle:
1. Use a compound trigger instead of a row-level trigger to avoid the error. A compound trigger allows initializing variables before and after statements to prevent mutating errors.
2. An example is given of a compound trigger that enforces a business rule limiting salary increases to 10% of the department average without causing a mutating error.
3. The mutating error occurs when a trigger references the table that owns the trigger, preventing the trigger from seeing changes made by its own statement.
This document discusses multiple-column subqueries in SQL. It describes how multiple-column subqueries can return multiple columns that can then be compared pairwise or nonpairwise to columns in the outer query. Examples are provided of multiple-column subqueries used to return order items that match the product number and quantity from another order. The document also discusses how subqueries can be used in the FROM clause and how null values are handled in subqueries.
This document discusses how to create and manage database tables in Oracle. It describes how to create tables with columns of different data types, alter table definitions by adding or modifying columns, drop and rename tables, and add comments to tables. The key database objects like tables, views, indexes and sequences are also introduced. Common SQL statements used for managing tables like CREATE TABLE, ALTER TABLE, DROP TABLE, COMMENT and more are explained with examples.
This document discusses subqueries in SQL. It defines subqueries as inner queries that execute before the outer or main query and provide results to the main query. There are single-row and multiple-row subqueries that use different comparison operators. The document provides examples of using subqueries to return values greater than, less than, equal to, or not equal to results of the subquery. It also discusses guidelines for using subqueries correctly.
This document discusses database constraints in Oracle. It defines various types of constraints like NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY and CHECK. It provides examples of creating constraints at column and table level during and after table creation. The document also discusses adding, dropping, disabling and enabling constraints. It describes viewing constraints and their associated columns in data dictionary views like USER_CONSTRAINTS and USER_CONS_COLUMNS.
This document discusses techniques for joining data from multiple database tables, including:
- Performing equijoins to retrieve matching records between tables based on equality conditions.
- Using outer joins to also return rows with no matches between tables.
- Self joins to join a table to itself based on relationships between records in the same table.
This document discusses data manipulation in Oracle databases. It describes how to insert new rows into tables using the INSERT statement, update existing rows using the UPDATE statement, and delete rows from tables using the DELETE statement. It also covers controlling transactions with commands like COMMIT, ROLLBACK, and SAVEPOINT to ensure data integrity when making multiple changes to a database.
This document discusses database objects like sequences, indexes, and synonyms. Sequences are used to automatically generate unique numbers, such as primary keys. Indexes improve query performance by allowing faster data retrieval. Synonyms provide alternative names for objects to simplify access. The document provides examples of creating, modifying, and removing these objects using SQL statements and reviewing their definitions in database data dictionaries.
The document provides an outline and introduction to basic SQL, including how data is structured in tables with rows and columns, different data types, and how to write simple queries to select, filter, and order data returned from one or multiple tables using keywords like SELECT, FROM, WHERE, and ORDER BY. Joins allow querying data across related tables by matching column values.
The document is a lecture on the SQL language given at Trinity College. It introduces SQL as the standard language for relational databases and describes it as declarative, meaning the user specifies the desired results without specifying how to retrieve them. It then discusses some basic SQL statements like CREATE TABLE to define the structure of tables and import data types for attributes.
This document provides an overview of basic SQL concepts including attribute ambiguity, aliasing, tuple variables, missing WHERE clauses, selecting all attributes with *, tables as sets, and set operations. It discusses how SQL allows duplicate tuples, qualifying attribute names, and retrieving distinct vs all values. Examples are provided for common SQL queries. The goal is to help students understand how to create and manipulate relational databases using SQL.
MySQL is an open-source relational database management system. The document discusses the introduction to MySQL, its development history, installation, features, data types, basic commands like CREATE, SELECT, UPDATE, DELETE. It also covers MySQL constraints. MySQL is widely used for web applications due to its speed, ease of use and open source nature. It can store and manage large volumes of data across different tables using relationships.
This document discusses various types of single-row functions in SQL including character, number, date, and conversion functions. It provides examples of using functions like UPPER, LOWER, ROUND, TRUNC, TO_CHAR, and NVL. Single-row functions manipulate or return a single value per row and may modify data types.
This document provides an overview of basic SQL statements and SQL*Plus commands. It describes how to select data from tables, perform calculations, define column aliases, and eliminate duplicate rows using the SELECT statement. It also outlines how to describe table structures, edit SQL statements, execute SQL within SQL*Plus, and load and save SQL files. The key goals of SQL statements are to select, project, and join data, while SQL*Plus is the environment used to execute SQL and manage database interactions.
This document provides an overview of Structured Query Language (SQL) and SQL Server by Brian Foote. It includes sections on SQL SELECT statements, joins, aggregate functions and more. The document covers basics like retrieving data from single and multiple tables, using ORDER BY, WHERE, and DISTINCT clauses. It also discusses aggregate functions like COUNT, MAX, MIN, AVG and SUM and using them with GROUP BY. Finally, it touches on other SQL topics like different join types, subqueries, temporary tables and exporting data to Excel.
After completing this lesson, you should be able to
do the following:
List the capabilities of SQL SELECT statements
Execute a basic SELECT statement
Differentiate between SQL statements and iSQL*Plus commands
http://phpexecutor.com
Tutorial for using SQL in Microsoft Accessmcclellm
SQL is a programming language used to manage data in relational databases. It allows users to insert, query, update and delete data from database tables. Microsoft Access is a common program that uses SQL to interact with its data tables, allowing users to run queries to retrieve certain records based on conditions. The document provides examples of SQL statements like SELECT, UPDATE, DELETE used in Microsoft Access and videos demonstrating how to execute them to select, modify and remove data from Access tables.
SQL injection is a code injection technique that exploits vulnerabilities in database-driven web applications. It occurs when user input is not validated or sanitized for string literal escape characters that are part of SQL statements. This allows attackers to interfere with the queries and obtain unauthorized access to sensitive data or make changes to the database. The document then provides step-by-step instructions on how to scan for vulnerabilities, determine database details like name and tables, extract data like user credentials, bypass protections like magic quotes, and use tools to automate the process.
The presentation has a quick preamble on SQL injection definition, sqlmap and its key features.
I then illustrate into details common and uncommon problems and respective solutions with examples that a penetration tester faces when he wants to take advantage of any kind of web application SQL injection flaw on real world web applications, for instance SQL injection in ORDER BY and LIMIT clauses, single entry UNION query SQL injection, specific web application technologies IDS bypasses and more.
These slides have been presented at the Front Range OWASP Conference in Denver on March 5, 2009.
This document discusses how to aggregate data using group functions in SQL. It describes various group functions like AVG, COUNT, MAX, MIN, and SUM. It explains how to use the GROUP BY clause to group data by one or more columns and produce aggregate results for each group. It also covers using the HAVING clause to filter groups based on aggregate conditions.
Les05[1]Aggregating Data Using Group Functionssiavosh kaviani
This document discusses how to use group functions in SQL to aggregate data and group rows together. It describes the available group functions like COUNT, AVG, MAX, MIN, and SUM. It explains how to use the GROUP BY clause to divide rows into groups and the HAVING clause to filter groups. It also shows examples of grouping data by department to find average salaries and summing salaries by job and department.
This document discusses how to use group functions in SQL to aggregate data and summarize information. Group functions such as MAX, MIN, SUM, AVG, COUNT operate on sets of rows and return one result per group. The GROUP BY clause is used to divide rows into groups, and the HAVING clause filters groups. Examples demonstrate finding minimum/maximum salaries, averages grouped by department, and sums grouped by multiple columns using functions like ROLLUP and CUBE.
The document provides an overview of Data Query Language (DQL) syntax for SELECT statements including:
- Selecting columns from tables
- Using column aliases
- Filtering rows with the WHERE clause
- Working with NULL values
- Sorting results with the ORDER BY clause
- Grouping rows with the GROUP BY clause and aggregate functions
- Filtering groups with the HAVING clause
- Sorting on multiple columns
- Nested subqueries
This document discusses cube, rollup and materialized views in Oracle databases. It provides an overview of how cube and rollup extend the GROUP BY clause to automatically calculate subtotals and totals. It also discusses how materialized views can store the results of a query to improve performance for frequent or complex queries. The document includes examples demonstrating how to use cube, rollup, and materialized views.
The SQL GROUP BY clause is used to retrieve data grouped by one or more columns. It is often used with aggregate functions like SUM to calculate totals for each group. For example, to find the total salary for each department, the query would select the department and sum of salaries, grouping by department. This groups the results by department and calculates the total salary for each department group.
The document discusses the GROUP BY clause in SQL, which groups or categorizes data in a table into smaller groups based on specified column(s). Group functions like SUM, COUNT, MAX, MIN can then return summary information for each group. The GROUP BY clause is used with SELECT statements to group data and apply aggregate functions to each group. It explains how to group data by single or multiple columns, and restrict groups using the HAVING clause.
The document discusses various aggregate functions used in SQL such as SUM, COUNT, AVG, MIN, and MAX. It provides examples of how to use these functions to retrieve aggregated data from tables, including the use of GROUP BY and HAVING clauses. Aggregate functions summarize data over multiple rows, returning a single value. COUNT(*) counts all rows while other functions like COUNT ignore NULL values.
This document discusses SQL group functions and how to summarize aggregated data from tables. It covers:
1) The main group functions - AVG, COUNT, MAX, MIN, SUM - and how to use them to aggregate numeric, character and date fields.
2) Using the GROUP BY clause to divide rows into groups and return aggregate results per group. Columns in the SELECT must be in the GROUP BY or be aggregate functions.
3) Applying the HAVING clause to restrict groups based on aggregate results, after rows are grouped and aggregate functions applied. HAVING cannot be used in the WHERE clause.
This document discusses SQL group functions and how to summarize aggregated data from tables. It covers:
1) The main group functions - AVG, COUNT, MAX, MIN, SUM - and how to use them to aggregate data from columns.
2) Using the GROUP BY clause to divide rows into groups and apply aggregate functions per group.
3) Using the HAVING clause to restrict groups based on aggregate conditions, since aggregates cannot be used in the WHERE clause.
This document discusses how to aggregate and group data using SQL functions. It covers various group functions like COUNT, MAX, MIN, AVG, and SUM. It explains how to use the GROUP BY clause to group rows by one or more columns and produce an aggregate result per group. It also explains how to use the HAVING clause to filter groups based on aggregate conditions.
Introduction to Oracle Functions--(SQL)--Abhishek Sharmaअभिषेक शर्मा
Functions make query results easier to understand and manipulate data values. There are two categories of functions: single row/scalar functions that return one value per row, and group/aggregate functions that operate on sets of values to return a single result. The GROUP BY clause groups rows based on columns and is used with aggregate functions to return summary results for each group.
The document discusses aggregate functions in SQL such as SUM, AVG, COUNT, MAX, MIN. It provides examples of using these functions to calculate totals, averages, counts and find maximum and minimum values from columns in tables. It also covers the use of the GROUP BY clause to perform aggregate calculations on grouped data and the HAVING clause to filter groups.
Aggregate row functions allow users to answer business questions by performing calculations on columns of data in tables. Common aggregate functions include COUNT, SUM, AVG, MIN, and MAX. These functions operate on groups of rows defined by the GROUP BY clause. The HAVING clause filters groups based on conditions with aggregates, similar to how WHERE filters rows.
The HAVING clause is used to filter data based on group functions, similar to a WHERE clause but for use with aggregate functions. Group functions like SUM cannot be used in a WHERE clause but can be used in a HAVING clause. An example SQL query uses a HAVING clause to select departments where the total salary paid is over $25,000. When used together, the WHERE clause is processed first before rows are grouped by the GROUP BY clause and then conditions in the HAVING clause are applied to the grouped rows.
The document provides information on various SQL functions. It discusses functions for sorting query results, performing calculations on aggregate data, grouping data, and filtering groups. Date and string functions are also covered, along with numeric and mathematical functions. Common functions include ORDER BY for sorting, SUM, AVG, COUNT for aggregates, GROUP BY for grouping, and HAVING for filtering groups. NOW() and SYSDATE() are described as functions for returning the current date and time.
Functions in Oracle can be used to manipulate data values and are categorized as single-row/scalar functions and group/aggregate functions. Single-row functions operate on each row and return one value per row, while group functions operate on sets of values to return one result. The GROUP BY clause is used to group or categorize data and can be used with aggregate functions to return summary results for each group.
Aggregating Data Using Group FunctionsSalman Memon
After completing this lesson, you should be able to
do the following:
Identify the available group functions
Describe the use of group functions
Group data using the GROUP BY clause
Include or exclude grouped rows by using the HAVING clause
http://phpexecutor.com
Oracle Week 2015 presentation (Presented on November 15, 2015)
Agenda:
Aggregative and advanced grouping options
Analytic functions, ranking and pagination
Hierarchical and recursive queries
Oracle 12c new rows pattern matching feature
XML and JSON handling with SQL
Regular Expressions
SQLcl – a new replacement tool for SQL*Plus from Oracle
This document discusses how to aggregate data using group functions in Oracle. It describes the available group functions like COUNT, MAX, MIN, AVG, and SUM. It explains how to group data using the GROUP BY clause and exclude grouped rows using the HAVING clause. It provides examples of queries that use various group functions along with the GROUP BY and HAVING clauses.
Automated Process for Auditng in Agile - SCRUMUmair Amjad
The document proposes an automated auditing model and tool called SAM (Scrum Auditing Machine) to provide project traceability for software projects using the Scrum agile framework. SAM would be available in three categories based on project size - large, medium, small - and would be used by Scrum Masters or auditors to track a project throughout its lifecycle. The tool would utilize current technologies like Ruby on Rails, AngularJS, Bootstrap, and would be open source to support auditing of Scrum software projects. A survey of 428 professionals found a need for improved auditing of agile projects.
Data Deduplication: Venti and its improvementsUmair Amjad
This document summarizes the data deduplication system called Venti and improvements over it. Venti identifies duplicate data blocks using cryptographic hashes of block contents. It stores only a single copy of each unique block. The document discusses three key limitations of Venti: hash collisions, fixed-size chunking sensitivity, and access control. It then summarizes approaches taken by other systems to improve on these limitations, such as using multiple hash functions to reduce collisions, variable-length chunking, and stronger authentication and encryption. In conclusion, while Venti was effective at eliminating data duplication, later systems aimed to address its remaining challenges to handle growing archive sizes securely and efficiently.
Bead–Sort :: A Natural Sorting AlgorithmUmair Amjad
The document describes a natural sorting algorithm called Bead-Sort that is inspired by observing beads falling through a frame. Bead-Sort can sort positive integers and has a time complexity that ranges from O(1) if all beads are dropped together, O(n) if beads are dropped row by row, or O(S) if each bead is dropped individually, where S is the sum of the input integers. The document also discusses three possible implementations of Bead-Sort as an analog hardware system, cellular automaton, or digital hardware.
- There are several ways to monitor Apache's status and performance such as using apachectl commands to check the version number or view the server status.
- The httpd.conf file can be configured to provide more detailed status information and make it available via the browser or remotely. Security measures like IP restrictions should be added.
- Apache has default error pages but custom pages can be configured using ErrorDocument directives. Multi-language error pages are also available.
- Access and error logs are automatically generated with each request and log important details. The location, format, and logging level can be configured via directives.
Exact Cell Decomposition of Arrangements used for Path Planning in RoboticsUmair Amjad
This is short overview of research paper.
We present a practical algorithm for the automatic generation of a map that describes the operation environment of an indoor mobile service robot. The input is a CAD description of a building consisting of line segments that represent the walls. The algorithm is based on the exact cell decomposition obtained when these segments are extended to infinite lines, resulting in a line arrangement. The cells are represented by nodes in a connectivity graph. The map consists of the connectivity graph and additional environmental information that is calculated for each cell. The method takes into account both the path planning and position verification requirements of the robot and has been implemented.
This document summarizes a DCT-based watermarking technique that allows detection of the watermark from a corrupted image without needing the original uncorrupted image. The technique embeds a watermark by modifying mid-frequency DCT coefficients of an image. During detection, the watermark is recovered by correlating the extracted DCT coefficients against different potential watermarks and selecting the one with the highest correlation. This avoids the need for the original image by directly correlating against watermarks rather than trying to estimate the original coefficients.
Multi-core processor and Multi-channel memory architectureUmair Amjad
Content of presentation:
Multi-core processors
Multi-channel memory architecture
Comparison between single and multi channel memory
Conclusion
References
The document discusses migrating from Rails 2 to Rails 3. Key changes include a new router, explicit dependency management with Bundler, assets pipeline, jQuery as default JavaScript library, reversible migrations, faster development mode, new routing engine, and automatic query explains. The migration process involves installing Rails 3, running an upgrade checker, backing up the app, generating a new Rails 3 app in the same directory, and installing dependencies with Bundler.
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!SOFTTECHHUB
As the digital landscape continually evolves, operating systems play a critical role in shaping user experiences and productivity. The launch of Nitrux Linux 3.5.0 marks a significant milestone, offering a robust alternative to traditional systems such as Windows 11. This article delves into the essence of Nitrux Linux 3.5.0, exploring its unique features, advantages, and how it stands as a compelling choice for both casual users and tech enthusiasts.
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
2. 5-2
Objectives
After completing this lesson, you shouldAfter completing this lesson, you should
be able to do the following:be able to do the following:
• Identify the available group functions
• Describe the use of group functions
• Group data using the GROUP BY clause
• Include or exclude grouped rows by
using the HAVING clause
3. 5-3
What Are Group Functions?
Group functions operate on sets of rows to giveGroup functions operate on sets of rows to give
one result per group.one result per group.
EMPEMP
““maximummaximum
salary insalary in
the EMP table”the EMP table”
DEPTNO SAL
--------- ---------
10 2450
10 5000
10 1300
20 800
20 1100
20 3000
20 3000
20 2975
30 1600
30 2850
30 1250
30 950
30 1500
30 1250
MAX(SAL)
---------
5000
4. 5-4
Types of Group Functions
• AVG
• COUNT
• MAX
• MIN
• STDDEV
• SUM
• VARIANCE
5. 5-5
Using Group Functions
SELECT [column,] group_function(column)
FROM table
[WHERE condition]
[GROUP BY column]
[ORDER BY column];
6. 5-6
Using AVG and SUM Functions
AVG(SAL) MAX(SAL) MIN(SAL) SUM(SAL)
-------- --------- --------- ---------
1400 1600 1250 5600
You can use AVG and SUM for numeric data.You can use AVG and SUM for numeric data.
SQL> SELECT AVG(sal), MAX(sal),
2 MIN(sal), SUM(sal)
3 FROM emp
4 WHERE job LIKE 'SALES%';
7. 5-7
Using MIN and MAX Functions
You can use MIN and MAX for any datatype.You can use MIN and MAX for any datatype.
SQL> SELECT MIN(hiredate), MAX(hiredate)
2 FROM emp;
MIN(HIRED MAX(HIRED
--------- ---------
17-DEC-80 12-JAN-83
8. 5-8
Using the COUNT Function
COUNT(*)
---------
6
SQL> SELECT COUNT(*)
2 FROM emp
3 WHERE deptno = 30;
COUNT(*) returns the number of rows in aCOUNT(*) returns the number of rows in a
table.table.
9. 5-9
Using the COUNT Function
COUNT(COUNT(exprexpr) returns the number of) returns the number of
nonnull rows.nonnull rows.
SQL> SELECT COUNT(comm)
2 FROM emp
3 WHERE deptno = 30;
COUNT(COMM)
-----------
4
10. 5-10
Group Functions and Null Values
Group functions ignore null values in theGroup functions ignore null values in the
column.column.
SQL> SELECT AVG(comm)
2 FROM emp;
AVG(COMM)
---------
550
11. 5-11
Using the NVL Function
with Group Functions
The NVL function forces group functionsThe NVL function forces group functions
to include null values.to include null values.
SQL> SELECT AVG(NVL(comm,0))
2 FROM emp;
AVG(NVL(COMM,0))
----------------
157.14286
12. 5-12
Creating Groups of Data
EMPEMP
““averageaverage
salarysalary
in EMPin EMP
tabletable
for eachfor each
department”department”
2916.66672916.6667
21752175
1566.66671566.6667
DEPTNO SAL
--------- ---------
10 2450
10 5000
10 1300
20 800
20 1100
20 3000
20 3000
20 2975
30 1600
30 2850
30 1250
30 950
30 1500
30 1250
DEPTNO AVG(SAL)
------- ---------
10 2916.6667
20 2175
30 1566.6667
13. 5-13
Creating Groups of Data:
GROUP BY Clause
SELECT column, group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];
Divide rows in a table into smaller groupsDivide rows in a table into smaller groups
by using the GROUP BY clause.by using the GROUP BY clause.
14. 5-14
Using the GROUP BY Clause
All columns in the SELECT list that are notAll columns in the SELECT list that are not
in group functions must be in the GROUPin group functions must be in the GROUP
BY clause.BY clause.
SQL> SELECT deptno, AVG(sal)
2 FROM emp
3 GROUP BY deptno;
DEPTNO AVG(SAL)
--------- ---------
10 2916.6667
20 2175
30 1566.6667
15. 5-15
Using the GROUP BY Clause
The GROUP BY column does not have toThe GROUP BY column does not have to
be in the SELECT list.be in the SELECT list.
SQL> SELECT AVG(sal)
2 FROM emp
3 GROUP BY deptno;
AVG(SAL)
---------
2916.6667
2175
1566.6667
16. 5-16
Grouping by More
Than One ColumnEMPEMP
““sum salaries insum salaries in
the EMP tablethe EMP table
for each job,for each job,
grouped bygrouped by
department”department”
DEPTNO JOB SAL
--------- --------- ---------
10 MANAGER 2450
10 PRESIDENT 5000
10 CLERK 1300
20 CLERK 800
20 CLERK 1100
20 ANALYST 3000
20 ANALYST 3000
20 MANAGER 2975
30 SALESMAN 1600
30 MANAGER 2850
30 SALESMAN 1250
30 CLERK 950
30 SALESMAN 1500
30 SALESMAN 1250
JOB SUM(SAL)
--------- ---------
CLERK 1300
MANAGER 2450
PRESIDENT 5000
ANALYST 6000
CLERK 1900
MANAGER 2975
CLERK 950
MANAGER 2850
SALESMAN 5600
DEPTNO
--------
10
10
10
20
20
20
30
30
30
17. 5-17
Using the GROUP BY Clause
on Multiple Columns
SQL> SELECT deptno, job, sum(sal)
2 FROM emp
3 GROUP BY deptno, job;
DEPTNO JOB SUM(SAL)
--------- --------- ---------
10 CLERK 1300
10 MANAGER 2450
10 PRESIDENT 5000
20 ANALYST 6000
20 CLERK 1900
...
9 rows selected.
18. 5-18
Illegal Queries
Using Group Functions
Any column or expression in the SELECTAny column or expression in the SELECT
list that is not an aggregate function mustlist that is not an aggregate function must
be in the GROUP BY clause.be in the GROUP BY clause.
SQL> SELECT deptno, COUNT(ename)
2 FROM emp;
SQL> SELECT deptno, COUNT(ename)
2 FROM emp;
SELECT deptno, COUNT(ename)
*
ERROR at line 1:
ORA-00937: not a single-group group function
SELECT deptno, COUNT(ename)
*
ERROR at line 1:
ORA-00937: not a single-group group function
Column missing in the GROUP BY clause
Column missing in the GROUP BY clause
19. 5-19
Illegal Queries
Using Group Functions
• You cannot use the WHERE clause to restrict
groups.
• You use the HAVING clause to restrict groups.
SQL> SELECT deptno, AVG(sal)
2 FROM emp
3 WHERE AVG(sal) > 2000
4 GROUP BY deptno;
SQL> SELECT deptno, AVG(sal)
2 FROM emp
3 WHERE AVG(sal) > 2000
4 GROUP BY deptno;
WHERE AVG(sal) > 2000
*
ERROR at line 3:
ORA-00934: group function is not allowed here
WHERE AVG(sal) > 2000
*
ERROR at line 3:
ORA-00934: group function is not allowed here
Cannot use the WHERE clause
Cannot use the WHERE clause
to restrict groups
to restrict groups
21. 5-21
Excluding Group Results:
HAVING Clause
Use the HAVING clause to restrict groupsUse the HAVING clause to restrict groups
– Rows are grouped.
– The group function is applied.
– Groups matching the HAVING clause
are displayed.
SELECT column, group_function
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
22. 5-22
Using the HAVING Clause
SQL> SELECT deptno, max(sal)
2 FROM emp
3 GROUP BY deptno
4 HAVING max(sal)>2900;
DEPTNO MAX(SAL)
--------- ---------
10 5000
20 3000
23. 5-23
Using the HAVING Clause
SQL> SELECT job, SUM(sal) PAYROLL
2 FROM emp
3 WHERE job NOT LIKE 'SALES%'
4 GROUP BY job
5 HAVING SUM(sal)>5000
6 ORDER BY SUM(sal);
JOB PAYROLL
--------- ---------
ANALYST 6000
MANAGER 8275
24. 5-24
Nesting Group Functions
SQL> SELECT max(avg(sal))
2 FROM emp
3 GROUP BY deptno;
MAX(AVG(SAL))
-------------
2916.6667
Display the maximum average salary.Display the maximum average salary.
25. 5-25
Summary
SELECT column, group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
Order of evaluation of the clauses:Order of evaluation of the clauses:
• WHERE clause
• GROUP BY clause
• HAVING clause
26. 5-26
Practice Overview
• Showing different queries that use
group functions
• Grouping by rows to achieve more than
one result
• Excluding groups by using the HAVING
clause
Editor's Notes
Schedule: Timing Topic 35 minutes Lecture 40 minutes Practice 75 minutes Total
Lesson Aim This lesson further addresses functions. It focuses on obtaining summary information, such as averages, for groups of rows. It discusses how to group rows in a table into smaller sets and how to specify search criteria for groups of rows.
Group Functions Unlike single-row functions, group functions operate on sets of rows to give one result per group. These sets may be the whole table or the table split into groups.
Group Functions (continued) Each of the functions accepts an argument. The following table identifies the options that you can use in the syntax:
Guidelines for Using Group Functions DISTINCT makes the function consider only nonduplicate values; ALL makes it consider every value including duplicates. The default is ALL and therefore does not need to be specified. The datatypes for the arguments may be CHAR, VARCHAR2, NUMBER, or DATE where expr is listed. All group functions except COUNT(*) ignore null values. To substitute a value for null values, use the NVL function. The Oracle Server implicitly sorts the result set in ascending order when using a GROUP BY clause. To override this default ordering, DESC can be used in an ORDER BY clause. Class Management Note Stress the use of DISTINCT and group functions ignoring null values. ALL is the default and is very rarely specified.
Group Functions You can use AVG, SUM, MIN, and MAX functions against columns that can store numeric data. The example on the slide displays the average, highest, lowest, and sum of monthly salaries for all salespeople.
Group Functions (continued) You can use MAX and MIN functions for any datatype. The slide example displays the most junior and most senior employee. The following example displays the employee name that is first and the employee name that is the last in an alphabetized list of all employees. Note: AVG, SUM, VARIANCE, and STDDEV functions can be used only with numeric datatypes. SQL> SELECT MIN(ename), MAX(ename) 2 FROM emp; MIN(ENAME) MAX(ENAME) ---------- ---------- ADAMS WARD
The COUNT Function The COUNT function has two formats: COUNT(*) COUNT( expr ) COUNT(*) returns the number of rows in a table, including duplicate rows and rows containing null values in any of the columns. If a WHERE clause is included in the SELECT statement, COUNT(*) returns the number of rows that satisfies the condition in the WHERE clause. In contrast, COUNT( expr ) returns the number of nonnull rows in the column identified by expr . The slide example displays the number of employees in department 30. Class Management Note Demo: l5count1.sql, l5count2.sql Purpose: To illustrate using the COUNT(*) and COUNT( expr ) functions.
The COUNT Function (continued) The slide example displays the number of employees in department 30 who can earn a commission. Notice that the result gives the total number of rows to be four because two employees in department 30 cannot earn a commission and contain a null value in the COMM column. Example Display the number of departments in the EMP table. Display the number of distinct departments in the EMP table. SQL> SELECT COUNT(deptno) 2 FROM emp; COUNT(DEPTNO) ------------- 14 SQL> SELECT COUNT(DISTINCT (deptno)) 2 FROM emp; COUNT(DISTINCT(DEPTNO)) ----------------------- 3
Group Functions and Null Values All group functions except COUNT (*) ignore null values in the column. In the slide example, the average is calculated based only on the rows in the table where a valid value is stored in the COMM column. The average is calculated as total commission being paid to all employees divided by the number of employees receiving commission (4).
Group Functions and Null Values (continued) The NVL function forces group functions to include null values. In the slide example, the average is calculated based on all rows in the table regardless of whether null values are stored in the COMM column. The average is calculated as total commission being paid to all employees divided by the total number of employees in the company (14).
Groups of Data Until now, all group functions have treated the table as one large group of information. At times, you need to divide the table of information into smaller groups. This can be done by using the GROUP BY clause.
The GROUP BY Clause You can use the GROUP BY clause to divide the rows in a table into groups. You can then use the group functions to return summary information for each group. In the syntax: group_by_expression specifies columns whose values determine the basis for grouping rows Guidelines If you include a group function in a SELECT clause, you cannot select individual results as well unless the individual column appears in the GROUP BY clause. You will receive an error message if you fail to include the column list. Using a WHERE clause, you can preexclude rows before dividing them into groups. You must include the columns in the GROUP BY clause. You cannot use the column alias in the GROUP BY clause. By default, rows are sorted by ascending order of the columns included in the GROUP BY list. You can override this by using the ORDER BY clause.
The GROUP BY Clause (continued) When using the GROUP BY clause, make sure that all columns in the SELECT list that are not in the group functions are included in the GROUP BY clause. The example on the slide displays the department number and the average salary for each department. Here is how this SELECT statement, containing a GROUP BY clause, is evaluated: The SELECT clause specifies the columns to be retrieved: Department number column in the EMP table The average of all the salaries in the group you specified in the GROUP BY clause The FROM clause specifies the tables that the database must access: the EMP table. The WHERE clause specifies the rows to be retrieved. Since there is no WHERE clause, by default all rows are retrieved. The GROUP BY clause specifies how the rows should be grouped. The rows are being grouped by department number, so the AVG function that is being applied to the salary column will calculate the average salary for each department.
The GROUP BY Clause (continued) The GROUP BY column does not have to be in the SELECT clause. For example, the SELECT statement on the slide displays the average salaries for each department without displaying the respective department numbers. Without the department numbers, however, the results do not look meaningful. You can use the group function in the ORDER BY clause. Class Management Note Demonstrate the query with and without the DEPTNO in the SELECT statement. SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 GROUP BY deptno 4 ORDER BY AVG(sal); DEPTNO AVG(SAL) ---------- ------------ 30 1566.6667 20 2175 10 2916.6667
Groups Within Groups Sometimes there is a need to see results for groups within groups. The slide shows a report that displays the total salary being paid to each job title, within each department. The EMP table is grouped first by department number, and within that grouping, it is grouped by job title. For example, the two clerks in department 20 are grouped together and a single result (total salary) is produced for all salespeople within the group. Class Management Note Demo: l5order1.sql,l5order2.sql Purpose: To illustrate ordering columns that are grouped by DEPTNO first and ordering columns that are grouped by JOB first.
Groups Within Groups (continued) You can return summary results for groups and subgroups by listing more than one GROUP BY column. You can determine the default sort order of the results by the order of the columns in the GROUP BY clause. Here is how the SELECT statement on the slide, containing a GROUP BY clause, is evaluated: The SELECT clause specifies the column to be retrieved: Department number in the EMP table Job title in the EMP table The sum of all the salaries in the group that you specified in the GROUP BY clause The FROM clause specifies the tables that the database must access: the EMP table. The GROUP BY clause specifies how you must group the rows: First, the rows are grouped by department number. Second, within the department number groups, the rows are grouped by job title. So the SUM function is being applied to the salary column for all job titles within each department number group.
Illegal Queries Using Group Functions Whenever you use a mixture of individual items (DEPTNO) and group functions (COUNT) in the same SELECT statement, you must include a GROUP BY clause that specifies the individual items (in this case, DEPTNO). If the GROUP BY clause is missing, then the error message “not a single-group group function” appears and an asterisk (*) points to the offending column. You can correct the error on the slide by adding the GROUP BY clause. Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause. Class Management Note Demo: l5error.sql Purpose: To illustrate executing a SELECT statement with no GROUP BY clause. SQL> SELECT deptno, COUNT(ename) 2 FROM emp 3 GROUP BY deptno; DEPTNO COUNT(ENAME) ---------- ------------ 10 3 20 5 30 6
Illegal Queries Using Group Functions (continued) The WHERE clause cannot be used to restrict groups. The SELECT statement on the slide results in an error because it uses the WHERE clause to restrict the display of average salaries of those departments that have an average salary greater than $2000. You can correct the slide error by using the HAVING clause to restrict groups. SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 GROUP BY deptno 4 HAVING AVG(sal) > 2000; DEPTNO AVG(SAL) ---------- -------------- 10 2916.6667 20 2175
Restricting Group Results In the same way that you use the WHERE clause to restrict the rows that you select, you use the HAVING clause to restrict groups. To find the maximum salary of each department, but show only the departments that have a maximum salary of more than $2900, you need to do the following: Find the average salary for each department by grouping by department number. Restrict the groups to those departments with a maximum salary greater than $2900.
The HAVING Clause You use the HAVING clause to specify which groups are to be displayed. Therefore, you further restrict the groups on the basis of aggregate information. In the syntax: group_condition restricts the groups of rows returned to those groups for which the specified condition is TRUE The Oracle Server performs the following steps when you use the HAVING clause: Rows are grouped. The group function is applied to the group. The groups that match the criteria in the HAVING clause are displayed. The HAVING clause can precede the GROUP BY clause, but it is recommended that you place the GROUP BY clause first because it is more logical. Groups are formed and group functions are calculated before the HAVING clause is applied to the groups in the SELECT list.
The HAVING Clause (continued) The slide example displays department numbers and maximum salary for those departments whose maximum salary is greater than $2900. You can use the GROUP BY clause without using a group function in the SELECT list. If you restrict rows based on the result of a group function, you must have a GROUP BY clause as well as the HAVING clause. The following example displays the department numbers and average salary for those departments whose maximum salary is greater than $2900: SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 GROUP BY deptno 4 HAVING MAX(sal) > 2900; DEPTNO AVG(SAL) --------- --------- 10 2916.6667 20 2175
The HAVING Clause (continued) The slide example displays the job title and total monthly salary for each job title with a total payroll exceeding $5000. The example excludes salespeople and sorts the list by the total monthly salary. Class Management Note Demo: l5job1.sql, l5job2.sql Purpose: To illustrate using a WHERE clause to restrict rows by JOB and using a HAVING clause to restrict groups by SUM(SAL).
Nesting Group Functions Group functions can be nested to a depth of two. The slide example displays the maximum average salary.
Summary Seven group functions are available in SQL: AVG COUNT MAX MIN SUM STDDEV VARIANCE You can create subgroups by using the GROUP BY clause. Groups can be excluded using the HAVING clause. Place the HAVING and GROUP BY clauses after the WHERE clause in a statement. Place the ORDER BY clause last. The Oracle Server evaluates the clauses in the following order: If the statement contains a WHERE clause, the server establishes the candidate rows. The server identifies the groups specified in the GROUP BY clause. The HAVING clause further restricts result groups that do not meet the group criteria in the HAVING clause.
Practice Overview At the end of this practice, you should be familiar with using group functions and selecting groups of data. Paper-Based Questions For questions 1 – 3, circle either True or False. Note: Column aliases are used for the queries. Class Management Note Hint for Practice #7: Advise the students to think about the MGR column in EMP when determining the number of managers, rather than the JOB column.