기본 SQL 명령-알아야 할 데이터베이스 쿼리 및 명령문 목록

SQL은 Structured Query Language를 나타냅니다. SQL 명령은 데이터로 작업, 기능 및 쿼리를 수행하기 위해 데이터베이스와 통신하는 데 사용되는 명령입니다.

SQL 명령을 사용하여 데이터베이스를 검색하고 테이블 생성, 테이블에 데이터 추가, 데이터 수정 및 테이블 삭제와 같은 기타 기능을 수행 할 수 있습니다.

다음은 SQL로 작업 할 경우 알아야 할 기본 SQL 명령 (절이라고도 함) 목록입니다.

SELECT 및 FROM

SELECT쿼리 의 일부는 결과에 표시 할 데이터 열을 결정합니다. 테이블 열이 아닌 데이터를 표시하기 위해 적용 할 수있는 옵션도 있습니다.

보여주는 아래의 예는 세 개의 열은 SELECT에드 FROM은 "학생 '표 계산 한 칼럼. 데이터베이스는 학생의 studentID, FirstName 및 LastName을 저장합니다. First 및 Last name 열을 결합하여 FullName 계산 열을 만들 수 있습니다.

SELECT studentID, FirstName, LastName, FirstName + ' ' + LastName AS FullName FROM student;
+-----------+-------------------+------------+------------------------+ | studentID | FirstName | LastName | FullName | +-----------+-------------------+------------+------------------------+ | 1 | Monique | Davis | Monique Davis | | 2 | Teri | Gutierrez | Teri Gutierrez | | 3 | Spencer | Pautier | Spencer Pautier | | 4 | Louis | Ramsey | Louis Ramsey | | 5 | Alvin | Greene | Alvin Greene | | 6 | Sophie | Freeman | Sophie Freeman | | 7 | Edgar Frank "Ted" | Codd | Edgar Frank "Ted" Codd | | 8 | Donald D. | Chamberlin | Donald D. Chamberlin | | 9 | Raymond F. | Boyce | Raymond F. Boyce | +-----------+-------------------+------------+------------------------+ 9 rows in set (0.00 sec)

테이블 만들기

CREATE TABLE말 그대로 데이터베이스에 테이블을 생성합니다. 테이블의 이름과 테이블에 있어야하는 열을 지정할 수 있습니다.

CREATE TABLE table_name ( column_1 datatype, column_2 datatype, column_3 datatype );

ALTER TABLE

ALTER TABLE테이블의 구조를 변경합니다. 다음은 데이터베이스에 열을 추가하는 방법입니다.

ALTER TABLE table_name ADD column_name datatype;

검사

CHECK제약 컬럼에 배치 될 수있는 값의 범위를 제한하는 데 사용된다.

CHECK단일 열에 대한 제약 조건 을 정의하면 이 열에 대해 특정 값만 허용됩니다. CHECK테이블에 대한 제약 조건 을 정의 하면 행에있는 다른 열의 값을 기반으로 특정 열의 값을 제한 할 수 있습니다.

다음 SQL은 CHECK"Persons"테이블이 생성 될 때 "Age"열에 대한 제약 조건을 생성합니다. CHECK제약 보장하지만은 18 세 미만의 사람을 가질 수있다.

CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, CHECK (Age>=18) );

CHECK제약 조건의 이름을 지정 CHECK하고 여러 열에 대한 제약 조건 을 정의 하려면 다음 SQL 구문을 사용하십시오.

CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, City varchar(255), CONSTRAINT CHK_Person CHECK (Age>=18 AND City="Sandnes") );

어디

(AND ,OR , IN, BETWEEN, 및 LIKE)

WHERE절은 반환되는 행 수를 제한하는 데 사용됩니다.

예를 들어, 첫째 우리는 당신에게 보여줄 것이다 SELECT문과 결과 없이WHERE 문을. 그런 다음 WHERE위의 다섯 가지 한정자를 모두 사용 하는 문을 추가합니다 .

SELECT studentID, FullName, sat_score, rcd_updated FROM student;
+-----------+------------------------+-----------+---------------------+ | studentID | FullName | sat_score | rcd_updated | +-----------+------------------------+-----------+---------------------+ | 1 | Monique Davis | 400 | 2017-08-16 15:34:50 | | 2 | Teri Gutierrez | 800 | 2017-08-16 15:34:50 | | 3 | Spencer Pautier | 1000 | 2017-08-16 15:34:50 | | 4 | Louis Ramsey | 1200 | 2017-08-16 15:34:50 | | 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 | | 6 | Sophie Freeman | 1200 | 2017-08-16 15:34:50 | | 7 | Edgar Frank "Ted" Codd | 2400 | 2017-08-16 15:35:33 | | 8 | Donald D. Chamberlin | 2400 | 2017-08-16 15:35:33 | | 9 | Raymond F. Boyce | 2400 | 2017-08-16 15:35:33 | +-----------+------------------------+-----------+---------------------+ 9 rows in set (0.00 sec)

이제 SELECT쿼리를 반복 하되 WHERE명령문을 사용하여 반환되는 행을 제한합니다 .

STUDENT studentID, FullName, sat_score, recordUpdated FROM student WHERE (studentID BETWEEN 1 AND 5 OR studentID = 8) AND sat_score NOT IN (1000, 1400);
+-----------+----------------------+-----------+---------------------+ | studentID | FullName | sat_score | rcd_updated | +-----------+----------------------+-----------+---------------------+ | 1 | Monique Davis | 400 | 2017-08-16 15:34:50 | | 2 | Teri Gutierrez | 800 | 2017-08-16 15:34:50 | | 4 | Louis Ramsey | 1200 | 2017-08-16 15:34:50 | | 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 | | 8 | Donald D. Chamberlin | 2400 | 2017-08-16 15:35:33 | +-----------+----------------------+-----------+---------------------+ 5 rows in set (0.00 sec)

최신 정보

테이블의 레코드를 업데이트하려면 UPDATE문 을 사용합니다 .

사용 WHERE하여 업데이트 할 레코드를 지정하는 조건을. 한 번에 하나 이상의 열을 업데이트 할 수 있습니다. 구문은 다음과 같습니다.

UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;

다음은 Id 4로 레코드 이름을 업데이트하는 예입니다.

UPDATE Person SET Name = “Elton John” WHERE Id = 4;

다른 테이블의 값을 사용하여 테이블의 열을 업데이트 할 수도 있습니다. 이 JOIN절을 사용하여 여러 테이블에서 데이터를 가져옵니다. 구문은 다음과 같습니다.

UPDATE table_name1 SET table_name1.column1 = table_name2.columnA table_name1.column2 = table_name2.columnB FROM table_name1 JOIN table_name2 ON table_name1.ForeignKey = table_name2.Key

다음은 모든 레코드의 관리자를 업데이트하는 예입니다.

UPDATE Person SET Person.Manager = Department.Manager FROM Person JOIN Department ON Person.DepartmentID = Department.ID

그룹화

GROUP BY 행을 결합하고 데이터를 집계 할 수 있습니다.

다음은 구문입니다 GROUP BY.

SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name;

HAVING

HAVINGGROUP BY사용자가 볼 수있는 제한된 레코드 집합을 얻을 수 있도록 절로 집계 된 데이터를 필터링 할 수 있습니다.

다음은 구문입니다 HAVING.

SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name HAVING COUNT(*) > value;

AVG ()

"Average"는 SQL 문이 반환 한 행 집합에서 숫자 열의 평균을 계산하는 데 사용됩니다.

함수를 사용하기위한 구문은 다음과 같습니다.

SELECT groupingField, AVG(num_field) FROM table1 GROUP BY groupingField

다음은 student 테이블을 사용한 예입니다.

SELECT studentID, FullName, AVG(sat_score) FROM student GROUP BY studentID, FullName;

같이

AS 별칭을 사용하여 열 또는 테이블의 이름을 바꿀 수 있습니다.

SELECT user_only_num1 AS AgeOfServer, (user_only_num1 - warranty_period) AS NonWarrantyPeriod FROM server_table

결과는 아래와 같습니다.

+-------------+------------------------+ | AgeOfServer | NonWarrantyPeriod | +-------------+------------------------+ | 36 | 24 | | 24 | 12 | | 61 | 49 | | 12 | 0 | | 6 | -6 | | 0 | -12 | | 36 | 24 | | 36 | 24 | | 24 | 12 | +-------------+------------------------+

또한 AS를 사용하여 테이블에 이름을 할당하여 조인에서보다 쉽게 ​​참조 할 수 있습니다.

SELECT ord.product, ord.ord_number, ord.price, cust.cust_name, cust.cust_number FROM customer_table AS cust JOIN order_table AS ord ON cust.cust_number = ord.cust_number

결과는 아래와 같습니다.

+-------------+------------+-----------+-----------------+--------------+ | product | ord_number | price | cust_name | cust_number | +-------------+------------+-----------+-----------------+--------------+ | RAM | 12345 | 124 | John Smith | 20 | | CPU | 12346 | 212 | Mia X | 22 | | USB | 12347 | 49 | Elise Beth | 21 | | Cable | 12348 | 0 | Paul Fort | 19 | | Mouse | 12349 | 66 | Nats Back | 15 | | Laptop | 12350 | 612 | Mel S | 36 | | Keyboard| 12351 | 24 | George Z | 95 | | Keyboard| 12352 | 24 | Ally B | 55 | | Air | 12353 | 12 | Maria Trust | 11 | +-------------+------------+-----------+-----------------+--------------+

주문

ORDER BY gives us a way to sort the result set by one or more of the items in the SELECT section. Here is an SQL sorting the students by FullName in descending order. The default sort order is ascending (ASC) but to sort in the opposite order (descending) you use DESC.

SELECT studentID, FullName, sat_score FROM student ORDER BY FullName DESC;

COUNT

COUNT will count the number of rows and return that count as a column in the result set.

Here are examples of what you would use COUNT for:

  • Counting all rows in a table (no group by required)
  • Counting the totals of subsets of data (requires a Group By section of the statement)

This SQL statement provides a count of all rows. Note that you can give the resulting COUNT column a name using “AS”.

SELECT count(*) AS studentCount FROM student; 

DELETE

DELETE is used to delete a record in a table.

Be careful. You can delete all records of the table or just a few. Use the WHERE condition to specify which records you want to delete. The syntax is:

DELETE FROM table_name WHERE condition;

Here is an example deleting from the table Person the record with Id 3:

DELETE FROM Person WHERE Id = 3;

INNER JOIN

JOIN, also called Inner Join, selects records that have matching values in two tables.

SELECT * FROM A x JOIN B y ON y.aId = x.Id

LEFT JOIN

A LEFT JOIN returns all rows from the left table, and the matched rows from the right table. Rows in the left table will be returned even if there was no match in the right table. The rows from the left table with no match in the right table will have null for right table values.

SELECT * FROM A x LEFT JOIN B y ON y.aId = x.Id

RIGHT JOIN

A RIGHT JOIN returns all rows from the right table, and the matched rows from the left table. Opposite of a left join, this will return all rows from the right table even where there is no match in the left table. Rows in the right table that have no match in the left table will have null values for left table columns.

SELECT * FROM A x RIGHT JOIN B y ON y.aId = x.Id 

FULL OUTER JOIN

A FULL OUTER JOIN returns all rows for which there is a match in either of the tables. So if there are rows in the left table that do not have matches in the right table, those will be included. Also, if there are rows in the right table that do not have matches in the left table, those will be included.

SELECT Customers.CustomerName, Orders.OrderID FROM Customers FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName

INSERT

INSERT is a way to insert data into a table.

INSERT INTO table_name (column_1, column_2, column_3) VALUES (value_1, 'value_2', value_3);

LIKE

LIKE  is used in a WHERE or HAVING (as part of the GROUP BY) to limit the selected rows to the items when a column has a certain pattern of characters contained in it.

This SQL will select students that have FullName starting with “Monique” or ending with “Greene”.

SELECT studentID, FullName, sat_score, rcd_updated FROM student WHERE FullName LIKE 'Monique%' OR FullName LIKE '%Greene'; 
+-----------+---------------+-----------+---------------------+ | studentID | FullName | sat_score | rcd_updated | +-----------+---------------+-----------+---------------------+ | 1 | Monique Davis | 400 | 2017-08-16 15:34:50 | | 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 | +-----------+---------------+-----------+---------------------+ 2 rows in set (0.00 sec)

You can place NOT before LIKE to exclude the rows with the string pattern instead of selecting them. This SQL excludes records that contain “cer Pau” and “Ted” in the FullName column.

SELECT studentID, FullName, sat_score, rcd_updated FROM student WHERE FullName NOT LIKE '%cer Pau%' AND FullName NOT LIKE '%"Ted"%';
+-----------+----------------------+-----------+---------------------+ | studentID | FullName | sat_score | rcd_updated | +-----------+----------------------+-----------+---------------------+ | 1 | Monique Davis | 400 | 2017-08-16 15:34:50 | | 2 | Teri Gutierrez | 800 | 2017-08-16 15:34:50 | | 4 | Louis Ramsey | 1200 | 2017-08-16 15:34:50 | | 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 | | 6 | Sophie Freeman | 1200 | 2017-08-16 15:34:50 | | 8 | Donald D. Chamberlin | 2400 | 2017-08-16 15:35:33 | | 9 | Raymond F. Boyce | 2400 | 2017-08-16 15:35:33 | +-----------+----------------------+-----------+---------------------+ 7 rows in set (0.00 sec)