SQL – Filtering, Sorting, and Data Manipulation

Today's lesson builds on your SQL foundation by focusing on data manipulation. You'll learn how to filter and sort data using operators like ORDER BY, AND, and OR, and you'll master the essential statements: INSERT, UPDATE, and DELETE, which are fundamental for modifying data within your databases.

Learning Objectives

  • Understand and apply the ORDER BY clause for sorting data.
  • Use the AND and OR operators to filter data based on multiple conditions.
  • Write INSERT statements to add new data to tables.
  • Utilize UPDATE and DELETE statements to modify and remove existing data.

Text-to-Speech

Listen to the lesson content

Lesson Content

Sorting Data with ORDER BY

The ORDER BY clause allows you to sort the results of a query. By default, it sorts in ascending order (A-Z, 0-9). You can specify descending order using DESC.

Example:
Assume we have a table called Customers with columns CustomerID, Name, and City.

SELECT * FROM Customers ORDER BY Name; -- Sorts customers alphabetically by name (ascending)
SELECT * FROM Customers ORDER BY City DESC; -- Sorts customers by city in descending order

Filtering Data with AND and OR

The WHERE clause is used with AND and OR to filter results based on multiple conditions. AND requires all conditions to be true, while OR requires at least one condition to be true.

Example:
SELECT * FROM Customers WHERE City = 'London' AND Country = 'UK'; -- Selects customers from London AND the UK.
SELECT * FROM Customers WHERE City = 'London' OR City = 'Paris'; -- Selects customers from London OR Paris.

Inserting Data with INSERT

The INSERT INTO statement adds new rows of data into a table. You specify the table name and the columns you want to populate, along with the corresponding values.

Example:
INSERT INTO Customers (Name, City, Country) VALUES ('Alice Smith', 'New York', 'USA'); -- Inserts a new customer.

Updating Data with UPDATE

The UPDATE statement modifies existing data in a table. You specify the table, the column(s) to update, and the new value(s), often using a WHERE clause to target specific rows.

Example:
UPDATE Customers SET City = 'Berlin' WHERE CustomerID = 123; -- Updates the city of the customer with ID 123 to Berlin.
UPDATE Customers SET Country = 'Germany' WHERE City = 'Berlin'; -- Updates the country of customers living in Berlin.

Deleting Data with DELETE

The DELETE FROM statement removes rows from a table. The WHERE clause is crucial to specify which rows to delete. Without a WHERE clause, all rows in the table will be deleted!

Example:
DELETE FROM Customers WHERE CustomerID = 456; -- Deletes the customer with ID 456.
DELETE FROM Customers WHERE Country = 'Spain'; -- Deletes all customers from Spain.

Progress
0%