Subscripts
Anonymous contributor
Published Nov 25, 2024
Contribute to Docs
Subscripts are used to access, update or manipulate elements of an array by their position or index.
They provide a concise way to reference particular elements in one-dimensional or multi-dimensional arrays.
Syntax
For a one-dimensional array, the following syntax is used:
array_name[subscript]
array_name
: The name of the array being accessed.subscript
: The index position of the element to be accessed within the array.
Alternatively, for multi-dimensional array the following syntax is used:
array_name[subscript_1][subscript_2]...[subscript_n]
array_name
: The name of the array being accessed.subscript_1, subscript_2, ..., subscript_n
: The index positions for each dimension of the array to access the specific element.
Example
Suppose we have a table students
with column name grades
that stores a multi-dimensional array of test scores:
CREATE TABLE students (id SERIAL PRIMARY KEY,name VARCHAR(100),grades INTEGER[][]);
Insert some data into the table:
INSERT INTO students (name, grades)VALUES('Bryan', ARRAY[[98, 60], [75, 52]]);
If we want to access Bryan’s score, we will run the below query:
SELECT grades[2][2] AS second_subject_scoreFROM studentsWHERE name = 'Bryan';
The above code will return Bryan’s score with the use of subscripts:
second_subject_score----------------------52
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PostgreSQL on Codecademy
- Skill path
Analyze Data with SQL
Learn to analyze data with SQL and prepare for technical interviews.Includes 9 CoursesWith CertificateBeginner Friendly17 hours - Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly90 hours