0% found this document useful (0 votes)
14 views6 pages

Key SQL Keywords with Examples

Uploaded by

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

Key SQL Keywords with Examples

Uploaded by

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

In database management systems (DBMS), SQL is used for querying and managing databases.

Here’s a
breakdown of the key SQL keywords AS, LIMIT, TOTAL, AVG, DISTINCT and GROUP BY along with
examples to illustrate their usage.

1. AS
Purpose: AS is used to create an alias for a column or table. This alias makes complex queries more
readable and can also be used to rename columns in the result set.
Syntax:
SELECT column_name AS alias_name FROM table_name;
Example:
SELECT employee_name AS Name, employee_salary AS Salary
FROM employees;
Explanation: In this example, employee_name is aliased as Name, and employee_salary as Salary,
making the output more readable.
Output:
Name | Salary
------------|--------
John Doe | 50000
Jane Smith | 60000

2. LIMIT
Purpose: LIMIT is used to specify the number of records to return in the result set. It’s often used when
dealing with large datasets to restrict the number of rows displayed.
Syntax:
SELECT column_name FROM table_name LIMIT number_of_rows;
Example:
SELECT employee_name FROM employees LIMIT 3;
Explanation: This query returns only the first three rows from the employees table.
Output:
employee_name
-------------
John Doe
Jane Smith
Peter Parker

3. TOTAL
Purpose: TOTAL is not a standard SQL function but may be used in certain DBMS like SQLite to sum
values. It’s similar to SUM, but TOTAL returns 0.0 instead of NULL when there are no matching rows.
Syntax:
SELECT TOTAL(column_name) FROM table_name;
Example:
SELECT TOTAL(employee_salary) AS TotalSalary FROM employees;
Explanation: This query calculates the total salary of all employees in the employees table. If no salaries
are present, it returns 0.0.
Output:
markdown
TotalSalary
-----------
170000.0

4. AVG
Purpose: AVG is an aggregate function that calculates the average value of a numeric column.
Syntax:
SELECT AVG(column_name) FROM table_name;
Example:
SELECT AVG(employee_salary) AS AverageSalary FROM employees;
Explanation: This query calculates the average salary of all employees in the employees table.
Output:
AverageSalary
-------------
56666.67

5. DISTINCT
Purpose: DISTINCT is used to return unique values, eliminating duplicates from the result set.
Syntax:
SELECT DISTINCT column_name FROM table_name;
Example:
SELECT DISTINCT department FROM employees;
Explanation: This query returns a list of unique departments in the employees table.
Output:
department
----------
IT
HR
Marketing

Combined Example:
Let’s combine some of the above keywords in a single query to illustrate their use together.
 Scenario: You want to find the average salary of employees in the "IT" department and limit the
result to the top 2 rows, displaying the department as "Department" and the average salary as
"Average Salary".
SELECT DISTINCT department AS Department, AVG(employee_salary) AS "Average Salary"
FROM employees
WHERE department = 'IT'
LIMIT 2;

Explanation:
DISTINCT ensures that only unique department names are retrieved.
AS creates aliases for the columns.
AVG calculates the average salary for employees in the IT department.
LIMIT restricts the result to 2 rows.

Output:
Department | Average Salary
-----------|----------------
IT | 60000

Key Takeaways:
 AS helps create aliases for better readability of results.
 LIMIT is useful when working with large datasets to limit the output.
 TOTAL (in SQLite) is used to sum values, returning 0.0 if no rows match.
 AVG calculates the average of a numeric column.
 DISTINCT is essential for eliminating duplicates from result sets.
The GROUP BY clause in SQL is used to group rows that have the same values in specified columns into
aggregated data. It’s often used in conjunction with aggregate functions like COUNT, SUM, AVG, MIN,
or MAX to perform calculations on each group of rows.
Syntax
SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1;

column1: The column by which the rows will be grouped.


aggregate_function(column2): An aggregate function applied to column2 for each group created
by column1.
Example Scenario
Scenario Description:
Consider a table named orders with the following columns: order_id, customer_id, product, quantity, and
price. You want to calculate the total quantity ordered by each customer.
Table Data:

order_id customer_id product quantity price

1 101 Widget A 3 10.0

2 102 Widget B 2 15.0

3 101 Widget A 1 10.0

4 103 Widget C 4 20.0

5 102 Widget A 2 10.0

Query:
SELECT customer_id, SUM(quantity) AS TotalQuantity
FROM orders
GROUP BY customer_id;
Explanation:
GROUP BY customer_id groups the rows by customer_id.
SUM(quantity) calculates the total quantity for each customer_id.
AS TotalQuantity renames the result column for readability.
Output:

customer_id TotalQuantity

101 4

102 4

103 4

Key Points:
The GROUP BY clause is especially useful for summarizing data and creating reports based on
grouped records.
Columns specified in SELECT but not in aggregate functions must be included in the GROUP
BY clause to avoid errors.
In this example, GROUP BY allowed us to find the total quantity of products ordered by each customer.

Common questions

Powered by AI

Using 'AVG' and 'GROUP BY' together in a query provides meaningful insights by calculating the average values within specific groups. For example, consider a sales database where you want to find the average sales per salesperson. The query `SELECT salesperson_id, AVG(sale_amount) AS AvgSale FROM sales GROUP BY salesperson_id` would calculate the average sales amount for each salesperson. This combination helps identify performance trends across sales staff and determine who might be performing above or below average, which can inform training or resource allocation decisions .

Using 'GROUP BY' with 'SUM' in SQL enables comprehensive reporting by aggregating data into groups based on common column values and then summarizing each group using the SUM function. This combination provides totals for each category of interest. For example, the query `SELECT customer_id, SUM(quantity) AS TotalQuantity FROM orders GROUP BY customer_id` calculates the total quantity of orders for each customer. It simplifies complex datasets into manageable summaries, allowing decision-makers to gain insights into customer behaviors and sales trends across different segments of the data .

Combining SQL keywords like DISTINCT, AVG, and LIMIT within a single query allows for more refined data analysis by leveraging multiple functions simultaneously. For example, the query `SELECT DISTINCT department AS Department, AVG(employee_salary) AS "Average Salary" FROM employees WHERE department = 'IT' LIMIT 2` makes use of DISTINCT to ensure unique department names, AVG to calculate the average salary in the 'IT' department, and LIMIT to restrict the result to the top two rows . Such combinations enable users to perform complex data analyses in a concise and efficient manner, tailoring the output to precisely meet the analysis criteria.

The 'TOTAL' function in SQLite might be preferred over 'SUM' because it returns 0.0 instead of NULL when there are no matching rows to sum. This behavior is useful in scenarios where a result is expected to always represent a numeric value, even if it's zero, rather than returning a NULL, which might require additional handling in the application. For example, the query `SELECT TOTAL(employee_salary) AS TotalSalary FROM employees` would return 0.0 if no salaries are present , ensuring consistency in the type of the result returned.

The 'DISTINCT' keyword can improve the accuracy of result sets by eliminating duplicate records, ensuring that each value is unique. This is particularly useful for obtaining a list of unique values within a column, such as retrieving all the distinct departments in an organization. For example, the query `SELECT DISTINCT department FROM employees` returns only the unique department names . Without 'DISTINCT', the same department name might appear multiple times if employees work in the same department, leading to redundant information.

The SQL keyword 'AS' is used to create aliases for columns or tables in a query, which enhances readability by providing more meaningful names. In complex queries, this makes the result set clearer and easier to understand. For example, in the query `SELECT employee_name AS Name, employee_salary AS Salary FROM employees`, 'AS' renames 'employee_name' to 'Name' and 'employee_salary' to 'Salary' . This simplification helps users quickly grasp the context of the data without having to interpret potentially complex or cryptically named columns.

When deciding to use the 'LIMIT' clause in a SQL query, several factors should be considered: the dataset size, the query's performance impact, and the relevance of the data displayed to the user. LIMIT is particularly useful for handling large datasets to avoid performance degradation by returning only a subset of records. It should also be used when the user requires a preview rather than the full dataset, such as displaying paginated search results or summaries. However, careful consideration of the context is necessary to ensure that the most relevant data is returned within the limited set .

Renaming columns and tables in SQL queries using the 'AS' keyword offers several advantages. It improves the readability and clarity of query results by assigning intuitive and meaningful names, which makes complex data more accessible to users. This strategy aids in documentation and maintenance, as renamed columns can better match business terminology, reducing misunderstandings. Additionally, creating aliases through 'AS' facilitates easier integration with application output formats where column names need to conform to specific formats or standards. For example, `SELECT employee_name AS Name, employee_salary AS Salary FROM employees` provides clearer reports by using everyday terms for column names .

The 'GROUP BY' clause in SQL plays a critical role in data summarization by grouping rows that share the same values in specified columns. It organizes data into categories and allows aggregate functions like COUNT, SUM, AVG, MIN, or MAX to be applied to each group. For instance, in the query `SELECT customer_id, SUM(quantity) AS TotalQuantity FROM orders GROUP BY customer_id`, 'GROUP BY customer_id' aggregates the total quantities ordered by each customer . This mechanism is essential for creating meaningful summaries and reports from raw data, enabling insights into structured metrics across different data segments.

The SQL keyword 'LIMIT' is particularly useful in scenarios where there is a need to manage large datasets efficiently by restricting the number of rows returned in a query. For instance, when displaying search results or data reports, limiting the output to a manageable size prevents overwhelming the user with too much information and helps improve query performance by reducing the processing required. An example usage is `SELECT employee_name FROM employees LIMIT 3`, which returns only the first three rows from the employees table . This ensures that resources are used efficiently, especially in systems with large volumes of data.

You might also like