SQL (Structured Query Language) is the most widely used language for database management. In this article, we will cover the basic SQL commands and functions with simple examples.
Basic SQL Commands and Their Usage
1. SELECT
Used to select specific columns from a table:
SELECT column1, column2 FROM table_name;
SELECT * FROM table_name; -- All columnsExample:
SELECT FirstName FROM Person.Person;
SELECT TOP 10 * FROM Person.Person;2. INSERT
Used to add new data:
INSERT INTO table_name (column1, column2) VALUES (value1, value2);Example:
INSERT INTO employee (employeeId, name) VALUES (1, 'Ahmet');3. UPDATE
Updates an existing record:
UPDATE table_name SET column_name = value WHERE condition;Example:
UPDATE employee SET name = 'Mehmet' WHERE employeeId = 1;4. DELETE
Used to delete records:
DELETE FROM table_name WHERE condition;Example:
DELETE FROM employee WHERE employeeId = 2;5. WHERE
Used to filter queries:
SELECT * FROM table_name WHERE column_name = 'value';Example:
SELECT * FROM employee WHERE gender = 'M';6. ORDER BY
Used to sort results:
SELECT * FROM table_name ORDER BY column_name [ASC|DESC];Example:
SELECT * FROM employee ORDER BY employeeId DESC;7. LIKE
Used to match a specific pattern:
SELECT * FROM table_name WHERE column_name LIKE 'value%';Example:
SELECT * FROM employee WHERE name LIKE 'A%';SQL Functions
1. COUNT
Returns the number of records:
SELECT COUNT(*) FROM table_name;2. SUM
Calculates the sum of numbers:
SELECT SUM(column_name) FROM table_name;3. AVG
Calculates the average:
SELECT AVG(column_name) FROM table_name;4. MAX and MIN
Returns maximum and minimum values:
SELECT MAX(column_name) FROM table_name;
SELECT MIN(column_name) FROM table_name;5. DISTINCT
Shows repeated values only once:
SELECT DISTINCT column_name FROM table_name;6. BETWEEN
Selects values within a specific range:
SELECT * FROM table_name WHERE column_name BETWEEN value1 AND value2;With these basics, you can make a strong start with SQL. Remember to practice regularly for more commands and details!