WHAT IS A QUERY IN SQL?
A query is a request for data or information from a database table or combination of tables. This data may be generated as results returned by Structured Query Language (SQL) or as pictorials, graphs or complex results, e.g., trend analyses from data-mining tools.
One of several different query languages may be used to perform a range of simple to complex database queries. SQL, the most well-known and widely-used query language, is familiar to most database administrators (DBAs).
For a machine to understand a request for information in the first place, the query must be written according to a code known as query language. For example, if you go to a bank and ask “Can I have an espresso?” the teller might be puzzled.
SQL represents one of the standard languages used for database management purposes, while MySQL, instead, is the software using that specific language. Although SQL is a fairly universal query language, other commonly used ones include DMX, Datalog and AQL.
The query database feature is equal in necessity to data storage capability. Thus, a number of query languages have been developed for different database engines and purposes, but SQL is by far the most ubiquitous and well-known. In fact, rookie database administrators often are surprised when they learn about the existence of other query languages.
Query languages generate different data types according to function. For example, SQL returns data in neat rows and columns and is very similar to Microsoft Excel in appearance.
Other query languages generate data as graphs or other complex data manipulations, e.g., data mining, which is the deep analysis of information that uncovers previously-unknown trends and relationships between distinct or divergent data. For example, a SQL manufacturing company query may reveal that monthly sales peak in June and July, or that female sales representatives continually outperform male counterparts during holiday months.
A database can be queried by less experienced users who are not trained in a specific query language. Using a pre-defined query written in a special query language to make a request isn’t the only way to request information from a database.
WHAT IS SQL SERVER?
Microsoft SQL Server is a relational database management system developed by Microsoft. As a database server, it is a software product with the primary function of storing and retrieving data as requested by other software applications—which may run either on the same computer or on another computer across a network
HOW DOES A QUERY WORK?
How a query works in SQL?
SQL Query mainly works in three phases . 1) Row filtering – Phase 1: Row filtering – phase 1 are done by FROM, WHERE , GROUP BY , HAVING clause. 2) Column filtering: Columns are filtered by SELECT clause. 3) Row filtering – Phase 2: Row filtering – phase 2 are done by DISTINCT , ORDER BY , LIMIT clause.
How does query work in database?
A query works the same way. It gives meaning to the code used in any query language. Be it SQL or anything else, both the user and the database can always exchange information as long as they ‘speak’ the same language. The software, by default, has lists of parameters on their menu
Types of SQL
Here are five types of widely used SQL queries.
- Data Definition Language (DDL)
- Data Manipulation Language (DML)
- Data Control Language(DCL)
- Transaction Control Language(TCL)
- Data Query Language (DQL)
Let see each of them in detail:
What is DDL?
Data Definition Language helps you to define the database structure or schema. Let’s learn about DDL commands with syntax.
Five types of DDL commands in SQL are:
CREATE
CREATE statements is used to define the database structure schema:
Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
For example:
Create database university; Create table students; Create view for_students;
DROP
Drops commands remove tables and databases from RDBMS.
Syntax
DROP TABLE ;
For example:
Drop object_type object_name; Drop database university; Drop table student;
ALTER
Alters command allows you to alter the structure of the database.
Syntax:
To add a new column in the table
ALTER TABLE table_name ADD column_name COLUMN-definition;
To modify an existing column in the table:
ALTER TABLE MODIFY(COLUMN DEFINITION....);
For example:
Alter table guru99 add subject varchar;
TRUNCATE:
This command used to delete all the rows from the table and free the space containing the table.
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE table students;
What is Data Manipulation Language?
Data Manipulation Language (DML) allows you to modify the database instance by inserting, modifying, and deleting its data. It is responsible for performing all types of data modification in a database.
There are three basic constructs which allow database program and user to enter data and information are:
Here are some important DML commands in SQL:
- INSERT
- UPDATE
- DELETE
INSERT:
This is a statement is a SQL query. This command is used to insert data into the row of a table.
Syntax:
INSERT INTO TABLE_NAME (col1, col2, col3,.... col N) VALUES (value1, value2, value3, .... valueN); Or INSERT INTO TABLE_NAME VALUES (value1, value2, value3, .... valueN);
For example:
INSERT INTO students (RollNo, FIrstName, LastName) VALUES ('60', 'Tom', Erichsen');
UPDATE:
This command is used to update or modify the value of a column in the table.
Syntax:
UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITION]
For example:
UPDATE students SET FirstName = 'Jhon', LastName= 'Wick' WHERE StudID = 3;
DELETE:
This command is used to remove one or more rows from a table.
Syntax:
DELETE FROM table_name [WHERE condition];
For example:
DELETE FROM students WHERE FirstName = 'Jhon';
What is DCL?
DCL (Data Control Language) includes commands like GRANT and REVOKE, which are useful to give “rights & permissions.” Other permission controls parameters of the database system.
Examples of DCL commands:
Commands that come under DCL:
- Grant
- Revoke
Grant:
This command is use to give user access privileges to a database.
Syntax:
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
For example:
GRANT SELECT ON Users TO'Tom'@'localhost;
Revoke:
It is useful to back permissions from the user.
Syntax:
REVOKE privilege_nameON object_nameFROM {user_name |PUBLIC |role_name}
For example:
REVOKE SELECT, UPDATE ON student FROM BCA, MCA;
What is TCL?
Transaction control language or TCL commands deal with the transaction within the database.https://512407338df7b501d08d199e3f6a225b.safeframe.googlesyndication.com/safeframe/1-0-38/html/container.html
Commit
This command is used to save all the transactions to the database.
Syntax:
Commit;
For example:
DELETE FROM Students WHERE RollNo =25; COMMIT;
Rollback
Rollback command allows you to undo transactions that have not already been saved to the database.
Syntax:
ROLLBACK;
Example:
DELETE FROM Students WHERE RollNo =25;
SAVEPOINT
This command helps you to sets a savepoint within a transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;
Example:
SAVEPOINT RollNo;
What is DQL?
Data Query Language (DQL) is used to fetch the data from the database. It uses only one command:
SELECT:
This command helps you to select the attribute based on the condition described by the WHERE clause.
Syntax:
SELECT expressions FROM TABLES WHERE conditions;
For example:
SELECT FirstName FROM Student WHERE RollNo > 15;
Summary:
- SQL is a database language designed for the retrieval and management of data in a relational database.
- It helps users to access data in the RDBMS system
- In the year 1974, the term Structured Query Language appeared
- Five types of SQL queries are 1) Data Definition Language (DDL) 2) Data Manipulation Language (DML) 3) Data Control Language(DCL) 4) Transaction Control Language(TCL) and, 5) Data Query Language (DQL)
- Data Definition Language(DDL) helps you to define the database structure or schema.
- Data Manipulation Language (DML) allows you to modify the database instance by inserting, modifying, and deleting its data.
- DCL (Data Control Language) includes commands like GRANT and REVOKE, which are useful to give “rights & permissions.”
- Transaction control language or TCL commands deal with the transaction within the database.
- Data Query Language (DQL) is used to fetch the data from the database.
WHAT IS QUERY WEB SERVICE FROM SQL SERVER?
Web service queries
Query services that are created in the Enterprise Services application and the Object Structures applications can be deployed as web services. To support querying, you must configure enterprise web services to bypass the JMS queues.
A successful response to a query that is run in a web service returns the query result set. If the result set is empty (it contains no records), the XML that is returned in the SOAP body contains the following empty MXPERSONSet tag:
<max:QueryMXPERSONResponse xmlns:max="http://www.ibm.com/maximo"
creationDateTime="2011-04-28T21:49:45"
baseLanguage="EN" transLanguage="EN" messageID="12345"
maximoVersion="7.5" rsStart="1" rsCount="10" rsTotal="10">
</max:MXPERSONSet>
</max:QueryMXPERSONResponse>
If an error occurs, an HTTP response code of 500 is returned, along with a SOAP fault detailing the error message.
Use the following URL for the query web service:
http://hostname:port/meaweb/services/web service name
- The host:port/meaweb is the value of the integration web application URL property.
- The web service name is the name of the web service.
You deploy query enterprise and object structure services as web services using the Web Services Library application.
How To Call A Web Service From SQL Server
Step 1 Create a stored procedure in your SQL Server.
- CREATE proc [dbo].[spHTTPRequest]
- @URI varchar(2000) = ‘http://localhost:55253/’,
- @methodName varchar(50) = ‘Get’,
- @requestBody varchar(8000) = ”,
- @SoapAction varchar(255),
- @UserName nvarchar(100), — Domain\UserName or UserName
- @Password nvarchar(100),
- @responseText varchar(8000) output
- as
- SET NOCOUNT ON
- IF @methodName = ”
- BEGIN
- select FailPoint = ‘Method Name must be set’
- return
- END
- set @responseText = ‘FAILED’
- DECLARE @objectID int
- DECLARE @hResult int
- DECLARE @source varchar(255), @desc varchar(255)
- EXEC @hResult = sp_OACreate ‘MSXML2.ServerXMLHTTP’, @objectID OUT
- IF @hResult <> 0
- BEGIN
- EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
- SELECT hResult = convert(varbinary(4), @hResult),
- source = @source,
- description = @desc,
- FailPoint = ‘Create failed’,
- MedthodName = @methodName
- goto destroy
- return
- END
- — open the destination URI with Specified method
- EXEC @hResult = sp_OAMethod @objectID, ‘open’, null, @methodName, @URI, ‘false’, @UserName, @Password
- IF @hResult <> 0
- BEGIN
- EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
- SELECT hResult = convert(varbinary(4), @hResult),
- source = @source,
- description = @desc,
- FailPoint = ‘Open failed’,
- MedthodName = @methodName
- goto destroy
- return
- END
- — set request headers
- EXEC @hResult = sp_OAMethod @objectID, ‘setRequestHeader’, null, ‘Content-Type’, ‘text/xml;charset=UTF-8’
- IF @hResult <> 0
- BEGIN
- EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
- SELECT hResult = convert(varbinary(4), @hResult),
- source = @source,
- description = @desc,
- FailPoint = ‘SetRequestHeader failed’,
- MedthodName = @methodName
- goto destroy
- return
- END
- — set soap action
- EXEC @hResult = sp_OAMethod @objectID, ‘setRequestHeader’, null, ‘SOAPAction’, @SoapAction
- IF @hResult <> 0
- BEGIN
- EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
- SELECT hResult = convert(varbinary(4), @hResult),
- source = @source,
- description = @desc,
- FailPoint = ‘SetRequestHeader failed’,
- MedthodName = @methodName
- goto destroy
- return
- END
- declare @len int
- set @len = len(@requestBody)
- EXEC @hResult = sp_OAMethod @objectID, ‘setRequestHeader’, null, ‘Content-Length’, @len
- IF @hResult <> 0
- BEGIN
- EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
- SELECT hResult = convert(varbinary(4), @hResult),
- source = @source,
- description = @desc,
- FailPoint = ‘SetRequestHeader failed’,
- MedthodName = @methodName
- goto destroy
- return
- END
- /*
- — if you have headers in a table called RequestHeader you can go through them with this
- DECLARE @HeaderKey varchar(500), @HeaderValue varchar(500)
- DECLARE RequestHeader CURSOR
- LOCAL FAST_FORWARD
- FOR
- SELECT HeaderKey, HeaderValue
- FROM RequestHeaders
- WHERE Method = @methodName
- OPEN RequestHeader
- FETCH NEXT FROM RequestHeader
- INTO @HeaderKey, @HeaderValue
- WHILE @@FETCH_STATUS = 0
- BEGIN
- –select @HeaderKey, @HeaderValue, @methodName
- EXEC @hResult = sp_OAMethod @objectID, ‘setRequestHeader’, null, @HeaderKey, @HeaderValue
- IF @hResult <> 0
- BEGIN
- EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
- SELECT hResult = convert(varbinary(4), @hResult),
- source = @source,
- description = @desc,
- FailPoint = ‘SetRequestHeader failed’,
- MedthodName = @methodName
- goto destroy
- return
- END
- FETCH NEXT FROM RequestHeader
- INTO @HeaderKey, @HeaderValue
- END
- CLOSE RequestHeader
- DEALLOCATE RequestHeader
- */
- — send the request
- EXEC @hResult = sp_OAMethod @objectID, ‘send’, null, @requestBody
- IF @hResult <> 0
- BEGIN
- EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
- SELECT hResult = convert(varbinary(4), @hResult),
- source = @source,
- description = @desc,
- FailPoint = ‘Send failed’,
- MedthodName = @methodName
- goto destroy
- return
- END
- declare @statusText varchar(1000), @status varchar(1000)
- — Get status text
- exec sp_OAGetProperty @objectID, ‘StatusText’, @statusText out
- exec sp_OAGetProperty @objectID, ‘Status’, @status out
- select @status, @statusText, @methodName
- — Get response text
- exec sp_OAGetProperty @objectID, ‘responseText’, @responseText out
- IF @hResult <> 0
- BEGIN
- EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
- SELECT hResult = convert(varbinary(4), @hResult),
- source = @source,
- description = @desc,
- FailPoint = ‘ResponseText failed’,
- MedthodName = @methodName
- goto destroy
- return
- END
- destroy:
- exec sp_OADestroy @objectID
- SET NOCOUNT OFF
- GO
The Stored Procedure takes the following parameters.
- @URI: the URI of the web service
- @MethodName: this would be ‘GET’ or ‘POST’
- @RequestBody: this is the SOAP xml that you want to send
- @SoapAction: this the operation that you want to call on your service
- @UserName: NT UserName if your web service requires authentication
- @Password: the password if using NT Authentication on the web service
- @ResponseText: this is an out parameter that contains the response from the web service
Step 2 Make the setting in SQL for it.
- Use master
- sp_configure ‘show advanced options’, 1
- GO
- RECONFIGURE;
- GO
- sp_configure ‘Ole Automation Procedures’, 1
- GO
- RECONFIGURE;
- GO
- sp_configure ‘show advanced options’, 1
- GO
- RECONFIGURE;
Step 3
Call the stored procedure (Here is a sample call to my service).
- declare @xmlOut varchar(8000)
- Declare @RequestText as varchar(8000);
- set @RequestText=
- ‘<soapenv:Envelope xmlns:soapenv=”http://schemas.xmlsoap.org/soap/envelope/” xmlns:tem=”http://tempuri.org/”>
- <soapenv:Header/>
- <soapenv:Body>
- <tem:CreateOrder>
- <!–Optional:–>
- <tem:OrderRequest>
- <tem:OrderId>200</tem:OrderId>
- <!–Optional:–>
- <tem:OrderName>something</tem:OrderName>
- </tem:OrderRequest>
- </tem:CreateOrder>
- </soapenv:Body>
- </soapenv:Envelope>’
- exec spHTTPRequest
- ‘http://localhost/testwebservices/helloworldservice.asmx’,
- ‘POST’,
- @RequestText,
- ‘http://tempuri.org/CreateOrderForMe’, — this is your SOAPAction:
- ”, ”, @xmlOut out
- select @xmlOut
Advantages of Web Service
The thought of web services created from the development of the Internet. The plan behind a web service is to drive the internet as a value-based instrument as opposed to just a visual apparatus. These application-to-application collaborations are driven by, and based on, existing principles, for example:
- Extensible Markup Language (XML)
- Hypertext Transfer Protocol (HTTP)
- Cleanser
- Widespread Description, Discovery, and Integration (UDDI)
- Web Services Description Language (WSDL)
Here are the advantages of utilizing web services are:
1. Revealing the Existing Function on Framework
A web administration is a managed code that can be remotely called using HTTP; that is, it tends to be started using HTTP inquiries. Web administrations empower you to uncover the handiness of your present code over the framework. At the point when it is uncovered on the framework, other applications can use the handiness of your program.
2. Interoperability
Web service interoperability objectives are to give consistent and programmed associations starting with one programming application then onto the next. Cleanser, WSDL, and UDDI conventions characterize a self-depicting approach to find and call a product application strategy – paying little mind to area or stage. Information is marshaled into XML solicitation and reaction reports and moved between programming bundles utilizing HTTP or message-based conventions. Interoperability issues creep in at the disclosure, definition, and solicitation/reaction instruments.
- Web administrations empower various applications to banter with one another and share information and administrations among themselves. A wide range of uses can converse with one another. So as opposed to composing explicit code that explicit applications must comprehend, you would now be able to compose nonexclusive code that all applications can comprehend.
- When looked with a test changing frameworks designs, heritage frameworks, a mixed drink of programming dialects that make up frameworks that should be coordinated at that point, web administrations prove to be useful.
- Maybe the most significant advantage of web administrations they give a nonexclusive method for cooperation. Web benefits just need to talk a similar message convention for them to between work. So far, a typical arrangement of norms based specialized techniques that incorporate HTTP, WSDL, SOAP have been created. These make it feasible for web administrations to be stage free.
3. Ordered Protocol
Web administrations use the institutionalized industry-standard show for the correspondence. All the four layers (Service Transport, XML Messaging, Service Description, and Service Discovery layers) use well-described shows in the web organizations show stack. This systematization of show stack gives the business various focal points, for instance, a wide extent of choices, a decline in the cost due to contention, and augmentation in the quality.
4. Ease of Use
Web services are intended to be utilized over the web; that is simply similarly a page is brought, one can get web administration capacity over the web. The ability of web administrations shifts from straightforward data query too complex algorithmic calculations. Thusly when help is utilized to uncover a business rationale, at that point, it can be used without much of a stretch utilized.
5.Send Capacity
Web Services are conveyed over standard Internet advancements. For example, utilizing Apache, Axis2 to give HTTP, WSDL driven administrations. This makes it easy to convey.
6. Agility
This sees the capacity to change. At the point when an undertaking IT framework is streamlined into administrations, new usefulness to address new business requests involves amassing existing administrations. Obviously, a couple of more administrations may need to manufacture, yet in general, it is simpler than re-assembling another framework without any preparation.
7. Quality
Related to reuse, on the grounds that web services advancement approaches enable administrations to be worked by gathering existing administrations, it is consistent to expect that such administrations are now tried with known execution attributes. Consequently, new frameworks will be less carriage.
8. Cost
The expense of growing new frameworks diminishes altogether since such frameworks are amassed from instant web administrations. Such cost decreases convert into benefits on might be passed on to the clients. The clients remain to win from cost cuts, and proficiency got by web administration.
9. Minimal Effort Communication(XML-Based)
Web Services uses XML at data depiction and data transportation layers. Using XML gets rid of any frameworks organization, working system, or stage official. Web Services based applications are significantly between operable application at their inside level.
Conclusion
Ideally, this article has given you an understanding of Web administrations’ capability, especially for settling a ton of the cross-stage availability issues that software engineers and framework creators. Making a Web service includes huge numbers of similar ideas and errands we face when fabricating any sort of application. We characterize the usefulness and logic necessary to create the service.
Drop your comment