SQL Session 02 - Manual
SQL Session 02 - Manual
Data Manipulation
Welcome to the SQL Manual for Filtering, Sorting, and updating Data. In this session, we'll
delve deeper into the techniques used to manipulate data within SQL databases effectively.
Objective:
• Understand the WHERE Clause:
• Modify the structure of existing tables using the ALTER TABLE statement
• Update data within these tables using the UPDATE statement. This includes adding new
columns, changing data types, and updating existing records.
The WHERE clause filters rows from a table based on a specified condition, allowing you to
retrieve only the data that meets certain criteria.
Syntax:
Example:
Key Points:
• Conditions in the WHERE clause can include comparisons (=, !=, >, <, >=, <=), logical
operators (AND, OR, NOT), and pattern matching using LIKE.
• Use single quotes for string values and no quotes for numeric values in conditions.
2. ORDER BY Clause:
The ORDER BY clause sorts the result set of a query based on specified columns, either in
ascending or descending order.
Syntax:
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
Example:
Key Points:
• You can specify multiple columns for sorting, with the order of precedence determined
by the sequence of columns in the ORDER BY clause.
• Use ASC for ascending order (default) and DESC for descending order.
3. LIMIT Clause:
The LIMIT clause is used to restrict the number of rows returned by a query, which is
particularly useful when dealing with large datasets.
Syntax:
FROM table_name
LIMIT number_of_rows;
Example:
Key Points:
• The LIMIT clause is not supported by all SQL databases, so check the documentation of
your specific database management system (DBMS) for compatibility.
• LIMIT is often used in combination with ORDER BY to retrieve the top or bottom N
records based on a specified criterion.
4. Modifying and Updating New Tables
You can modify the structure of an existing table using the ALTER TABLE statement and update
the data using the UPDATE statement.
Syntax
Example
Updating Data
Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example
UPDATE employees
SET salary = 80000.00
WHERE employee_id = 1;
A primary key is a field in a table which uniquely identifies each row/record in that table.
Primary keys must contain unique values and cannot contain NULL values.
To create a primary key when creating a table, use the following syntax:
Example
Example
Example
6. Auto-Increments
Introduction
To create an auto-increment field, you can use the AUTO_INCREMENT attribute in MySQL or the
SERIAL data type in PostgreSQL.
MySQL Example
Example
Best Practices
Remember to always end your SQL statements with a semicolon (;) and to use appropriate
whitespace and indentation for readability. Utilize these techniques to efficiently filter, sort,
and update data in your SQL databases. Happy querying!