Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

SQL Query to Display the Length and First 3 Characters of Ename Column in Emp Table

  • Last Updated : 10 Oct, 2021

To display the length and first three characters of a string, string functions come in handy to do these in SQL. In this article let us see how to display the length and first 3 characters of the Ename column in the Emp table using MSSQL as the server.

To find the length of a string we use the LEN( ) function.

Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course  by GeeksforGeeks.

Syntax:

LEN(Ename)

To find the first n characters of string we use the LEFT() function:



Syntax:

LEFT(Ename , N)

Step 1: Creating a Database

We use the below command to create a database named GeeksforGeeks.

Query:

CREATE DATABASE GeeksforGeeks

Step 2: Using the Database

To use the GeeksforGeeks database use the below command:

Query:



USE GeeksforGeeks;

Step 3: Creating a table

Creating a table Emp with 5 columns using the following SQL query as follows.

CREATE TABLE Emp
(
E_id varchar(20),
Ename varchar(20),
Edept varchar(20),
E_age INT,
E_sex varchar(8)
);

Output:

Step 4: Verifying the database

To view the description of the database using the following SQL query as follows.

Query:

EXEC sp_columns Emp

Output:



Step 5: Inserting data into the table 

Inserting rows into the Emp table using the following SQL query as follows.

Query:

 INSERT INTO Emp VALUES('E00001','JHONNY','BACKEND DEVELOPER',26,'male'),
 ('E00002','DARSHI','MARKETING',27,'male'),
('E00003','JASMINE','FRONTEND DEVELOPER',37,'female'),
('E00004','LILLY','FULL STACK DEVELOPER',47,'female'),
('E00005','RONALD','UI DEVELOPER',26,'male')

Output:

Step 6: Verifying inserted data 

Check the inserted data in the table using the select query as follows.

Query:

SELECT* FROM Emp

Output:

  • Query to Display the Length and First 3 Characters of Ename Column.

Query:

SELECT LEN(Ename) AS LengthofEname,
LEFT(Ename,3) AS FirstThree FROM Emp

Output:

  • Query to Display the Length and Last 3 Characters of Ename Column.

Query:

SELECT LEN(Ename) AS LengthofEname,
RIGHT(Ename,3) AS LastThree FROM Emp

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :