Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 28

SQL FUNDAMENTALS

AND QUERY
PROCESSING
• SQL IS A PROGRAMMING LANGUAGE USED FOR MANAGING AND
MANIPULATING DATABASES.IT ALLOWS
STORING,RETRIEVING,UPDATING AND DEETING DATA FROM A
DATABASE.
• SQL commands can be divided into two main sub-languages.
The Data Definition Language contains the commands used to
create and destroy databases and database objects.
• After the database structure is defined with DDL, database
administrators and users can use the Data Manipulation
Language to insert, retrieve and modify the data contained
within it.
DATA DEFINITION LANGUAGE(DDL)

• IS USED TO DEFINE AND MANAGE THE STRUCTURE OF THE DATABASE.


• These commands are primarily used by database administrators
during the setup and removal phases of a database project.
• EXAMPLES:
• CREATE TABLE:CREATES A NEW TABLE IN THE DATABASE
• ALTER TABLE:MODIFIES THE STRUCTURE OF AN EXISTING TABLE
• DROP TABLE:DELETES A TABLE FROM THE DATABASE
Create

• The create command establishes databases, tables, or queries on your platform. For example, the command:

CREATE DATABASE employees;

• creates an empty database named employees on your DBMS. After creating the database, the next step is to
create tables that contain data. Another variant of the create command accomplishes this purpose. The
command:

• CREATE TABLE personal_info (first_name char(20) not null, last_name char(20) not null, employee_id int not
null);

• establishes a table titled personal_info in the current database. In the example, the table contains three
attributes: first_name, last_name, and employee_id along with some additional information
Alter

• After you've created a table within a database, modify its definition through
the alter command, which changes to the structure of a table without
deleting and recreating it. Take a look at the following command:

ALTER TABLE personal_info ADD salary money null;

• This example adds a new attribute to the personal_info table—an


employee's salary. The money argument specifies that an employee's salary
stores using a dollars and cents format. Finally, the null keyword tells the
database that it's OK for this field to contain no value for any given
employee.
Drop

• The final command of the Data Definition Language, drop, removes entire database objects from
our DBMS. For example, to permanently remove the personal_info table that we created, use
the following command:

DROP TABLE personal_info;

• Similarly, the command below would be used to remove the entire employee database:

• DROP DATABASE employees;

• Use this command with care. The drop command removes entire data structures from your
database. If you want to remove individual records, use the delete command of the Data
Manipulation Language.
Data Manipulation Language Commands

• DATA MANIPULATION LANGUAGES(DML)


• ARE USED TO MANIPULATE DATA WITHIN TABLES
• EXAMPLES:
• INSERT INTO:INSERTS NEW RECORDS INTO A TABLE
• EG
• INSERT INTO CUSTOMERS(CUSTOMER-NAME,EMAIL) VALUES(‘DZOKERAI MABHUNU’,MABHUNU@GMAIL.COM);

• UPDATE:MODIFIES EXISTING RECORDS IN A TABE


• EG
• UPDATE CUSTOMERS
• SET CUSTOMERNAME=’TRABABLAS ‘ WHERE CUSTOMER ID=1;
• DELETES FROM: DELETES RECORDS FROM A TABLE
• EG
• DELETE FROM CUSTOMERS
• WHERE CUSTOMER ID=1;
Insert

• The insert command adds records to an existing table. Returning to the


personal_info example from the previous section, imagine that a HR
department needs to add a new employee to its database. Use a command
similar to this one:

• INSERT INTO personal_info


• values('bart','simpson',12345,$45000);

• Note that there are four values specified for the record. These correspond to
the table attributes in the order they were defined: first_name, last_name,
employee_id and salary.
Select

• The select command is the most commonly used command in SQL. It


retrieves specific information from an operational database. Take a look
at a few examples, again using the personal_info table from the
employee database.

• The command shown below retrieves all the information contained


within the personal_info table. The asterisk is a wildcard character in SQL.

• SELECT *
• FROM personal_info;
• Alternatively, limit the attributes that are retrieved from the database by specifying what
gets selected. For example, the Human Resources department may require a list of the last
names of all employees in the company. The following SQL command would retrieve only
that information:

• SELECT last_name
• FROM personal_info;

• The where clause limits the records that are retrieved to those that meet specified criteria.
The CEO might be interested in reviewing the personnel records of all highly paid
employees. The following command retrieves all of the data contained within
personal_info for records that have a salary value greater than $50,000:

• SELECT *
• FROM personal_info
• WHERE salary > $50000;
Update

• The update command modifies the information contained within a table, either in bulk or individually.
Assume the company gives all employees a 3 percent cost-of-living increase in their salary annually.
The following SQL command applies this bump to all the employees stored in the database:

• UPDATE personal_info
• SET salary = salary * 1.03;

• When the new employee Bart Simpson demonstrates performance above and beyond the call of duty,
management wishes to recognize his stellar accomplishments with a $5,000 raise. The WHERE clause
singles out Bart for this raise:

• UPDATE personal_info
• SET salary = salary + 5000
• WHERE employee_id = 12345;
Delete

• Finally, the delete command. The syntax of this command is similar to that of the other DML
commands. The DELETE command, with a where clause, remove a record from a table:

• DELETE FROM personal_info


• WHERE employee_id = 12345;

• DML supports aggregate fields, too. In a select statement, mathematical operators like sum
and count summarize data within a query. For example, the query:

• select count(*) from personal_info;

• counts the number of records in the table.


MERGE
• The MERGE statement in SQL can be used to perform operations like INSERT, DELETE, and UPDATE, all within the same SQL query.
In simple terms, the MERGE statement combines the separate INSERT, UPDATE, and DELETE statements into a single SQL
query.Merge in SQL merges two tables, a TARGET table, and a SOURCE table, to form a single TARGET table where entries are
INSERTED, DELETED, or UPDATED based on their presence or absence on the source table.
Suppose you have two tables, source and target, and you want to update the target table based on the source table values that
match the target table. You have three cases:-

1. The source table has some rows that do not exist in the target table; in that case, you need to insert those rows in the target
table from the source table.
2. The target table contains some rows that do not exist in the source table and that need to be deleted from the target table.
3. The source table has some rows with the same keys as the rows in the target table. However, these rows have different values
in the non-key columns. In this case, you need to update the rows in the target table with the values coming from the source
table.
And to perform the above three cases, we have to construct three separate SQL queries. Here MERGE statements come in handy as
this can be used within the same SQL query as INSERT, DELETE and UPDATE.

• MERGE in SQL helps in performing the repetitive tasks by a single query, which means that when we want to INSERT, DELETE and
UPDATE data from a table. The MERGE statement comes in handy because It does three operations through a single MERGE
statement.
Syntax
MERGE target_table USING source_table
ON merge_condition
WHEN MATCHED
THEN update_statement
WHEN NOT MATCHED
THEN insert_statement
WHEN NOT MATCHED BY SOURCE
THEN DELETE;
Syntax
MERGE target_table USING source_table
ON merge_condition
WHEN MATCHED
THEN update_statement
WHEN NOT MATCHED
THEN insert_statement
WHEN NOT MATCHED BY SOURCE
THEN DELETE;
example
• Let’s say we have two tables: tbl_A and tbl_B. We want to synchronize them by inserting, updating,
or deleting rows in tbl_A based on differences found in tbl_B. Here’s how you might use MERGE:

MERGE INTO tbl_A AS target


USING tbl_B AS source
ON target.col = source.col
WHEN MATCHED AND target.col2 <> source.col2 THEN
UPDATE SET target.col2 = source.col2
WHEN NOT MATCHED BY TARGET THEN
INSERT (col, col2) VALUES (source.col, source.col2)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
DATA RETRIEVAL LANGUAGE(DRL)

• ARE STATEMENTS USED TO RETRIEVE DATA FROM THE DATABASE


• EG
• SELECT * FROM CUSTOMERS;
• SELECT WITH CONDITIONS
• SELECT * FROM CUSTOMERS WHERE COUNTRY =’USA’;
• An SQL SELECT statement retrieves records from a database table
according to clauses (for example, FROM and WHERE) that specify
criteria. The syntax is:

• SELECT column1, column2 FROM table1, table2 WHERE


column2='value';
In the above SQL statement:

• The SELECT clause specifies one or more columns to be retrieved; to


specify multiple columns, use a comma and a space between column
names. To retrieve all columns, use the wild card * (an asterisk).
• The FROM clause specifies one or more tables to be queried. Use a
comma and space between table names when specifying multiple tables.
• The WHERE clause selects only the rows in which the specified column
contains the specified value. The value is enclosed in single quotes (for
example, WHERE last_name='Vader').
• The semicolon (;) is the statement terminator. Technically, if you're
sending only one statement to the back end, you don't need the
statement terminator; if you're sending more than one, you need it. It's
best practice to include it.
GroupBy Clause
• The GroupBy clause is used to arrange identical data into groups based on one or more
columns. It is particularly useful when you want to perform aggregate functions (like
SUM, AVG, COUNT) on specific groups within a dataset.
• To combine rows together by common column values, the GROUP BY clause is used in
conjunction with the SELECT statement and aggregate functions.

Syntax of GroupBy Clause


• SELECT column1, column2, aggregate_function(column3)

• FROM table

• GROUP BY column1, column2;


Syntax:

• SELECT column_name1, column_name2,...

• FROM table_name

• WHERE condition

• GROUP BY column_name(s);

Code:
• SELECT COUNT(customer_name), country

• FROM customers

• GROUP BY country;
OrderBy Clause
• The OrderBy clause is used to sort the result set of a query in ascending or
descending order based on one or more columns. This ensures that the
retrieved data is presented in a structured and easily interpretable manner.

Syntax of OrderBy Clause


• SELECT column1, column2

• FROM table

• ORDER BY column1 [ASC | DESC], column2 [ASC | DESC];


OrderBy Clause in SQL Example

• SELECT product_name, price

• FROM products

• ORDER BY price DESC;

Order By Where Clause in SQL

• You can combine the OrderBy and Where clauses to filter and sort data simultaneously.

• SELECT product_name, price

• FROM products

• WHERE category = 'Electronics'

• ORDER BY price DESC;


Having Clause
• The Having clause is used in combination with the GroupBy clause to filter the results of
aggregate functions based on specified conditions. It is applied after the data has been
grouped.

Syntax of Having Clause


• SELECT column1, aggregate_function(column2)

• FROM table

• GROUP BY column1

• HAVING aggregate_function(column2) condition;


Having Clause in SQL Example

• SELECT department, AVG(salary) as avg_salary

• FROM employees

• GROUP BY department

• HAVING AVG(salary) > 50000;


QUERY PROCESSING
• ARE STEPS TAKEN BY THE DATABASE ENGINE TO EXECUTE A QUERY

• 1)PARSING:THE DATABASE ENGINE ANALYZES THE SQL QUERY TO ENSURE IT IS SYNTACTICALLY


CORRECT.IT CHECKS FOR PROPER KEY WORDS,TABLE AND COLUMN NAMES AND OVERALLL QUERY
STRUCTURE

• 2)OPTIMIZATION:THE DB ENGINE DETERMINES THE MOST EFFFICIENT WAY TO EXECUTE THE


QUERY.IT CONSIDERS FACTORS LIKE TABLE SIZES,AVAILABE INDEXES AND QUERY COMPLEXITY TO
GENERATE AN OPTIMAL EXECUTION PLAN

• 3)EVALUATION:THE DB ENGINE EXECUTES THE QUERY ACCORDING TO THE OPTIMIZED PLAN


GENERATED IN THE PREVIOUS STEP.IT ACCESSES THE NECESSARY DATA FROM THE TABLES AND
PERFORMS ANY REQUIRED OPERATIONS(FILTERING,SORTING,JOINING) AND RETURNS THE RESULT.
Query processing continuing
• Query processing is when high level query language is converted to
low level query language
Query processing continuing

You might also like