SQL on
Created By: chatGPT
SQL (Structured Query Language) is a domain-specific language used for managing and manipulating relational databases. It allows you to perform operations such as querying data, updating records, and managing database schema. Below are some common SQL commands and examples.
SELECT statement is used to retrieve data from a database. You can specify the columns you want to retrieve as well as the table name.
SELECT column1, column2
FROM table_name;
-- Example
SELECT first_name, last_name
FROM employees;
WHERE clause allows filtering the records based on specific conditions.
SELECT column1, column2
FROM table_name
WHERE condition;
-- Example
SELECT *
FROM employees
WHERE department = 'Sales';
INSERT INTO statement is used to add new records to a table. You can specify the table name and the values for each column.
INSERT INTO table_name (column1, column2)
VALUES (value1, value2);
-- Example
INSERT INTO employees (first_name, last_name)
VALUES ('John', 'Doe');
UPDATE statement is used to modify existing records in a table.
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;
-- Example
UPDATE employees
SET department = 'Marketing'
WHERE last_name = 'Doe';
DELETE statement is used to remove records from a table. Be careful when using this, as it permanently deletes data.
DELETE FROM table_name
WHERE condition;
-- Example
DELETE FROM employees
WHERE last_name = 'Doe';
JOIN operations allow you to combine rows from two or more tables based on a related column. Common joins include INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN.
SELECT columns
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;
-- Example
SELECT employees.first_name, departments.department_name
FROM employees
INNER JOIN departments
ON employees.department_id = departments.id;
GROUP BY statement groups rows that have the same values in specified columns into summary rows, like counting or averaging.
SELECT column1, COUNT(*)
FROM table_name
GROUP BY column1;
-- Example
SELECT department, COUNT(*)
FROM employees
GROUP BY department;
ORDER BY clause sorts the result set in ascending or descending order based on one or more columns.
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC|DESC;
-- Example
SELECT *
FROM employees
ORDER BY last_name ASC;
LIMIT clause is used to specify the number of records to return, allowing for pagination of results.
SELECT column1, column2
FROM table_name
LIMIT number;
-- Example
SELECT *
FROM employees
LIMIT 10;