Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views23 pages

SQL Commands

The document provides an overview of data warehousing, including its purpose, structure, and the ETL process for data integration. It also explains Entity-Relationship Diagrams (ERDs), star and snowflake schemas, and the differences between OLAP and OLTP systems. Additionally, it covers SQL commands for data manipulation, integrity constraints, and strategies for data retrieval.

Uploaded by

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

SQL Commands

The document provides an overview of data warehousing, including its purpose, structure, and the ETL process for data integration. It also explains Entity-Relationship Diagrams (ERDs), star and snowflake schemas, and the differences between OLAP and OLTP systems. Additionally, it covers SQL commands for data manipulation, integrity constraints, and strategies for data retrieval.

Uploaded by

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

01-04-2023

Data Warehouse
• A data warehouse is a large, centralized repository of data that is used
for business intelligence and decision-making purposes. The purpose

SQL Commands of a data warehouse is to provide a comprehensive view of an


organization's data, by integrating data from multiple sources and
transforming it into a standardized format.
By
Dr.Pooja Jain • Data warehouses are typically used in organizations with large
amounts of data, where it is difficult to extract insights from that data
IIIT Nagpur
using traditional database systems. Data warehouses are optimized
for querying and analyzing large datasets, and they often use
specialized tools and techniques to support data mining and analytics.

Data Warehouse Data Warehouse


• The process of creating a data warehouse typically involves extracting • Data warehouses typically have a large amount of historical data,
data from multiple sources, such as databases, data streams, and which allows organizations to analyze trends and patterns over time.
external systems. The data is then transformed and integrated to They also often have a dimensional structure, which allows data to be
ensure consistency and accuracy, and loaded into the data organized in a way that is optimized for querying and analysis.
warehouse. This process is often referred to as Extract, Transform, • Overall, data warehouses are an important tool for organizations that
Load (ETL). need to analyze large amounts of data to make informed business
• Once the data is loaded into the data warehouse, it can be analyzed decisions. They allow organizations to integrate and analyze data from
using business intelligence tools, such as data visualization and multiple sources, and provide a comprehensive view of an
reporting tools. These tools allow users to explore the data and organization's data.
extract insights that can be used to inform business decisions.

1
01-04-2023

ERD ERD
• An ERD (Entity-Relationship Diagram) is a graphical representation of An ERD typically consists of the following components:
entities, attributes, and relationships that exist in a database. ERDs • Entities: Entities are objects or concepts that have attributes and
are used in database design to model and define the relationships relationships with other entities. In an ERD, entities are represented
between different entities and their attributes. by rectangles.
• Attributes: Attributes are characteristics or properties of an entity. In
an ERD, attributes are represented by ovals or ellipses, and are
connected to their respective entities.
• Relationships: Relationships are the associations between two or
more entities. In an ERD, relationships are represented by lines that
connect two or more entities.

ERD ERD
There are three types of relationships that can exist between entities: • In an ERD, relationships can also have attributes, which describe the
• One-to-one: This relationship exists when one entity is associated characteristics of the relationship itself.
with only one instance of another entity. • ERDs are an important tool in database design, as they allow
• One-to-many: This relationship exists when one entity is associated designers to visualize the relationships between entities and their
with multiple instances of another entity. attributes. This helps ensure that the database design is accurate and
efficient, and that the database can be easily queried and analyzed.
• Many-to-many: This relationship exists when multiple instances of
one entity are associated with multiple instances of another entity.

2
01-04-2023

Star and snowflake schema


• Star and snowflake schemas are two common data warehouse
modeling techniques used to organize data in a way that is optimized
for querying and analysis.
• The star schema is a simple, denormalized design that consists of a
central fact table surrounded by dimension tables. The fact table
contains the quantitative measures of the data (e.g. sales figures),
while the dimension tables contain descriptive information about the
data (e.g. time, location, product). Each dimension table is connected
to the fact table through a foreign key, which allows for easy querying
and analysis.

Star and snowflake schema Star and snowflake schema


• The snowflake schema is a more complex, normalized design that builds on • Both schema types have their advantages and disadvantages and are
the star schema by breaking down some of the dimension tables into used in different situations depending on the requirements of the
smaller, related tables. This results in a more normalized schema, with less
data redundancy, but also requires more complex queries to access the organization. The star schema is commonly used in smaller, simpler
data. The snowflake schema gets its name from its appearance, as it data warehouses with fewer dimensions, while the snowflake schema
resembles a snowflake with the central fact table surrounded by dimension is often used in larger, more complex data warehouses with many
tables that branch off into additional tables. dimensions.
• The key difference between the two schemas is in their level of
normalization. The star schema is denormalized, with all the information in
one table, which makes it easier to understand and query but can lead to
data redundancy. The snowflake schema is more normalized, with
information split across multiple tables, which reduces data redundancy
but can make it more complex to query.

3
01-04-2023

OLAP vs OLTP OLAP vs OLTP


• OLAP (Online Analytical Processing) and OLTP (Online Transactional • OLAP is a type of database architecture designed for analytical processing
of large amounts of data. It is optimized for complex queries and reporting,
Processing) are two types of database architectures used for different and allows users to analyze data from different perspectives and
purposes. dimensions.
• OLTP is a type of database architecture designed for transactional • OLAP databases are designed to support decision-making and business
intelligence applications by providing fast, flexible, and interactive access to
processing of large amounts of data. It is used to process and manage multidimensional data. Examples of OLAP systems include data warehouses
real-time transactions and is optimized for fast, reliable, and and business intelligence systems.
consistent data processing. OLTP databases are designed to support • The key difference between OLTP and OLAP is in their focus and design.
frequent and concurrent transactions, ensuring data integrity and OLTP databases are designed for real-time transactional processing, while
OLAP databases are designed for analytical processing and reporting. OLTP
consistency. Examples of OLTP systems include bank transaction databases are optimized for fast data updates and consistency, while OLAP
systems, airline reservation systems, and point-of-sale systems. databases are optimized for complex queries and reporting.

Entity constraints Entity constraints


• Constraints are rules that can be applied to the columns of a database • FOREIGN KEY Constraint: This constraint establishes a relationship
table to ensure data integrity and consistency. Here are the four types between two tables. It ensures that the values in a column of one
of constraints commonly used in databases: table match the values in a column of another table. For example, a
• UNIQUE Constraint: This constraint ensures that each value in a column is foreign key constraint can be used to link a customer table with an
unique across all rows in the table. For example, a UNIQUE constraint can be order table by ensuring that each order has a valid customer ID.
used on an email column to ensure that no two users have the same email
address. • NOT NULL Constraint: This constraint ensures that a column cannot
• PRIMARY KEY Constraint: This constraint uniquely identifies each row in a contain null values. It is used to enforce data integrity by requiring
table. A primary key column must contain a unique value for each row, and it that a value be entered for each row in a column.
cannot contain null values. A table can have only one primary key constraint.

4
01-04-2023

Referential constraints Referential constraints


• Referential constraints, also known as foreign key constraints, are a • Referential constraints are important for maintaining the accuracy
type of constraint used in relational databases to ensure the integrity and consistency of data in a database. They ensure that data is not
of data across related tables. Referential constraints establish a duplicated or lost due to inconsistencies in related tables, and they
relationship between two tables by linking a column in one table to a help to maintain the overall integrity of the database.
column in another table.
• A referential constraint works by enforcing the following two rules:
• The foreign key column in the child table (the table that references the parent
table) must contain only values that exist in the primary key column of the
parent table.
• When a row in the parent table is deleted or updated, the corresponding
rows in the child table must also be deleted or updated (depending on the
specific action defined in the constraint).

Semantic constraints Semantic constraints


• Semantic constraints are a type of constraint used in databases that Examples of semantic constraints include:
are based on the meaning or context of the data. Unlike other • Domain constraints: These constraints specify the valid values that can be entered into a
column. For example, a domain constraint can ensure that a birthdate column only
constraints that are based on data type or structure, semantic contains dates that are in the past and not in the future.
constraints enforce rules that are specific to the domain of the data • Entity integrity constraints: These constraints ensure that each row in a table has a
unique identifier or primary key. Entity integrity constraints prevent the entry of
being stored. These constraints ensure that the data being entered duplicate or missing data.
into the database is accurate, consistent, and meaningful. • Referential integrity constraints: These constraints ensure that the relationships between
tables are maintained. Referential integrity constraints prevent the entry of inconsistent
or invalid data.
• Business rules: These are constraints that are specific to the business or organization that
is using the database. Business rules ensure that the data entered into the database
adheres to the policies and procedures of the organization. For example, a business rule
can require that a customer's account balance cannot be negative.

5
01-04-2023

Semantic constraints
• Semantic constraints are an important tool for ensuring the accuracy
and consistency of data in a database. They help to prevent errors,
improve data quality, and ensure that the data is meaningful and
relevant to the domain being represented.

SQL queries

SQL 3 Types of SQL Commands


• SQL is a data manipulation language. • Data Definition Language (DDL):
• SQL is not a programming language. • Commands that define a database - Create, Alter, Drop
• SQL commands are interpreted by the DBMS • Data Manipulation Language (DML)
engine. • Commands that maintain and query a database.
• SQL commands can be used interactively as a • Data Control Language (DCL)
query language within the DBMS. • Commands that control a database, including administering
privileges and committing data.
• SQL commands can be embedded within
programming languages.

6
01-04-2023

Data Manipulation Language (DML)


Inserting Data into a Table
Four basic commands: INSERT INTO tablename (column-list)
VALUES (value-list)
• INSERT
• UPDATE PUTS ONE ROW INTO A TABLE
• DELETE
• SELECT INSERT INTO COURSE
(COURSE_CODE, COURSE_NAME,
CREDIT_HOURS)
VALUES (‘MIS499’,’ADVANCED ORACLE’,4);

More on Inserting Data Inserting Null Data


INSERT INTO COURSE INSERT INTO COURSE
VALUES (‘MIS499’,’ADVANCED ORACLE’,4); (COURSE_CODE, CREDIT_HOURS)
VALUES (‘MIS499’,4); COLUMN LIST IS NEEDED IF
COLUMN LIST IS OPTIONAL IF YOU PLAN TO YOU PLAN TO LEAVE OUT A
INSERT A VALUE IN EVERY COLUMN AND IN VALUE IN THE VALUE LIST
THE SAME ORDER AS IN THE TABLE
INSERT INTO COURSE COLUMN LIST CAN BE OMITTED
VALUES (‘MIS499’,’’,4); IF YOU PUT IN A BLANK VALUE
INSERT INTO COURSE
(COURSE_NAME, COURSE_CODE, THE NULL KEYWORD CAN
CREDIT_HOURS) INSERT INTO COURSE BE USED TO CREATE A BLANK
COLUMN
VALUES (’ADVANCED ORACLE’,‘MIS499’,4); VALUES (‘MIS499’,NULL,4);

COLUMN LIST IS NEEDED


ALL OF THESE ASSUME THAT THE DATABASE ALLOWS THE COLUMN TO
TO CHANGE THEORDER NOTE - TABLE STILL HAS THE
BE NULL. YOU CANNOT LEAVE PRIMARY KEYS AND FOREIGN KEYS BLANK
- MUST MATCH VALUE LIST ORIGINAL COLUMN ORDER

7
01-04-2023

Inserting and Integrity Constraints Entity Integrity Problems


SQL> INSERT INTO SECTION VALUES
('1234','MIS333','10-12','MW','COPE101','200000000'); SQL> INSERT INTO COURSE
INSERT INTO SECTION VALUES ('MIS220','NEW',4);
VALUES ('1234','MIS333','10-12','MW','COPE101',
*
ERROR at line 1: insert into course values ('MIS220','NEW',4)
ORA-02291: integrity constraint (ORA40.SYS_C00337)
violated - parent key not COURSE
*
found SECTION COURSE_CODE KEY
ERROR at line 1:
CALL_NUMBER KEY
COURSE_NAME
CREDIT_HOURS
ORA-00001: unique constraint
COURSE_CODE
SECTION_TIME INSTRUCTOR (ORA40.SYS_C00335) violated
SECTION_DAYS
SECTION_ROOM INSTRUCTOR_ID KEY
INSTRUCTOR_ID INSTRUCTOR_NAME
INSTRUCTOR_OFFICE

Deleting Data Updating Data


Be careful!! This deletes ALL of
DELETE from COURSE; the rows in your table. If you UPDATE COURSE SET HOURS=5;
DELETES ALL ROWS use this command in error, you CHANGES EVERY ROW
can use ROLLBACK to undo
the changes.
DELETE from COURSE WHERE UPDATE COURSE SET HOURS=5
COURSE_CODE = ‘MIS220’; WHERE COURSE_CODE=‘MIS220’
DELETES SPECIFIC ROWS (MORE TYPICAL) CHANGES ONE ROW (MORE TYPICAL)

DELETE from COURSE WHERE HOURS=4; UPDATE COURSE SET HOURS=3


DELETES A GROUP OF ROWS WHERE COURSE_CODE LIKE ‘MIS%’
DELETE from COURSE WHERE HOURS<4; CHANGES A GROUP OF ROWS

8
01-04-2023

Updating and Integrity Constraints Integrity Error


YOU CAN CHANGE THE VALUE OF A FOREIGN SQL> UPDATE COURSE
KEY AS LONG AS THE NEW VALUE ALSO SET COURSE_CODE='MIS221‘
COMPLIES WITH REFERENTIAL INTEGRITY WHERE COURSE_CODE='MIS220';
CONSTRAINTS.
UPDATE COURSE

PRIMARY KEY VALUES CAN BE UPDATED AS *


LONG AS THERE ARE NO ROWS IN OTHER ERROR at line 1:
TABLES WITH FOREIGN KEYS WITH THE ORA-02292: integrity constraint (ORA40.SYS_C00341)
SAME VALUE violated - child record found

DOES NOT MATTER IF CONSTRAINT IS


RESTRICTED OR CASCADED

Rollback and Commit Rollback and Commit


CHANGES TO DATA ARE TEMPORARY SQL>ROLLBACK;
DURING YOUR SQLPLUS SESSION Rollback complete.
REVERSES ALL CHANGES TO DATA MADE
DOES NOT APPLY TO CHANGES IN DURING YOUR SESSION
DATABASE STRUCTURE - ALTER... SQL>COMMIT;
• MAKES ALL CHANGES TO THIS POINT
BEFORE LEAVING SQLPLUS, YOU CAN PERMANENT
REVERSE THEM • POINTS AT WHICH COMMIT IS ISSUED,
DEFINE EXTENT OF ROLLBACK
• ROLLBACK REVERSES EVERY CHANGE
APPLIES TO INSERTS, UPDATES, AND DELETES SINCE THE LAST COMMIT
• EXITING SQLPLUS ISSUES A COMMIT

9
01-04-2023

SQL for Retrieving Data from One Table Conceptual Evaluation Strategy
SELECT column_name, column_name, … • Semantics of an SQL query defined in terms of the
FROM table_name
following conceptual evaluation strategy:
• Compute the cross-product of relation-list.
WHERE condition/criteria;
• Discard resulting tuples if they fail qualifications.
• Delete attributes that are not in target-list.
• This statement will retrieve the specified field values for all rows in the specified • If DISTINCT is specified, eliminate duplicate rows.
table that meet the specified conditions.
• This strategy is probably the least efficient way to
• Every SELECT statement returns a recordset. compute a query! An optimizer will find more efficient
strategies to compute the same answers.

WHERE Conditions More WHERE Conditions


SELECT * FROM COURSE SELECT * FROM CUSTOMER
WHERE COURSE_CODE LIKE ‘MIS%’; WHERE STATE IN (‘OH’,’WV’,’KY’);
USE % TO SUBSTITUTE FOR LIST OF SPECIFIC VALUES TO
ANY STRING LOOK FOR

SELECT * FROM COURSE


WHERE CREDIT HOURS BETWEEN 3 AND 5; SELECT * FROM CUSTOMER
WHERE (CREDIT_LIMIT - BALANCE) <1000;
3 AND 5 ARE INCLUDED
CAN MANIPULATE NUMBER
SELECT * FROM CUSTOMER
VALUES MATHMATICALLY
WHERE BALANCE < CREDIT_LIMIT;
YOU CAN COMPARE TWO
COLUMNS

10
01-04-2023

AND/OR/NOT Conditions More on AND/OR/NOT


SELECT * FROM CUSTOMER SELECT * FROM CUSTOMER
Use parentheses to
WHERE BALANCE >=500 WHERE STATE = ‘OH’
TWO COMPARISONS make complex logic
AND BALANCE<=1000; OR (CREDIT_LIMIT=1000
ON THE SAME COLUMN more understandable.
AND BALANCE <500);
CUST STATE LIMIT BAL
SELECT * FROM CUSTOMER TWO COMPARISONS A OH 1000 600
WHERE STATE = ‘OH’ ON THE DIFFERENT B WV 1000 200
OR CREDIT_LIMIT>1000; COLUMNS C OH 500 300 Who will be selected??
D OH 1000 200
E KY 1300 800
SELECT * FROM CUSTOMER SAME AS F KY 1000 700
WHERE NOT (STATE=‘OH’); STATE<>‘OH’ G MA 200 100
H NB 1000 100

SQL - Other Features SQL - Other Features


• * - All columns in a table • DISTINCT
• Aliases • Arithmetic operators: +, -, *, /
• SELECT EmployeeID, LastName, FirstName, • Comparison operators: =, >, >=, <, <=, <>
BirthDate AS DOB FROM Employee;
• SELECT EmployeeID, LastName, FirstName, FROM • Concatenation operator: ||
Employee AS E;
• Substring comparisons: %, _
• Dot Notation - ambiguous attribute names • BETWEEN
• SELECT Customer.LName, E.Lname
FROM Customer, Employee AS E • AND, OR
WHERE ...

11
01-04-2023

SQL - Other Features SQL for Retrieving Data from Two or


More Tables
• ORDER BY Clause SQL provides two ways to retrieve data from related tables:
• UNION, EXCEPT, INTERSECT • Join - When two or more tables are joined by a common
• IN field.
• Subqueries - When one Select command is nested within
another command.

SQL - Joins DDL and DML


Joins:
• The WHERE clause is used to specify the common field. • Data Definition Language
• For every relationship among the tables in the FROM clause, • Creating tables (we’ll just talk about this)
you need one WHERE condition (2 tables - 1 join, 3 tables - 2
joins…)
• Data Manipulation Language
• Inserting/Updating/Deleting data
• Retrieving data
• Single table queries
SELECT C.Cust_ID, Comp_Name, Country,OrderID • Where
FROM Customer AS C, Order AS O • Joins
WHERE C.Cust_ID = O.Cust_ID • Grouping
AND Country = ‘USA’;

12
01-04-2023

SQL aggregate functions SQL inbuilt functions


• Aggregate functions are used to perform calculations on a set of • Inbuilt functions, also known as scalar functions, are used to perform
values and return a single value. These functions are commonly used operations on individual values within a table or query. These
in SQL queries that involve grouping of data, such as when using the functions can be used in SELECT, WHERE, and ORDER BY clauses of
GROUP BY clause. SQL statements.
• Some common inbuilt functions in SQL are:
• Some common aggregate functions in SQL are: • CONCAT(): concatenates two or more strings.
• COUNT(): returns the number of rows that match a specified condition. • UPPER(): converts a string to uppercase.
• SUM(): returns the sum of all values in a column. • LOWER(): converts a string to lowercase.
• AVG(): returns the average of all values in a column. • TRIM(): removes leading and trailing spaces from a string.
• MIN(): returns the smallest value in a column. • SUBSTRING(): extracts a substring from a string.
• MAX(): returns the largest value in a column. • ROUND(): rounds a numeric value to a specified number of decimal places.

String functions Date time functions


• CONCAT(string1, string2, ...): concatenates two or more strings. • CURRENT_DATE: returns the current date in the database.
• LENGTH(string): returns the length of a string. • CURRENT_TIME: returns the current time in the database.
• LOWER(string): converts a string to lowercase. • CURRENT_TIMESTAMP: returns the current date and time in the database.
• UPPER(string): converts a string to uppercase. • EXTRACT(field FROM datetime): extracts a specific field (year, month, day,
• TRIM([leading|trailing|both] [char] from string): removes hour, minute, second) from a date/time value.
leading/trailing/both specified characters from a string.
• DATEADD(interval, number, datetime): adds a specified interval (year,
• SUBSTR(string, start, length): returns a substring from a string, starting at month, day, hour, minute, second) to a date/time value.
the specified position and of the specified length.
• REPLACE(string, old_substring, new_substring): replaces all occurrences of • DATEDIFF(interval, datetime1, datetime2): returns the difference between
the old substring with the new substring in a string. two date/time values in the specified interval.
• INSTR(string, substring): returns the position of the first occurrence of a • DATEPART(interval, datetime): returns the value of a specific date/time
substring in a string. interval (year, month, day, hour, minute, second).

13
01-04-2023

Questions Query questions on SQL


• What is a primary key in SQL, and why is it important? 1. How do you select all columns from a table in SQL?
• How do you join two or more tables in SQL? 2. How do you select specific columns from a table in SQL?
• What is the difference between a LEFT JOIN and an INNER JOIN? 3. How do you filter data based on a specific condition in SQL?
4. How do you sort data in SQL?
• How do you create a new table in SQL?
5. How do you limit the number of rows returned in a SQL query?
• How do you insert new data into a table in SQL? 6. How do you use the LIKE operator to filter data based on a pattern match in SQL?
• How do you update existing data in a table in SQL? 7. How do you use the IN operator to filter data based on a set of values in SQL?
• How do you delete data from a table in SQL? 8. How do you use the BETWEEN operator to filter data based on a range of values in
• How do you use the GROUP BY clause to group data in SQL? SQL?
• How do you use the HAVING clause to filter data in SQL? 9. How do you use the DISTINCT keyword to remove duplicates from a SQL query?
10. How do you use the GROUP BY clause to group data based on one or more columns in
• How do you use the ORDER BY clause to sort data in SQL? SQL?

1 2
• SELECT * FROM table_name; • SELECT column1, column2, column3 FROM table_name;

14
01-04-2023

3 4
• SELECT * FROM table_name WHERE column1 = 'value'; • SELECT * FROM table_name ORDER BY column1 DESC;

5 6: To use the LIKE operator to filter data based on


a pattern match in SQL, you can use the following
• SELECT * FROM table_name LIMIT 10; syntax:
• SELECT * FROM table_name WHERE column1 LIKE '%pattern%';

15
01-04-2023

7 8
• SELECT * FROM table_name WHERE column1 IN ('value1', 'value2', • SELECT * FROM table_name WHERE column1 BETWEEN value1 AND
'value3'); value2;

• This will select all rows from the specified table where column1 is • This will select all rows from the specified table where column1 is
equal to any of the specified values. between the specified values.

9 10
• SELECT DISTINCT column1 FROM table_name; • SELECT column1, COUNT(*) FROM table_name GROUP BY column1;

16
01-04-2023

Query questions on SQL


1. How do you join two or more tables in SQL? • How do you join two or more tables in SQL?
2. How do you perform a left or right join in SQL?
3. How do you perform an inner join in SQL?
• To join two or more tables in SQL, you can use the JOIN keyword
4. How do you perform a full outer join in SQL?
followed by the table name and the ON keyword to specify the
5. How do you use the HAVING clause in SQL? columns that are used to join the tables. For example:
6. How do you use the SUM() function to calculate a total in SQL? SELECT *
7. How do you use the AVG() function to calculate an average in SQL? FROM table1
8. How do you use the MAX() and MIN() functions to find the maximum and
minimum values in SQL? JOIN table2
9. How do you use the COUNT() function to count the number of rows in a table ON table1.id = table2.id;
in SQL?
10. How do you use subqueries in SQL?

• How do you perform a left or right join in SQL? • How do you perform an inner join in SQL?
• To perform a left or right join in SQL, you can use the LEFT JOIN or • To perform an inner join in SQL, you can use the INNER JOIN
RIGHT JOIN keywords instead of JOIN. For example: keyword. For example:
SELECT * SELECT *
FROM table1 FROM table1
LEFT JOIN table2 INNER JOIN table2
ON table1.id = table2.id; ON table1.id = table2.id;

17
01-04-2023

• How do you use the HAVING clause in SQL? • How do you use the SUM() function to calculate a total in SQL?
• The HAVING clause is used to filter the results of a GROUP BY clause • The SUM() function is used to calculate the sum of a column. For
based on a condition. For example: example:

SELECT column1, COUNT(*) SELECT SUM(column1)


FROM table1 FROM table1;
GROUP BY column1
HAVING COUNT(*) > 5;

• How do you use the MAX() and MIN() functions to find the maximum • How do you use the COUNT() function to count the number of rows in
and minimum values in SQL? a table in SQL?
• The MAX() and MIN() functions are used to find the maximum and • The COUNT() function is used to count the number of rows in a table.
minimum values of a column. For example: For example:
SELECT COUNT(*)
SELECT MAX(column1), MIN(column1) FROM table1;
FROM table1;

18
01-04-2023

• How do you use subqueries in SQL? 1. Write a query to select all columns from a table named "customers".
2. Write a query to select the columns "name" and "age" from a table named
• Subqueries are used to retrieve data from a table based on the results "students".
of another query. For example: 3. Write a query to select all rows from a table named "orders" where the column
"status" is equal to "shipped".
SELECT column1 4. Write a query to select all rows from a table named "employees" and order
FROM table1 them by the column "hire_date" in descending order.
5. Write a query to select the top 10 rows from a table named "products" and
WHERE column1 IN (SELECT column1 FROM table2 WHERE column2 = order them by the column "price" in ascending order.
'value'); 6. Write a query to select all rows from a table named "customers" where the
column "email" contains the string "gmail.com".
7. Write a query to select all rows from a table named "orders" where the column
"status" is either "shipped" or "delivered".

8. Write a query to select all rows from a table named "employees" 11. Write a query to retrieve the names of all the employees from a table
named "employees" whose names start with the letter 'J'.
where the column "salary" is between 50000 and 100000.
12. Write a query to retrieve the names and prices of all the products from a
9. Write a query to select all distinct values from a column named table named "products" whose prices are between 50 and 100.
"category" in a table named "products". 13. Write a query to retrieve the number of orders for each customer from a
table named "orders" grouped by the "customer_id" column.
10. Write a query to select the total sales for each product in a table 14. Write a query to retrieve the names and total sales of all the products
named "sales", grouping by the column "product_id". from a table named "sales" grouped by the "product_id" column.
15. Write a query to retrieve the names and birth dates of all the customers
from a table named "customers" whose birth dates are in the year 1990.
16. Write a query to retrieve the names and hire dates of all the employees
from a table named "employees" who were hired in the year 2018.

19
01-04-2023

1 How do you use the EXISTS keyword in SQL?


SQL queries
1. How do you use the EXISTS keyword in SQL? • The EXISTS keyword is used to check if a subquery returns any rows. It can be
2. How do you use the UNION operator to combine two or more SELECT statements in used in a WHERE clause to filter rows based on the result of a subquery. For
SQL? example, to check if there are any orders with a certain product ID:
3. How do you use the JOIN ON clause to specify a condition for a join in SQL?
4. How do you use the CASE statement in SQL? SELECT *
5. How do you use the GROUP_CONCAT() function to concatenate rows into a single FROM orders
string in SQL?
WHERE EXISTS (
6. How do you use the COALESCE() function in SQL?
SELECT *
7. How do you use the DATEADD() function to add or subtract time from a date in SQL?
FROM order_details
8. How do you use the CAST() function to convert data types in SQL?
WHERE orders.order_id = order_details.order_id
9. How do you use the RANK() function to rank rows in a result set in SQL?
10. How do you use the ROW_NUMBER() function to assign a unique number to each row AND order_details.product_id = '123'
in a result set in SQL? );

2. How do you use the UNION operator to combine two or more SELECT 3. How do you use the JOIN ON clause to specify a condition for a join
statements in SQL? in SQL?
The UNION operator is used to combine the results of two or more SELECT
statements into a single result set. The columns in each SELECT statement
must match in number and data type. For example, to combine the results of • The JOIN ON clause is used to specify a condition for joining two
two SELECT statements: tables together. It is used in conjunction with the JOIN keyword. For
example, to join two tables on a common column:
SELECT column1, column2 SELECT *
FROM table1
FROM table1
UNION
SELECT column1, column2 JOIN table2
FROM table2; ON table1.column1 = table2.column1;

20
01-04-2023

4. How do you use the CASE statement in SQL? 5 How do you use the GROUP_CONCAT() function to concatenate rows
The CASE statement is used to conditionally return a value based on one or more into a single string in SQL?
conditions. It can be used in the SELECT, WHERE, and ORDER BY clauses. For
example, to return a different value based on the value of a column: The GROUP_CONCAT() function is used to concatenate multiple rows
SELECT column1, into a single string. It is often used with the GROUP BY clause. For
CASE example, to concatenate the values of a column for each group:
WHEN column2 = 'value1' THEN 'Result1' SELECT column1, GROUP_CONCAT(column2)
WHEN column2 = 'value2' THEN 'Result2' FROM table1
ELSE 'Other'
GROUP BY column1;
END AS Result
FROM table1;

6. How do you use the COALESCE() function in SQL? 7. How do you use the DATEADD() function to add or subtract time
• The COALESCE() function is used to return the first non-null value in a from a date in SQL?
list of values. It can be used to handle null values in a query. For The DATEADD() function is used to add or subtract a specified interval
example, to return a default value if a column is null: of time from a date. It takes three arguments: the interval to
SELECT COALESCE(column1, 'default') add/subtract, the number of intervals, and the date to modify. For
example, to add 7 days to a date:
FROM table1;

SELECT DATEADD(day, 7, '2022-01-01');

21
01-04-2023

8. How do you use the CAST() function to convert data types in SQL? 9. How do you use the RANK() function to rank rows in a result set in
The CAST() function is used to convert one data type to another. It SQL?
takes two arguments: the value to convert, and the data type to • The RANK() function is used to assign a rank to each row in a result
convert to. For example, to convert a string to an integer: set based on a specified criteria. The rank of a row is determined by
its position in the result set when ordered by the criteria specified in
the function.
• To use the RANK() function in SQL, you need to include it in your
SELECT CAST('123' AS int); SELECT statement and specify an ORDER BY clause to determine the
order in which the rows should be ranked. Here's an example:

SELECT RANK() OVER (ORDER BY column_name DESC) AS rank_number, * 10. How do you use the ROW_NUMBER() function to assign a unique
FROM table_name; number to each row in a result set in SQL?
• In this example, the RANK() function is used to assign a rank to each row in
the result set, and the ORDER BY clause specifies the column that the rows The ROW_NUMBER() function is used to assign a unique number to
should be ordered by. The "DESC" keyword is used to order the rows in each row in a result set in SQL. This function is very useful for ranking,
descending order. pagination, and other operations that require a unique identifier for
• The result set will include a new column called "rank_number" that each row.
contains the rank assigned to each row. Rows with the same value for the
ranking criteria will receive the same rank, and the next rank will be To use the ROW_NUMBER() function, you need to include it in your
skipped. For example, if two rows have the same value for the ranking SELECT statement and specify an ORDER BY clause to determine the
criteria and are ranked 1 and 2, the next rank assigned will be 3. order in which the rows should be numbered. Here's an example:
• Note that the RANK() function is available in most SQL databases, but the SELECT ROW_NUMBER() OVER (ORDER BY column_name) AS row_number, *
syntax may vary slightly depending on the database you are using.
FROM table_name;

22
01-04-2023

Constraints
The following constraints are commonly used in SQL:
•NOT NULL - Ensures that a column cannot have a NULL value
•UNIQUE - Ensures that all values in a column are different
•PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
•FOREIGN KEY - Prevents actions that would destroy links between
tables
•CHECK - Ensures that the values in a column satisfies a specific
condition
•DEFAULT - Sets a default value for a column if no value is
specified
•CREATE INDEX - Used to create and retrieve data from the
database very quickly

23

You might also like