SQL | SELECT Query
The SELECT Statement in SQL is used to retrieve or fetch data from a database.
We can fetch either the entire table or according to some specified rules. The data returned is stored in a result table. This result table is also called the result set. With the SELECT clause of a SELECT command statement, we specify the columns that we want to be displayed in the query result and, optionally, which column headings we prefer to see above the result table.
The select clause is the first clause and is one of the last clauses of the select statement that the database server evaluates. The reason for this is that before we can determine what to include in the final result set, we need to know all of the possible columns that could be included in the final result set.
CREATE TABLE Customer( CustomerID INT PRIMARY KEY, CustomerName VARCHAR(50), LastName VARCHAR(50), Country VARCHAR(50), Age int(2), Phone int(10) ); -- Insert some sample data into the Customers table INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age, Phone) VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'), (2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'), (3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'), (4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'), (5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain','22','xxxxxxxxxx');
To fetch any column in the table.
SELECT column1,column2 FROM table_name
column1 , column2: names of the fields of the table
table_name: from where we want to apply query
This query will return all the rows in the table with fields column1 and column2.
SELECT Statement in SQL
To fetch the entire table or all the fields in the table:
SELECT * FROM table_name;
— asterisks represent all attributes of the table
Query to fetch the fields CustomerName, LastName from the table Customer:
SELECT CustomerName, LastName FROM Customer;
To fetch all the fields from the table Customer:
SELECT * FROM Customer;
SELECT Statement with WHERE Clause
Suppose we want to see table values with specific conditions then Where Clause is used with select statement.
SELECT CustomerName FROM Customer where Age = '21';
SQL SELECT Statement with GROUP BY Clause
SELECT COUNT (item), Customer_id FROM Orders GROUP BY order_id;
SELECT Statement with HAVING Clause
Consider the following database for Having Clause:
SELECT Department, sum(Salary) as Salary FROM employee GROUP BY department HAVING SUM(Salary) >= 50000;
SELECT Statement with ORDER BY clause in SQL
SELECT * FROM Customer ORDER BY Age DESC;
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Please Login to comment...